commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
326ae45949c2ee4f53e9c377582313155d9d0b70
kk/models/base.py
kk/models/base.py
from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class ModifiableModel(models.Model): created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") class Meta: abstract = True
import base64 import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ def generate_id(): t = time.time() * 1000000 b = base64.b32encode(struct.pack(">Q", int(t)).lstrip(b'\x00')).strip(b'=').lower() return b.decode('utf8') class ModifiableModel(models.Model): id = models.CharField(primary_key=True, max_length=100) created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") def save(self, *args, **kwargs): pk_type = self._meta.pk.get_internal_type() if pk_type == 'CharField': if not self.pk: self.pk = generate_id() elif pk_type == 'AutoField': pass else: raise Exception('Unsupported primary key field: %s' % pk_type) super().save(*args, **kwargs) class Meta: abstract = True
Set char primary key. Generate ID.
Set char primary key. Generate ID.
Python
mit
vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,City-of-Helsinki/kerrokantasi,vikoivun/kerrokantasi,stephawe/kerrokantasi
from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class ModifiableModel(models.Model): created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") class Meta: abstract = True Set char primary key. Generate ID.
import base64 import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ def generate_id(): t = time.time() * 1000000 b = base64.b32encode(struct.pack(">Q", int(t)).lstrip(b'\x00')).strip(b'=').lower() return b.decode('utf8') class ModifiableModel(models.Model): id = models.CharField(primary_key=True, max_length=100) created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") def save(self, *args, **kwargs): pk_type = self._meta.pk.get_internal_type() if pk_type == 'CharField': if not self.pk: self.pk = generate_id() elif pk_type == 'AutoField': pass else: raise Exception('Unsupported primary key field: %s' % pk_type) super().save(*args, **kwargs) class Meta: abstract = True
<commit_before> from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class ModifiableModel(models.Model): created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") class Meta: abstract = True <commit_msg>Set char primary key. Generate ID.<commit_after>
import base64 import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ def generate_id(): t = time.time() * 1000000 b = base64.b32encode(struct.pack(">Q", int(t)).lstrip(b'\x00')).strip(b'=').lower() return b.decode('utf8') class ModifiableModel(models.Model): id = models.CharField(primary_key=True, max_length=100) created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") def save(self, *args, **kwargs): pk_type = self._meta.pk.get_internal_type() if pk_type == 'CharField': if not self.pk: self.pk = generate_id() elif pk_type == 'AutoField': pass else: raise Exception('Unsupported primary key field: %s' % pk_type) super().save(*args, **kwargs) class Meta: abstract = True
from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class ModifiableModel(models.Model): created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") class Meta: abstract = True Set char primary key. Generate ID.import base64 import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ def generate_id(): t = time.time() * 1000000 b = base64.b32encode(struct.pack(">Q", int(t)).lstrip(b'\x00')).strip(b'=').lower() return b.decode('utf8') class ModifiableModel(models.Model): id = models.CharField(primary_key=True, max_length=100) created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") def save(self, *args, **kwargs): pk_type = self._meta.pk.get_internal_type() if pk_type == 'CharField': if not self.pk: self.pk = generate_id() elif pk_type == 'AutoField': pass else: raise Exception('Unsupported primary key field: %s' % pk_type) super().save(*args, **kwargs) class Meta: abstract = True
<commit_before> from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class ModifiableModel(models.Model): created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") class Meta: abstract = True <commit_msg>Set char primary key. Generate ID.<commit_after>import base64 import struct from django.conf import settings from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ def generate_id(): t = time.time() * 1000000 b = base64.b32encode(struct.pack(">Q", int(t)).lstrip(b'\x00')).strip(b'=').lower() return b.decode('utf8') class ModifiableModel(models.Model): id = models.CharField(primary_key=True, max_length=100) created_at = models.DateTimeField(verbose_name=_('Time of creation'), default=timezone.now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Created by'), null=True, blank=True, related_name="%(class)s_created") modified_at = models.DateTimeField(verbose_name=_('Time of modification'), default=timezone.now) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Modified by'), null=True, blank=True, related_name="%(class)s_modified") def save(self, *args, **kwargs): pk_type = self._meta.pk.get_internal_type() if pk_type == 'CharField': if not self.pk: self.pk = generate_id() elif pk_type == 'AutoField': pass else: raise Exception('Unsupported primary key field: %s' % pk_type) super().save(*args, **kwargs) class Meta: abstract = True
aaf776b94416b63a0da6dfeca6ea04f6fe32d201
systemtests/test_cli.py
systemtests/test_cli.py
import os import os.path from scripttest import TestFileEnvironment def test_persists_data(): env = TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content'
import os import os.path import scripttest def test_persists_data(): env = scripttest.TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content'
Fix number of skipped tests when running pytest.
Fix number of skipped tests when running pytest.
Python
mit
jgosmann/fridge,jgosmann/fridge
import os import os.path from scripttest import TestFileEnvironment def test_persists_data(): env = TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content' Fix number of skipped tests when running pytest.
import os import os.path import scripttest def test_persists_data(): env = scripttest.TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content'
<commit_before>import os import os.path from scripttest import TestFileEnvironment def test_persists_data(): env = TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content' <commit_msg>Fix number of skipped tests when running pytest.<commit_after>
import os import os.path import scripttest def test_persists_data(): env = scripttest.TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content'
import os import os.path from scripttest import TestFileEnvironment def test_persists_data(): env = TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content' Fix number of skipped tests when running pytest.import os import os.path import scripttest def test_persists_data(): env = scripttest.TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content'
<commit_before>import os import os.path from scripttest import TestFileEnvironment def test_persists_data(): env = TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content' <commit_msg>Fix number of skipped tests when running pytest.<commit_after>import os import os.path import scripttest def test_persists_data(): env = scripttest.TestFileEnvironment() # FIXME path to fridge script should be determined in some other way env.run('../../bin/fridge', 'init') env.writefile('somefile', 'with some content') env.run('../../bin/fridge', 'commit') os.unlink(os.path.join(env.base_path, 'somefile')) result = env.run('../../bin/fridge', 'checkout', 'somefile') assert result.files_created['somefile'].bytes == 'with some content'
b21f540ca7b53aeb569f7034de41da0dc4dd7b03
__init__.py
__init__.py
from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config("./template_values.ini")
import os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * _script_path = os.path.abspath(__file__) _script_path = os.path.split(_script_path)[0] config_path = os.path.join(_script_path, "template_values.ini") (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config(config_path)
Read the configuration file upon import
Read the configuration file upon import
Python
mit
bbayles/vod_metadata
from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config("./template_values.ini")Read the configuration file upon import
import os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * _script_path = os.path.abspath(__file__) _script_path = os.path.split(_script_path)[0] config_path = os.path.join(_script_path, "template_values.ini") (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config(config_path)
<commit_before>from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config("./template_values.ini")<commit_msg>Read the configuration file upon import<commit_after>
import os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * _script_path = os.path.abspath(__file__) _script_path = os.path.split(_script_path)[0] config_path = os.path.join(_script_path, "template_values.ini") (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config(config_path)
from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config("./template_values.ini")Read the configuration file upon importimport os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * _script_path = os.path.abspath(__file__) _script_path = os.path.split(_script_path)[0] config_path = os.path.join(_script_path, "template_values.ini") (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config(config_path)
<commit_before>from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config("./template_values.ini")<commit_msg>Read the configuration file upon import<commit_after>import os.path from vod_metadata.md5_checksum import * from vod_metadata.media_info import * from vod_metadata.parse_config import * from vod_metadata.VodPackage import * _script_path = os.path.abspath(__file__) _script_path = os.path.split(_script_path)[0] config_path = os.path.join(_script_path, "template_values.ini") (extensions, MediaInfo_path, product, provider_id, prefix, title_category, provider, ecn_2009) = parse_config(config_path)
f691b8d997327a09824881810cf1edaeb53d7579
telemetry/telemetry/internal/backends/app_backend.py
telemetry/telemetry/internal/backends/app_backend.py
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def __del__(self): self.Close() def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError
Remove custom destructor from AppBackend
[Telemetry] Remove custom destructor from AppBackend Closing the backend in the destructor is 1) Redundant since the backend is being closed from Browser.close() 2) Dangerous since it can happen at any moment due to garbage collection and cause deadlocks in tracing code (see the bug). Bug: chromium:1227504 Change-Id: I518eb7153c8929117715834b60bc08c413883866 Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/3015685 Auto-Submit: Mikhail Khokhlov <26a5474f563e73cb4d4e9a12e954c50f60aae4c8@google.com> Reviewed-by: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com> Commit-Queue: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com>
Python
bsd-3-clause
catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def __del__(self): self.Close() def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError [Telemetry] Remove custom destructor from AppBackend Closing the backend in the destructor is 1) Redundant since the backend is being closed from Browser.close() 2) Dangerous since it can happen at any moment due to garbage collection and cause deadlocks in tracing code (see the bug). Bug: chromium:1227504 Change-Id: I518eb7153c8929117715834b60bc08c413883866 Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/3015685 Auto-Submit: Mikhail Khokhlov <26a5474f563e73cb4d4e9a12e954c50f60aae4c8@google.com> Reviewed-by: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com> Commit-Queue: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com>
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError
<commit_before># Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def __del__(self): self.Close() def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError <commit_msg>[Telemetry] Remove custom destructor from AppBackend Closing the backend in the destructor is 1) Redundant since the backend is being closed from Browser.close() 2) Dangerous since it can happen at any moment due to garbage collection and cause deadlocks in tracing code (see the bug). Bug: chromium:1227504 Change-Id: I518eb7153c8929117715834b60bc08c413883866 Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/3015685 Auto-Submit: Mikhail Khokhlov <26a5474f563e73cb4d4e9a12e954c50f60aae4c8@google.com> Reviewed-by: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com> Commit-Queue: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com><commit_after>
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def __del__(self): self.Close() def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError [Telemetry] Remove custom destructor from AppBackend Closing the backend in the destructor is 1) Redundant since the backend is being closed from Browser.close() 2) Dangerous since it can happen at any moment due to garbage collection and cause deadlocks in tracing code (see the bug). Bug: chromium:1227504 Change-Id: I518eb7153c8929117715834b60bc08c413883866 Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/3015685 Auto-Submit: Mikhail Khokhlov <26a5474f563e73cb4d4e9a12e954c50f60aae4c8@google.com> Reviewed-by: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com> Commit-Queue: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com># Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError
<commit_before># Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def __del__(self): self.Close() def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError <commit_msg>[Telemetry] Remove custom destructor from AppBackend Closing the backend in the destructor is 1) Redundant since the backend is being closed from Browser.close() 2) Dangerous since it can happen at any moment due to garbage collection and cause deadlocks in tracing code (see the bug). Bug: chromium:1227504 Change-Id: I518eb7153c8929117715834b60bc08c413883866 Reviewed-on: https://chromium-review.googlesource.com/c/catapult/+/3015685 Auto-Submit: Mikhail Khokhlov <26a5474f563e73cb4d4e9a12e954c50f60aae4c8@google.com> Reviewed-by: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com> Commit-Queue: Wenbin Zhang <45ad8a1ff616a38a2202fd35571df81897c5f14f@google.com><commit_after># Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import six from py_trace_event import trace_event class AppBackend(six.with_metaclass(trace_event.TracedMetaClass, object)): def __init__(self, app_type, platform_backend): super(AppBackend, self).__init__() self._app = None self._app_type = app_type self._platform_backend = platform_backend def SetApp(self, app): self._app = app @property def app(self): return self._app @property def app_type(self): return self._app_type @property def platform_backend(self): return self._platform_backend def Foreground(self): # TODO(catapult:#2194): Remove the unnecessary pass below when the method # has been implemented on all concrete subclasses. pass # pylint: disable=unnecessary-pass raise NotImplementedError def Background(self): raise NotImplementedError def Close(self): raise NotImplementedError def IsAppRunning(self): raise NotImplementedError
1fe88c1a619211a93297e1081133017ff2ef0370
scenario/__main__.py
scenario/__main__.py
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main()
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main()
Update command line usage with scenario
Update command line usage with scenario
Python
mit
shlomihod/scenario,shlomihod/scenario,shlomihod/scenario
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main() Update command line usage with scenario
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main()
<commit_before>import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main() <commit_msg>Update command line usage with scenario<commit_after>
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main()
import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main() Update command line usage with scenarioimport sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main()
<commit_before>import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: python -m foo <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main() <commit_msg>Update command line usage with scenario<commit_after>import sys from scenario import run_scenario def main(args=None): if args is None: args = sys.argv[1:] assert len(args) == 2, 'Usage: scenario <executable> <scenario>' executable_path = args[0] scenario_path = args[1] run_scenario(executable_path, scenario_path) if __name__ == '__main__': main()
c85631d77cd25de520688666a3d0e72537e482eb
acquisition_record.py
acquisition_record.py
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. Test of github push. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass
Test of github push from Eclipse.
Test of github push from Eclipse.
Python
apache-2.0
ama-jharrison/agdc,GeoscienceAustralia/agdc,jeremyh/agdc,sixy6e/agdc,jeremyh/agdc,smr547/agdc,smr547/agdc,alex-ip/agdc,sixy6e/agdc,GeoscienceAustralia/agdc,alex-ip/agdc,ama-jharrison/agdc
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass Test of github push from Eclipse.
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. Test of github push. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass
<commit_before>""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass <commit_msg>Test of github push from Eclipse.<commit_after>
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. Test of github push. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass
""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass Test of github push from Eclipse.""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. Test of github push. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass
<commit_before>""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass <commit_msg>Test of github push from Eclipse.<commit_after>""" AcquisitionRecord: database interface class. These classes provide an interface between the database and the top-level ingest algorithm (AbstractIngester and its subclasses). They also provide the implementation of the database and tile store side of the ingest process. They are expected to be independent of the structure of any particular dataset, but will change if the database schema or tile store format changes. Test of github push. """ import logging # Set up logger. LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.INFO) class AcquisitionRecord(object): """AcquisitionRecord database interface class.""" def __init__(self, collection, acquisition_id): self.collection = collection self.acquisition_id = acquisition_id def create_dataset_record(self, dataset): pass
65734594816b158bdf08b93244795b5dcc8626ba
scrapy/core/downloader/handlers/__init__.py
scrapy/core/downloader/handlers/__init__.py
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middlware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close()
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middleware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close()
Fix minor typo in DownloaderHandlers comment
Fix minor typo in DownloaderHandlers comment
Python
bsd-3-clause
heamon7/scrapy,redapple/scrapy,Partoo/scrapy,ArturGaspar/scrapy,fpy171/scrapy,AaronTao1990/scrapy,fafaman/scrapy,agreen/scrapy,aivarsk/scrapy,Bourneer/scrapy,w495/scrapy,1yvT0s/scrapy,curita/scrapy,dhenyjarasandy/scrapy,rdowinton/scrapy,Allianzcortex/scrapy,zackslash/scrapy,ashishnerkar1/scrapy,AaronTao1990/scrapy,kmike/scrapy,pfctdayelise/scrapy,olorz/scrapy,KublaikhanGeek/scrapy,agreen/scrapy,tliber/scrapy,kazitanvirahsan/scrapy,farhan0581/scrapy,arush0311/scrapy,heamon7/scrapy,starrify/scrapy,scrapy/scrapy,hwsyy/scrapy,CodeJuan/scrapy,kashyap32/scrapy,jc0n/scrapy,raphaelfruneaux/scrapy,rolando/scrapy,beni55/scrapy,TarasRudnyk/scrapy,hectoruelo/scrapy,lacrazyboy/scrapy,codebhendi/scrapy,rootAvish/scrapy,github-account-because-they-want-it/scrapy,csalazar/scrapy,huoxudong125/scrapy,Geeglee/scrapy,darkrho/scrapy-scrapy,shaform/scrapy,liyy7/scrapy,barraponto/scrapy,foromer4/scrapy,fontenele/scrapy,crasker/scrapy,raphaelfruneaux/scrapy,farhan0581/scrapy,cyberplant/scrapy,wangjun/scrapy,yusofm/scrapy,yarikoptic/scrapy,github-account-because-they-want-it/scrapy,scrapy/scrapy,nowopen/scrapy,kmike/scrapy,URXtech/scrapy,Chenmxs/scrapy,CodeJuan/scrapy,GregoryVigoTorres/scrapy,pombredanne/scrapy,kimimj/scrapy,zjuwangg/scrapy,tagatac/scrapy,z-fork/scrapy,redapple/scrapy,jiezhu2007/scrapy,elacuesta/scrapy,zhangtao11/scrapy,Djlavoy/scrapy,cyrixhero/scrapy,gbirke/scrapy,hbwzhsh/scrapy,Allianzcortex/scrapy,umrashrf/scrapy,rdowinton/scrapy,jorik041/scrapy,sardok/scrapy,ashishnerkar1/scrapy,ArturGaspar/scrapy,darkrho/scrapy-scrapy,avtoritet/scrapy,rdowinton/scrapy,dhenyjarasandy/scrapy,nguyenhongson03/scrapy,cleydson/scrapy,Parlin-Galanodel/scrapy,cyberplant/scrapy,WilliamKinaan/scrapy,Preetwinder/scrapy,Geeglee/scrapy,dgillis/scrapy,nowopen/scrapy,dacjames/scrapy,Ryezhang/scrapy,hyrole/scrapy,yidongliu/scrapy,Allianzcortex/scrapy,Cnfc19932/scrapy,joshlk/scrapy,kashyap32/scrapy,johnardavies/scrapy,eLRuLL/scrapy,codebhendi/scrapy,foromer4/scrapy,TarasRudnyk/scrapy,scorphus/scrapy,godfreyy/scrapy,jamesblunt/scrapy,mgedmin/scrapy,rahulsharma1991/scrapy,cleydson/scrapy,TarasRudnyk/scrapy,IvanGavran/scrapy,webmakin/scrapy,olafdietsche/scrapy,heamon7/scrapy,Bourneer/scrapy,jdemaeyer/scrapy,pablohoffman/scrapy,zhangtao11/scrapy,livepy/scrapy,nguyenhongson03/scrapy,mlyundin/scrapy,Parlin-Galanodel/scrapy,moraesnicol/scrapy,CENDARI/scrapy,dacjames/scrapy,kazitanvirahsan/scrapy,arush0311/scrapy,jiezhu2007/scrapy,curita/scrapy,ssh-odoo/scrapy,fontenele/scrapy,eLRuLL/scrapy,JacobStevenR/scrapy,yarikoptic/scrapy,Adai0808/scrapy-1,pawelmhm/scrapy,beni55/scrapy,rolando-contrib/scrapy,ramiro/scrapy,olorz/scrapy,rootAvish/scrapy,Lucifer-Kim/scrapy,Slater-Victoroff/scrapy,mlyundin/scrapy,smaty1/scrapy,ramiro/scrapy,OpenWhere/scrapy,lacrazyboy/scrapy,wenyu1001/scrapy,gbirke/scrapy,scrapy/scrapy,stenskjaer/scrapy,coderabhishek/scrapy,avtoritet/scrapy,tliber/scrapy,irwinlove/scrapy,Cnfc19932/scrapy,KublaikhanGeek/scrapy,carlosp420/scrapy,finfish/scrapy,jorik041/scrapy,agusc/scrapy,ssh-odoo/scrapy,stenskjaer/scrapy,IvanGavran/scrapy,carlosp420/scrapy,Preetwinder/scrapy,cyberplant/scrapy,CodeJuan/scrapy,wujuguang/scrapy,kalessin/scrapy,crasker/scrapy,zorojean/scrapy,JacobStevenR/scrapy,nguyenhongson03/scrapy,Chenmxs/scrapy,eliasdorneles/scrapy,starrify/scrapy,yarikoptic/scrapy,tntC4stl3/scrapy,legendtkl/scrapy,OpenWhere/scrapy,nfunato/scrapy,legendtkl/scrapy,kalessin/scrapy,finfish/scrapy,hwsyy/scrapy,devGregA/scrapy,ssh-odoo/scrapy,olafdietsche/scrapy,yusofm/scrapy,lacrazyboy/scrapy,godfreyy/scrapy,rklabs/scrapy,Adai0808/scrapy-1,nfunato/scrapy,IvanGavran/scrapy,webmakin/scrapy,dracony/scrapy,wangjun/scrapy,Geeglee/scrapy,elijah513/scrapy,ENjOyAbLE1991/scrapy,fafaman/scrapy,z-fork/scrapy,ramiro/scrapy,snowdream1314/scrapy,joshlk/scrapy,scorphus/scrapy,haiiiiiyun/scrapy,songfj/scrapy,ylcolala/scrapy,pombredanne/scrapy,elijah513/scrapy,zorojean/scrapy,Zephor5/scrapy,redapple/scrapy,rolando-contrib/scrapy,csalazar/scrapy,nikgr95/scrapy,devGregA/scrapy,kimimj/scrapy,ssteo/scrapy,huoxudong125/scrapy,cyrixhero/scrapy,snowdream1314/scrapy,Djlavoy/scrapy,umrashrf/scrapy,JacobStevenR/scrapy,hyrole/scrapy,johnardavies/scrapy,xiao26/scrapy,amboxer21/scrapy,taito/scrapy,haiiiiiyun/scrapy,CENDARI/scrapy,profjrr/scrapy,Digenis/scrapy,codebhendi/scrapy,wzyuliyang/scrapy,cursesun/scrapy,github-account-because-they-want-it/scrapy,pranjalpatil/scrapy,Chenmxs/scrapy,mgedmin/scrapy,legendtkl/scrapy,joshlk/scrapy,godfreyy/scrapy,haiiiiiyun/scrapy,amboxer21/scrapy,dracony/scrapy,Bourneer/scrapy,ENjOyAbLE1991/scrapy,Preetwinder/scrapy,nikgr95/scrapy,Zephor5/scrapy,pfctdayelise/scrapy,liyy7/scrapy,hansenDise/scrapy,snowdream1314/scrapy,dangra/scrapy,jeffreyjinfeng/scrapy,Slater-Victoroff/scrapy,WilliamKinaan/scrapy,profjrr/scrapy,rahulsharma1991/scrapy,bmess/scrapy,taito/scrapy,URXtech/scrapy,zjuwangg/scrapy,yidongliu/scrapy,eLRuLL/scrapy,chekunkov/scrapy,hbwzhsh/scrapy,fqul/scrapy,fqul/scrapy,z-fork/scrapy,finfish/scrapy,stenskjaer/scrapy,darkrho/scrapy-scrapy,kashyap32/scrapy,Timeship/scrapy,tntC4stl3/scrapy,pranjalpatil/scrapy,livepy/scrapy,agusc/scrapy,yidongliu/scrapy,fpy171/scrapy,xiao26/scrapy,devGregA/scrapy,Digenis/scrapy,tagatac/scrapy,pranjalpatil/scrapy,elacuesta/scrapy,wujuguang/scrapy,cyrixhero/scrapy,OpenWhere/scrapy,olafdietsche/scrapy,aivarsk/scrapy,ylcolala/scrapy,Parlin-Galanodel/scrapy,jc0n/scrapy,nowopen/scrapy,kalessin/scrapy,wzyuliyang/scrapy,hectoruelo/scrapy,webmakin/scrapy,farhan0581/scrapy,barraponto/scrapy,nikgr95/scrapy,hansenDise/scrapy,yusofm/scrapy,bmess/scrapy,irwinlove/scrapy,livepy/scrapy,starrify/scrapy,sigma-random/scrapy,dangra/scrapy,rolando/scrapy,1yvT0s/scrapy,hbwzhsh/scrapy,dacjames/scrapy,URXtech/scrapy,CENDARI/scrapy,Lucifer-Kim/scrapy,beni55/scrapy,umrashrf/scrapy,rootAvish/scrapy,smaty1/scrapy,hyrole/scrapy,mgedmin/scrapy,ssteo/scrapy,dangra/scrapy,Timeship/scrapy,KublaikhanGeek/scrapy,sigma-random/scrapy,mlyundin/scrapy,irwinlove/scrapy,coderabhishek/scrapy,cursesun/scrapy,Ryezhang/scrapy,Digenis/scrapy,dhenyjarasandy/scrapy,elacuesta/scrapy,rklabs/scrapy,rolando-contrib/scrapy,Cnfc19932/scrapy,Slater-Victoroff/scrapy,profjrr/scrapy,AaronTao1990/scrapy,jdemaeyer/scrapy,elijah513/scrapy,Ryezhang/scrapy,famorted/scrapy,Partoo/scrapy,pawelmhm/scrapy,Zephor5/scrapy,liyy7/scrapy,csalazar/scrapy,wenyu1001/scrapy,dgillis/scrapy,eliasdorneles/scrapy,hansenDise/scrapy,crasker/scrapy,raphaelfruneaux/scrapy,smaty1/scrapy,songfj/scrapy,1yvT0s/scrapy,aivarsk/scrapy,Partoo/scrapy,kazitanvirahsan/scrapy,carlosp420/scrapy,fafaman/scrapy,hwsyy/scrapy,olorz/scrapy,wenyu1001/scrapy,ENjOyAbLE1991/scrapy,avtoritet/scrapy,Timeship/scrapy,chekunkov/scrapy,amboxer21/scrapy,kimimj/scrapy,pombredanne/scrapy,dracony/scrapy,fqul/scrapy,tliber/scrapy,WilliamKinaan/scrapy,fontenele/scrapy,pfctdayelise/scrapy,rahulsharma1991/scrapy,Lucifer-Kim/scrapy,fpy171/scrapy,shaform/scrapy,jeffreyjinfeng/scrapy,w495/scrapy,jdemaeyer/scrapy,jiezhu2007/scrapy,zhangtao11/scrapy,ylcolala/scrapy,famorted/scrapy,rolando/scrapy,bmess/scrapy,pawelmhm/scrapy,wangjun/scrapy,YeelerG/scrapy,GregoryVigoTorres/scrapy,wujuguang/scrapy,scorphus/scrapy,hectoruelo/scrapy,w495/scrapy,agreen/scrapy,tntC4stl3/scrapy,YeelerG/scrapy,chekunkov/scrapy,Adai0808/scrapy-1,taito/scrapy,zackslash/scrapy,jorik041/scrapy,pablohoffman/scrapy,zorojean/scrapy,cleydson/scrapy,kmike/scrapy,jc0n/scrapy,zjuwangg/scrapy,dgillis/scrapy,pablohoffman/scrapy,ArturGaspar/scrapy,tagatac/scrapy,arush0311/scrapy,eliasdorneles/scrapy,xiao26/scrapy,agusc/scrapy,johnardavies/scrapy,sardok/scrapy,moraesnicol/scrapy,ssteo/scrapy,wzyuliyang/scrapy,songfj/scrapy,foromer4/scrapy,famorted/scrapy,rklabs/scrapy,YeelerG/scrapy,coderabhishek/scrapy,zackslash/scrapy,curita/scrapy,barraponto/scrapy,GregoryVigoTorres/scrapy,moraesnicol/scrapy,cursesun/scrapy,jeffreyjinfeng/scrapy,nfunato/scrapy,Djlavoy/scrapy,jamesblunt/scrapy,huoxudong125/scrapy,shaform/scrapy
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middlware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close() Fix minor typo in DownloaderHandlers comment
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middleware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close()
<commit_before>"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middlware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close() <commit_msg>Fix minor typo in DownloaderHandlers comment<commit_after>
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middleware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close()
"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middlware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close() Fix minor typo in DownloaderHandlers comment"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middleware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close()
<commit_before>"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middlware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close() <commit_msg>Fix minor typo in DownloaderHandlers comment<commit_after>"""Download handlers for different schemes""" from twisted.internet import defer from scrapy.exceptions import NotSupported, NotConfigured from scrapy.utils.httpobj import urlparse_cached from scrapy.utils.misc import load_object from scrapy import signals class DownloadHandlers(object): def __init__(self, crawler): self._handlers = {} self._notconfigured = {} handlers = crawler.settings.get('DOWNLOAD_HANDLERS_BASE') handlers.update(crawler.settings.get('DOWNLOAD_HANDLERS', {})) for scheme, clspath in handlers.iteritems(): # Allow to disable a handler just like any other # component (extension, middleware, etc). if clspath is None: continue cls = load_object(clspath) try: dh = cls(crawler.settings) except NotConfigured as ex: self._notconfigured[scheme] = str(ex) else: self._handlers[scheme] = dh crawler.signals.connect(self._close, signals.engine_stopped) def download_request(self, request, spider): scheme = urlparse_cached(request).scheme try: handler = self._handlers[scheme].download_request except KeyError: msg = self._notconfigured.get(scheme, \ 'no handler available for that scheme') raise NotSupported("Unsupported URL scheme '%s': %s" % (scheme, msg)) return handler(request, spider) @defer.inlineCallbacks def _close(self, *_a, **_kw): for dh in self._handlers.values(): if hasattr(dh, 'close'): yield dh.close()
d6bfc8be7944bd8495a21d9db065990148e6c466
tests/template_error.py
tests/template_error.py
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): print "Context:" for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): six.print_("Context:") for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
Fix test incompatibility with Python 3 versions
Fix test incompatibility with Python 3 versions Replaced 'print' instruction with call of a 'six' package's implementation compatible with Python 2 as well as Python 3.
Python
lgpl-2.1
elapouya/python-docx-template
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): print "Context:" for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80) Fix test incompatibility with Python 3 versions Replaced 'print' instruction with call of a 'six' package's implementation compatible with Python 2 as well as Python 3.
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): six.print_("Context:") for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
<commit_before>from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): print "Context:" for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80) <commit_msg>Fix test incompatibility with Python 3 versions Replaced 'print' instruction with call of a 'six' package's implementation compatible with Python 2 as well as Python 3.<commit_after>
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): six.print_("Context:") for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): print "Context:" for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80) Fix test incompatibility with Python 3 versions Replaced 'print' instruction with call of a 'six' package's implementation compatible with Python 2 as well as Python 3.from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): six.print_("Context:") for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
<commit_before>from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): print "Context:" for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80) <commit_msg>Fix test incompatibility with Python 3 versions Replaced 'print' instruction with call of a 'six' package's implementation compatible with Python 2 as well as Python 3.<commit_after>from docxtpl import DocxTemplate, RichText from jinja2.exceptions import TemplateError import six six.print_('=' * 80) six.print_("Generating template error for testing (so it is safe to ignore) :") six.print_('.' * 80) try: tpl = DocxTemplate('test_files/template_error_tpl.docx') tpl.render({ 'test_variable' : 'test variable value' }) except TemplateError as the_error: six.print_(six.text_type(the_error)) if hasattr(the_error, 'docx_context'): six.print_("Context:") for line in the_error.docx_context: six.print_(line) tpl.save('test_files/template_error.docx') six.print_('.' * 80) six.print_(" End of TemplateError Test ") six.print_('=' * 80)
6403229da220fddac236a8e3ccf061446c37e27c
auditlog/__openerp__.py
auditlog/__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
Add OCA as author of OCA addons
Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
Python
agpl-3.0
Vauxoo/server-tools,Vauxoo/server-tools,Vauxoo/server-tools
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
<commit_before># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } <commit_msg>Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.<commit_after>
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
<commit_before># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } <commit_msg>Add OCA as author of OCA addons In order to get visibility on https://www.odoo.com/apps the OCA board has decided to add the OCA as author of all the addons maintained as part of the association.<commit_after># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>). # # 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/>. # ############################################################################## { 'name': "Audit Log", 'version': "1.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'views/auditlog_view.xml', ], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
33394f4081880c2718f1c017fb90588628c2bfcc
tests/test_extension.py
tests/test_extension.py
import unittest import mock from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = true', config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn('username', schema) self.assertIn('password', schema) self.assertIn('bitrate', schema) self.assertIn('timeout', schema) self.assertIn('cache_dir', schema) def test_setup(self): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
import mock from mopidy_spotify import Extension, backend as backend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[spotify]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert 'username' in schema assert 'password' in schema assert 'bitrate' in schema assert 'timeout' in schema assert 'cache_dir' in schema def test_setup(): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
Convert extension tests to pytest syntax
tests: Convert extension tests to pytest syntax
Python
apache-2.0
jodal/mopidy-spotify,kingosticks/mopidy-spotify,mopidy/mopidy-spotify
import unittest import mock from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = true', config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn('username', schema) self.assertIn('password', schema) self.assertIn('bitrate', schema) self.assertIn('timeout', schema) self.assertIn('cache_dir', schema) def test_setup(self): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend) tests: Convert extension tests to pytest syntax
import mock from mopidy_spotify import Extension, backend as backend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[spotify]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert 'username' in schema assert 'password' in schema assert 'bitrate' in schema assert 'timeout' in schema assert 'cache_dir' in schema def test_setup(): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
<commit_before>import unittest import mock from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = true', config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn('username', schema) self.assertIn('password', schema) self.assertIn('bitrate', schema) self.assertIn('timeout', schema) self.assertIn('cache_dir', schema) def test_setup(self): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend) <commit_msg>tests: Convert extension tests to pytest syntax<commit_after>
import mock from mopidy_spotify import Extension, backend as backend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[spotify]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert 'username' in schema assert 'password' in schema assert 'bitrate' in schema assert 'timeout' in schema assert 'cache_dir' in schema def test_setup(): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
import unittest import mock from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = true', config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn('username', schema) self.assertIn('password', schema) self.assertIn('bitrate', schema) self.assertIn('timeout', schema) self.assertIn('cache_dir', schema) def test_setup(self): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend) tests: Convert extension tests to pytest syntaximport mock from mopidy_spotify import Extension, backend as backend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[spotify]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert 'username' in schema assert 'password' in schema assert 'bitrate' in schema assert 'timeout' in schema assert 'cache_dir' in schema def test_setup(): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
<commit_before>import unittest import mock from mopidy_spotify import Extension, backend as backend_lib class ExtensionTest(unittest.TestCase): def test_get_default_config(self): ext = Extension() config = ext.get_default_config() self.assertIn('[spotify]', config) self.assertIn('enabled = true', config) def test_get_config_schema(self): ext = Extension() schema = ext.get_config_schema() self.assertIn('username', schema) self.assertIn('password', schema) self.assertIn('bitrate', schema) self.assertIn('timeout', schema) self.assertIn('cache_dir', schema) def test_setup(self): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend) <commit_msg>tests: Convert extension tests to pytest syntax<commit_after>import mock from mopidy_spotify import Extension, backend as backend_lib def test_get_default_config(): ext = Extension() config = ext.get_default_config() assert '[spotify]' in config assert 'enabled = true' in config def test_get_config_schema(): ext = Extension() schema = ext.get_config_schema() assert 'username' in schema assert 'password' in schema assert 'bitrate' in schema assert 'timeout' in schema assert 'cache_dir' in schema def test_setup(): registry = mock.Mock() ext = Extension() ext.setup(registry) registry.add.assert_called_with('backend', backend_lib.SpotifyBackend)
69d2620ee64d367331edcf0260c73034384aae8e
subprocrunner/retry.py
subprocrunner/retry.py
import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
import time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter self.__quiet = quiet if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method and not self.__quiet: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
Add quiet mode support for Retry
Add quiet mode support for Retry
Python
mit
thombashi/subprocrunner,thombashi/subprocrunner
import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration Add quiet mode support for Retry
import time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter self.__quiet = quiet if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method and not self.__quiet: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
<commit_before>import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration <commit_msg>Add quiet mode support for Retry<commit_after>
import time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter self.__quiet = quiet if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method and not self.__quiet: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration Add quiet mode support for Retryimport time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter self.__quiet = quiet if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method and not self.__quiet: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
<commit_before>import time from random import uniform from typing import Callable, Optional class Retry: def __init__(self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration <commit_msg>Add quiet mode support for Retry<commit_after>import time from random import uniform from typing import Callable, Optional class Retry: def __init__( self, total: int = 3, backoff_factor: float = 0.2, jitter: float = 0.2, quiet: bool = False ) -> None: self.total = total self.__backoff_factor = backoff_factor self.__jitter = jitter self.__quiet = quiet if self.total <= 0: raise ValueError("total must be greater than zero") if self.__backoff_factor <= 0: raise ValueError("backoff_factor must be greater than zero") if self.__jitter <= 0: raise ValueError("jitter must be greater than zero") def calc_backoff_time(self, attempt: int) -> float: sleep_duration = self.__backoff_factor * (2 ** max(0, attempt - 1)) sleep_duration += uniform(0.5 * self.__jitter, 1.5 * self.__jitter) return sleep_duration def sleep_before_retry( self, attempt: int, logging_method: Optional[Callable] = None, retry_target: Optional[str] = None, ) -> float: sleep_duration = self.calc_backoff_time(attempt) if logging_method and not self.__quiet: if retry_target: msg = "Retrying '{}' in ".format(retry_target) else: msg = "Retrying in " msg += "{:.2f} seconds ... (attempt={})".format(sleep_duration, attempt) logging_method(msg) time.sleep(sleep_duration) return sleep_duration
d676065cb9f137c5feb18b125d0d30dfae4e0b65
Dice.py
Dice.py
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face())
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
Add get dice roll function
Add get dice roll function
Python
mit
achyutreddy24/DiceGame
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) Add get dice roll function
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
<commit_before>import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) <commit_msg>Add get dice roll function<commit_after>
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) Add get dice roll functionimport random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
<commit_before>import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) <commit_msg>Add get dice roll function<commit_after>import random class Die(object): def __init__(self, sides = 6): self.sides = sides self.held = False self.die_face = 1 def change_held(self, held): self.held = held def roll_die(self): if (self.held == False): self.die_face = random.randint(1, self.sides) else: pass def get_die_face(self): return self.die_face class DiceBag(object): def __init__(self): self.dice = [] self.dice_roll = [] def add_die_obj(self, die_obj): self.dice.append(die_obj) def remove_die(self, die_obj): self.dice.remove(die_obj) def remove_die_index(self, index): del self.dice[index] def add_die_notation(self, standard_die_notation): lst_notation = standard_die_notation.split("d") for i in int(lst_notation[0]): die1 = Die(int(lst_notation[1])) self.dice.append(die1) def roll_all(self): for obj in self.dice: obj.roll_die() self.dice_roll.append(obj.get_die_face()) def get_dice_roll(self): return self.dice_roll
8ea896e3290d441e6025822cc4e67b2fd86c3a8c
social_django/compat.py
social_django/compat.py
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
Remove version check in favor of import error check
Remove version check in favor of import error check
Python
bsd-3-clause
python-social-auth/social-app-django,python-social-auth/social-app-django,python-social-auth/social-app-django
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT'] Remove version check in favor of import error check
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
<commit_before># coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT'] <commit_msg>Remove version check in favor of import error check<commit_after>
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT'] Remove version check in favor of import error check# coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
<commit_before># coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse if django.VERSION >= (1, 10): from django.utils.deprecation import MiddlewareMixin else: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT'] <commit_msg>Remove version check in favor of import error check<commit_after># coding=utf-8 import six import django from django.db import models try: from django.urls import reverse except ImportError: from django.core.urlresolvers import reverse try: from django.utils.deprecation import MiddlewareMixin except ImportError: MiddlewareMixin = object def get_rel_model(field): if django.VERSION >= (2, 0): return field.remote_field.model user_model = field.rel.to if isinstance(user_model, six.string_types): app_label, model_name = user_model.split('.') user_model = models.get_model(app_label, model_name) return user_model def get_request_port(request): if django.VERSION >= (1, 9): return request.get_port() host_parts = request.get_host().partition(':') return host_parts[2] or request.META['SERVER_PORT']
342f2a948ba88d6c67c003457923b135234088a0
JSON.py
JSON.py
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): global name dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False
Call global name in getservicesoffline function
Call global name in getservicesoffline function
Python
mit
regexpressyourself/passman
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False Call global name in getservicesoffline function
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): global name dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False
<commit_before>import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False <commit_msg>Call global name in getservicesoffline function<commit_after>
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): global name dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False
import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False Call global name in getservicesoffline functionimport os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): global name dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False
<commit_before>import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False <commit_msg>Call global name in getservicesoffline function<commit_after>import os import json import ast from functions import quit from encryption import encrypt, decrypt global name global key def setOfflineUsername(_name, _key): global name global key name = _name key = _key def getServicesOffline(): global name dir_path = os.path.expanduser("~/.passman") file_path = os.path.expanduser("~/.passman/{}.json".format(name)) if not os.path.isfile(file_path) or \ not os.path.isdir(dir_path): print("No local file found - exiting") quit() with open(file_path) as data_file: data = data_file.read() data = ast.literal_eval(data)['data'] for service in data: service['service'] = decrypt(service['service'], key) service['serviceUserName'] = decrypt(service['serviceUserName'], key) service['servicePassword'] = decrypt(service['servicePassword'], key) service['serviceUrl'] = decrypt(service['serviceUrl'], key) return data def getServiceDataOffline(sname): global name serviceArray = getServicesOffline() for service in serviceArray: if service['service'] == sname: return service return False
a6ae05c13666b83a1f1a8707fe21972bd1f758d9
walltime.py
walltime.py
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') plt.show()
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') t2 = time.time() print 'Running took an extra {} s'.format(t2-t1) print 'For a total of {} s'.format(t2 - t0) plt.show()
Print statements added for profiling
Print statements added for profiling
Python
mit
ibackus/custom_python_packages,trquinn/custom_python_packages
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') plt.show()Print statements added for profiling
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') t2 = time.time() print 'Running took an extra {} s'.format(t2-t1) print 'For a total of {} s'.format(t2 - t0) plt.show()
<commit_before>#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') plt.show()<commit_msg>Print statements added for profiling<commit_after>
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') t2 = time.time() print 'Running took an extra {} s'.format(t2-t1) print 'For a total of {} s'.format(t2 - t0) plt.show()
#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') plt.show()Print statements added for profiling#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') t2 = time.time() print 'Running took an extra {} s'.format(t2-t1) print 'For a total of {} s'.format(t2 - t0) plt.show()
<commit_before>#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import matplotlib.pyplot as plt import numpy as np import datetime import sys if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') plt.show()<commit_msg>Print statements added for profiling<commit_after>#!/usr/bin/env python """ Created on Fri Mar 14 15:25:36 2014 @author: ibackus """ import time t0 = time.time() import matplotlib.pyplot as plt import numpy as np import datetime import sys t1 = time.time() print 'Importing took {} s'.format(t1-t0) if len(sys.argv) < 2: print 'USAGE: walltime filename' else: fname = sys.argv[-1] log_file = np.genfromtxt(fname, comments='#', delimiter=' ') walltime_total = datetime.timedelta(seconds = log_file[:,-1].sum()) walltime_avg = datetime.timedelta(seconds = log_file[:,-1].mean()) print 'Total walltime: ' print str(walltime_total) print 'Average walltime per step:' print str(walltime_avg) plt.plot(log_file[:,-1],'x') t2 = time.time() print 'Running took an extra {} s'.format(t2-t1) print 'For a total of {} s'.format(t2 - t0) plt.show()
692a6d4480e917ff2648bac7ac4975f981e4c571
scripts/util/assignCounty.py
scripts/util/assignCounty.py
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ s.geom && c.the_geom and s.county IS NULL").dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) )
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query(""" select s.id, c.name from stations s, counties c, states t WHERE ST_Contains(c.the_geom, s.geom) and s.geom && c.the_geom and s.county IS NULL and s.state = t.state_abbr and t.state_fips = c.state_fips """).dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) )
Make sure that the county is in the right state even.
Make sure that the county is in the right state even.
Python
mit
akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ s.geom && c.the_geom and s.county IS NULL").dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) ) Make sure that the county is in the right state even.
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query(""" select s.id, c.name from stations s, counties c, states t WHERE ST_Contains(c.the_geom, s.geom) and s.geom && c.the_geom and s.county IS NULL and s.state = t.state_abbr and t.state_fips = c.state_fips """).dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) )
<commit_before> from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ s.geom && c.the_geom and s.county IS NULL").dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) ) <commit_msg>Make sure that the county is in the right state even.<commit_after>
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query(""" select s.id, c.name from stations s, counties c, states t WHERE ST_Contains(c.the_geom, s.geom) and s.geom && c.the_geom and s.county IS NULL and s.state = t.state_abbr and t.state_fips = c.state_fips """).dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) )
from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ s.geom && c.the_geom and s.county IS NULL").dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) ) Make sure that the county is in the right state even. from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query(""" select s.id, c.name from stations s, counties c, states t WHERE ST_Contains(c.the_geom, s.geom) and s.geom && c.the_geom and s.county IS NULL and s.state = t.state_abbr and t.state_fips = c.state_fips """).dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) )
<commit_before> from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query("select s.id, c.name from stations s, counties c WHERE \ s.geom && c.the_geom and s.county IS NULL").dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) ) <commit_msg>Make sure that the county is in the right state even.<commit_after> from pyIEM import iemdb import re i = iemdb.iemdb() mydb = i["mesosite"] rs = mydb.query(""" select s.id, c.name from stations s, counties c, states t WHERE ST_Contains(c.the_geom, s.geom) and s.geom && c.the_geom and s.county IS NULL and s.state = t.state_abbr and t.state_fips = c.state_fips """).dictresult() for i in range(len(rs)): id = rs[i]['id'] cnty = re.sub("'", " ", rs[i]['name']) print id, cnty mydb.query("UPDATE stations SET county = '%s' WHERE id = '%s'" \ % (cnty, id) )
2dbd2d385e821cee9a8bc8414bfba71c8b4dbc06
tests/test_ehrcorral.py
tests/test_ehrcorral.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ import unittest from ehrcorral import ehrcorral class TestEhrcorral(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import unittest from ehrcorral import ehrcorral from faker import Faker fake = Faker() fake.seed(8548) class TestEHRcorral(unittest.TestCase): def setUp(self): profile_fields = ['name', 'birthdate', 'ssn', 'address'] self.herd = [fake.profile(fields=profile_fields) for n in xrange(100)] def test_something(self): pass def tearDown(self): pass
Add test case setUp to generate fake patient info
Add test case setUp to generate fake patient info
Python
isc
nsh87/ehrcorral
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ import unittest from ehrcorral import ehrcorral class TestEhrcorral(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass Add test case setUp to generate fake patient info
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import unittest from ehrcorral import ehrcorral from faker import Faker fake = Faker() fake.seed(8548) class TestEHRcorral(unittest.TestCase): def setUp(self): profile_fields = ['name', 'birthdate', 'ssn', 'address'] self.herd = [fake.profile(fields=profile_fields) for n in xrange(100)] def test_something(self): pass def tearDown(self): pass
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ import unittest from ehrcorral import ehrcorral class TestEhrcorral(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass <commit_msg>Add test case setUp to generate fake patient info<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import unittest from ehrcorral import ehrcorral from faker import Faker fake = Faker() fake.seed(8548) class TestEHRcorral(unittest.TestCase): def setUp(self): profile_fields = ['name', 'birthdate', 'ssn', 'address'] self.herd = [fake.profile(fields=profile_fields) for n in xrange(100)] def test_something(self): pass def tearDown(self): pass
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ import unittest from ehrcorral import ehrcorral class TestEhrcorral(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass Add test case setUp to generate fake patient info#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import unittest from ehrcorral import ehrcorral from faker import Faker fake = Faker() fake.seed(8548) class TestEHRcorral(unittest.TestCase): def setUp(self): profile_fields = ['name', 'birthdate', 'ssn', 'address'] self.herd = [fake.profile(fields=profile_fields) for n in xrange(100)] def test_something(self): pass def tearDown(self): pass
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ import unittest from ehrcorral import ehrcorral class TestEhrcorral(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): pass <commit_msg>Add test case setUp to generate fake patient info<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ehrcorral ---------------------------------- Tests for `ehrcorral` module. """ from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import unittest from ehrcorral import ehrcorral from faker import Faker fake = Faker() fake.seed(8548) class TestEHRcorral(unittest.TestCase): def setUp(self): profile_fields = ['name', 'birthdate', 'ssn', 'address'] self.herd = [fake.profile(fields=profile_fields) for n in xrange(100)] def test_something(self): pass def tearDown(self): pass
4783f7047500865da06202a7d6d777801cf49c71
Box.py
Box.py
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() def main(): N = input() box = list() for i in range(N): x = input() x = x.split('') b = Box(x[0], x[1], x[2]) box.append(b) if __name__ == "__main__": main()
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() self.plength = 0 def __lt__(self, other): return (self.length < other.length and self.width < other.width and self.height < other.height) def link_to(self, box): self.plist.append(box) self.plength += 1 """ Test for input: def print_content(self): print(self.length, self.width, self.height) """ def main(): N = int(input()) box = list() for i in range(N): x = input() x = x.split(' ') x = Box(x[0], x[1], x[2]) box.append(x) # Test: # for i, x in enumerate(box): # x.print_content() if __name__ == "__main__": main()
Redefine function __lt__ and define a function to set link with others.
Redefine function __lt__ and define a function to set link with others.
Python
mit
hane1818/Algorithm_HW4_box_problem
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() def main(): N = input() box = list() for i in range(N): x = input() x = x.split('') b = Box(x[0], x[1], x[2]) box.append(b) if __name__ == "__main__": main() Redefine function __lt__ and define a function to set link with others.
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() self.plength = 0 def __lt__(self, other): return (self.length < other.length and self.width < other.width and self.height < other.height) def link_to(self, box): self.plist.append(box) self.plength += 1 """ Test for input: def print_content(self): print(self.length, self.width, self.height) """ def main(): N = int(input()) box = list() for i in range(N): x = input() x = x.split(' ') x = Box(x[0], x[1], x[2]) box.append(x) # Test: # for i, x in enumerate(box): # x.print_content() if __name__ == "__main__": main()
<commit_before>class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() def main(): N = input() box = list() for i in range(N): x = input() x = x.split('') b = Box(x[0], x[1], x[2]) box.append(b) if __name__ == "__main__": main() <commit_msg>Redefine function __lt__ and define a function to set link with others.<commit_after>
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() self.plength = 0 def __lt__(self, other): return (self.length < other.length and self.width < other.width and self.height < other.height) def link_to(self, box): self.plist.append(box) self.plength += 1 """ Test for input: def print_content(self): print(self.length, self.width, self.height) """ def main(): N = int(input()) box = list() for i in range(N): x = input() x = x.split(' ') x = Box(x[0], x[1], x[2]) box.append(x) # Test: # for i, x in enumerate(box): # x.print_content() if __name__ == "__main__": main()
class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() def main(): N = input() box = list() for i in range(N): x = input() x = x.split('') b = Box(x[0], x[1], x[2]) box.append(b) if __name__ == "__main__": main() Redefine function __lt__ and define a function to set link with others.class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() self.plength = 0 def __lt__(self, other): return (self.length < other.length and self.width < other.width and self.height < other.height) def link_to(self, box): self.plist.append(box) self.plength += 1 """ Test for input: def print_content(self): print(self.length, self.width, self.height) """ def main(): N = int(input()) box = list() for i in range(N): x = input() x = x.split(' ') x = Box(x[0], x[1], x[2]) box.append(x) # Test: # for i, x in enumerate(box): # x.print_content() if __name__ == "__main__": main()
<commit_before>class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() def main(): N = input() box = list() for i in range(N): x = input() x = x.split('') b = Box(x[0], x[1], x[2]) box.append(b) if __name__ == "__main__": main() <commit_msg>Redefine function __lt__ and define a function to set link with others.<commit_after>class Box: def __init__(self, length, width, height): self.length = length self.width = width self.height = height self.plist = list() self.plength = 0 def __lt__(self, other): return (self.length < other.length and self.width < other.width and self.height < other.height) def link_to(self, box): self.plist.append(box) self.plength += 1 """ Test for input: def print_content(self): print(self.length, self.width, self.height) """ def main(): N = int(input()) box = list() for i in range(N): x = input() x = x.split(' ') x = Box(x[0], x[1], x[2]) box.append(x) # Test: # for i, x in enumerate(box): # x.print_content() if __name__ == "__main__": main()
ea15b51ad444eeca3fdbc9eeb30fb8434ec3bfbd
pyscores/api_wrapper.py
pyscores/api_wrapper.py
import json import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main()
import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main()
Remove unused json import in api wrapper
Remove unused json import in api wrapper
Python
mit
conormag94/pyscores
import json import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main() Remove unused json import in api wrapper
import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main()
<commit_before>import json import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main() <commit_msg>Remove unused json import in api wrapper<commit_after>
import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main()
import json import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main() Remove unused json import in api wrapperimport os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main()
<commit_before>import json import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main() <commit_msg>Remove unused json import in api wrapper<commit_after>import os import requests class APIWrapper(object): def __init__(self, base_url=None, auth_token=None): if base_url: self.base_url = base_url else: self.base_url = "http://api.football-data.org/v1" if auth_token: self.headers = { 'X-Auth-Token': auth_token } else: self.headers = {} def do_request(self, url, filters=None): params = filters if filters else {} r = requests.get(url=url, params=params, headers=self.headers) if r.status_code == requests.codes.ok: return r.json() return None def all_competitions(self): url = "%s/competitions" % self.base_url response = self.do_request(url=url) return response def main(): api = APIWrapper(auth_token=os.environ["PYSCORES_KEY"]) res = api.do_request("http://api.football-data.org/v1/competitions") print(res) if __name__ == "__main__": main()
3d48732d577514d888ba5769a27d811d55fd9979
app.py
app.py
from flask import Flask import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): current_repo = repos.get('key') remote_name = current_repo('remote_name') remote_branch = current_repo('remote_branch') local_dir = current_repo('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0')
from flask import Flask from flask import request import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): repo_id = request.args.get('key') current_repo = repos.get(repo_id) remote_name = current_repo.get('remote_name') remote_branch = current_repo.get('remote_branch') local_dir = current_repo.get('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0')
Send repo id in get param
Send repo id in get param
Python
mit
Heads-and-Hands/pullover
from flask import Flask import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): current_repo = repos.get('key') remote_name = current_repo('remote_name') remote_branch = current_repo('remote_branch') local_dir = current_repo('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0') Send repo id in get param
from flask import Flask from flask import request import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): repo_id = request.args.get('key') current_repo = repos.get(repo_id) remote_name = current_repo.get('remote_name') remote_branch = current_repo.get('remote_branch') local_dir = current_repo.get('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0')
<commit_before>from flask import Flask import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): current_repo = repos.get('key') remote_name = current_repo('remote_name') remote_branch = current_repo('remote_branch') local_dir = current_repo('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0') <commit_msg>Send repo id in get param<commit_after>
from flask import Flask from flask import request import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): repo_id = request.args.get('key') current_repo = repos.get(repo_id) remote_name = current_repo.get('remote_name') remote_branch = current_repo.get('remote_branch') local_dir = current_repo.get('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0')
from flask import Flask import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): current_repo = repos.get('key') remote_name = current_repo('remote_name') remote_branch = current_repo('remote_branch') local_dir = current_repo('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0') Send repo id in get paramfrom flask import Flask from flask import request import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): repo_id = request.args.get('key') current_repo = repos.get(repo_id) remote_name = current_repo.get('remote_name') remote_branch = current_repo.get('remote_branch') local_dir = current_repo.get('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0')
<commit_before>from flask import Flask import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): current_repo = repos.get('key') remote_name = current_repo('remote_name') remote_branch = current_repo('remote_branch') local_dir = current_repo('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0') <commit_msg>Send repo id in get param<commit_after>from flask import Flask from flask import request import subprocess from config import repos app = Flask(__name__) @app.route("/", methods=['GET']) def hello(): repo_id = request.args.get('key') current_repo = repos.get(repo_id) remote_name = current_repo.get('remote_name') remote_branch = current_repo.get('remote_branch') local_dir = current_repo.get('local_dir') cmd = ["cd %s && git reset --hard && git pull %s %s" % (local_dir, remote_name, remote_branch),""] p = subprocess.Popen(cmd, shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() return out if __name__ == "__main__": app.run(host='0.0.0.0')
69a294d2a7aeab592dfa08e42423d8741aeb3828
app.py
app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): random_ip = '.'.join(map(str, [randint(0, 255) for _ in range(4)])) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
#!/usr/bin/env python # -*- coding: utf-8 -*- import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): if random.random() < 0.5: random_ip = '.'.join(map(str, [random.randint(0, 255) for _ in range(4)])) else: random_ip = ':'.join('{0:x}'.format(random.randint(0,2**16-1)) for _ in range(8)) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
Support IPv6 in random ip
Support IPv6 in random ip
Python
mit
lord63/pyhipku_web,lord63/pyhipku_web
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): random_ip = '.'.join(map(str, [randint(0, 255) for _ in range(4)])) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Support IPv6 in random ip
#!/usr/bin/env python # -*- coding: utf-8 -*- import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): if random.random() < 0.5: random_ip = '.'.join(map(str, [random.randint(0, 255) for _ in range(4)])) else: random_ip = ':'.join('{0:x}'.format(random.randint(0,2**16-1)) for _ in range(8)) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): random_ip = '.'.join(map(str, [randint(0, 255) for _ in range(4)])) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') <commit_msg>Support IPv6 in random ip<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): if random.random() < 0.5: random_ip = '.'.join(map(str, [random.randint(0, 255) for _ in range(4)])) else: random_ip = ':'.join('{0:x}'.format(random.randint(0,2**16-1)) for _ in range(8)) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): random_ip = '.'.join(map(str, [randint(0, 255) for _ in range(4)])) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') Support IPv6 in random ip#!/usr/bin/env python # -*- coding: utf-8 -*- import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): if random.random() < 0.5: random_ip = '.'.join(map(str, [random.randint(0, 255) for _ in range(4)])) else: random_ip = ':'.join('{0:x}'.format(random.randint(0,2**16-1)) for _ in range(8)) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- from random import randint from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): random_ip = '.'.join(map(str, [randint(0, 255) for _ in range(4)])) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') <commit_msg>Support IPv6 in random ip<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import random from flask import Flask, request, render_template, url_for, redirect from pyhipku import encode app = Flask(__name__) @app.route('/<current_ip>') def index(current_ip): your_ip = request.remote_addr lines = encode(current_ip).split('\n') return render_template('cover.html', lines=lines, your_ip=your_ip, current_ip=current_ip) @app.route('/') def get_ip(): return redirect(url_for('index', current_ip=request.remote_addr)) @app.route('/random') def random_ip(): if random.random() < 0.5: random_ip = '.'.join(map(str, [random.randint(0, 255) for _ in range(4)])) else: random_ip = ':'.join('{0:x}'.format(random.randint(0,2**16-1)) for _ in range(8)) return redirect(url_for('index', current_ip=random_ip)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')
552ea94c9fe2a42a8041d986e929b7defcdc4a4e
bot.py
bot.py
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my profile description or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my [profile description](/people/448c48d02c1c013349f314dae9b624ce) or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
Add link to foaas profile
Add link to foaas profile
Python
mit
Zauberstuhl/foaasBot
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my profile description or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout() Add link to foaas profile
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my [profile description](/people/448c48d02c1c013349f314dae9b624ce) or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
<commit_before>#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my profile description or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout() <commit_msg>Add link to foaas profile<commit_after>
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my [profile description](/people/448c48d02c1c013349f314dae9b624ce) or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my profile description or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout() Add link to foaas profile#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my [profile description](/people/448c48d02c1c013349f314dae9b624ce) or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
<commit_before>#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my profile description or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout() <commit_msg>Add link to foaas profile<commit_after>#! /usr/bin/env python from time import gmtime, strftime from foaas import foaas from diaspy_client import Client import re import urllib2 client = Client() notify = client.notifications() for n in notify: if not n.unread: continue idm = re.search('href=\\"/posts/(\d+?)\\"', n._data['note_html']) if hasattr(idm, 'group'): post_id = idm.group(1) text = client.getPostText(post_id) m = re.search('^\s*\@\{[^\};]+;[^\};]+\}\s+(\/.+?)$', text) if hasattr(m, 'group'): try: command = m.group(1) client.post(foaas(command)) except urllib2.URLError: client.comment(post_id, "Fuck this! Something went wrong :\\") else: client.comment(post_id, "Fuck this! Your command is not well-formed.\n" "Check my [profile description](/people/448c48d02c1c013349f314dae9b624ce) or " "[fuck around with him...](/posts/0f99d95040130133bbca14dae9b624ce)") # mark as read if it # is not a mention n.mark() client.logout()
2c4e93844c1b704e3435816737a6cfda624ff7b7
bot.py
bot.py
import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start()
import json import logging import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def post(self): logging.debug(json.dumps(self.request)) application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start()
Debug any incoming POST request.
Debug any incoming POST request.
Python
mit
pistonsky/pistonskybot
import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start() Debug any incoming POST request.
import json import logging import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def post(self): logging.debug(json.dumps(self.request)) application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start()
<commit_before>import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start() <commit_msg>Debug any incoming POST request.<commit_after>
import json import logging import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def post(self): logging.debug(json.dumps(self.request)) application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start()
import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start() Debug any incoming POST request.import json import logging import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def post(self): logging.debug(json.dumps(self.request)) application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start()
<commit_before>import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start() <commit_msg>Debug any incoming POST request.<commit_after>import json import logging import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import define, options from settings import * class MainHandler(tornado.web.RequestHandler): def post(self): logging.debug(json.dumps(self.request)) application = tornado.web.Application([ (r'/', MainHandler), ]) if __name__ == "__main__": define("port", default="443", help="Port to listen on") define("host", default="localhost", help="Server address to listen on") tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(application, ssl_options={ "certfile": PEMFILE, "keyfile": KEYFILE }) http_server.listen(int(options.port), address=options.host) tornado.ioloop.IOLoop.current().start()
ea4949dab887a14a0ca8f5ffbcd3c578c61c005e
api/urls.py
api/urls.py
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^services/$', views.services, name='api-services'), url(r'^collect/$', views.collect_response, name='api-collect'), url(r'^search/text/$', views.text_search, name='api-text-search'), url(r'^license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ]
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^v1/services/$', views.services, name='api-services'), url(r'^v1/collect/$', views.collect_response, name='api-collect'), url(r'^v1/search/text/$', views.text_search, name='api-text-search'), url(r'^v1/license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ]
Add API versioning at the url
Add API versioning at the url https://github.com/AudioCommons/ac-mediator/issues/13
Python
apache-2.0
AudioCommons/ac-mediator,AudioCommons/ac-mediator,AudioCommons/ac-mediator
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^services/$', views.services, name='api-services'), url(r'^collect/$', views.collect_response, name='api-collect'), url(r'^search/text/$', views.text_search, name='api-text-search'), url(r'^license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ] Add API versioning at the url https://github.com/AudioCommons/ac-mediator/issues/13
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^v1/services/$', views.services, name='api-services'), url(r'^v1/collect/$', views.collect_response, name='api-collect'), url(r'^v1/search/text/$', views.text_search, name='api-text-search'), url(r'^v1/license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ]
<commit_before>from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^services/$', views.services, name='api-services'), url(r'^collect/$', views.collect_response, name='api-collect'), url(r'^search/text/$', views.text_search, name='api-text-search'), url(r'^license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ] <commit_msg>Add API versioning at the url https://github.com/AudioCommons/ac-mediator/issues/13<commit_after>
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^v1/services/$', views.services, name='api-services'), url(r'^v1/collect/$', views.collect_response, name='api-collect'), url(r'^v1/search/text/$', views.text_search, name='api-text-search'), url(r'^v1/license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ]
from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^services/$', views.services, name='api-services'), url(r'^collect/$', views.collect_response, name='api-collect'), url(r'^search/text/$', views.text_search, name='api-text-search'), url(r'^license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ] Add API versioning at the url https://github.com/AudioCommons/ac-mediator/issues/13from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^v1/services/$', views.services, name='api-services'), url(r'^v1/collect/$', views.collect_response, name='api-collect'), url(r'^v1/search/text/$', views.text_search, name='api-text-search'), url(r'^v1/license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ]
<commit_before>from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^services/$', views.services, name='api-services'), url(r'^collect/$', views.collect_response, name='api-collect'), url(r'^search/text/$', views.text_search, name='api-text-search'), url(r'^license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ] <commit_msg>Add API versioning at the url https://github.com/AudioCommons/ac-mediator/issues/13<commit_after>from django.conf.urls import include, url from api import views urlpatterns = [ url(r'^v1/services/$', views.services, name='api-services'), url(r'^v1/collect/$', views.collect_response, name='api-collect'), url(r'^v1/search/text/$', views.text_search, name='api-text-search'), url(r'^v1/license/$', views.licensing, name='api-licensing'), # Oauth2 urls url(r'^o/', include('api.oauth2_urls', namespace='oauth2_provider')), ]
21193559b063e85f26971d5ae6181a0bd097cda3
tests/utilities_test.py
tests/utilities_test.py
#pylint: disable=W0104,W0108 import pytest import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n"
#pylint: disable=W0104,W0108 import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" ############ # Vector # ############ @pyop.vector def multFirstColumn(column): img = column.reshape((2, 2), order = 'C') img[:, 0] *= 2 return img.flatten(0) def testVectorOnMatrix(): np.testing.assert_allclose( multFirstColumn(np.array([[1, 1, 1, 1], [2, 1, 2, 1]]).T), np.array([[2, 4], [1, 1], [2, 4], [1, 1]])) def testVectorOnVector(): np.testing.assert_allclose( multFirstColumn(np.array([1, 1, 1, 1])), np.array(np.array([2, 1, 2, 1])))
Test vector, passes matrix and vector input.
Test vector, passes matrix and vector input.
Python
bsd-3-clause
ryanorendorff/pyop
#pylint: disable=W0104,W0108 import pytest import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" Test vector, passes matrix and vector input.
#pylint: disable=W0104,W0108 import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" ############ # Vector # ############ @pyop.vector def multFirstColumn(column): img = column.reshape((2, 2), order = 'C') img[:, 0] *= 2 return img.flatten(0) def testVectorOnMatrix(): np.testing.assert_allclose( multFirstColumn(np.array([[1, 1, 1, 1], [2, 1, 2, 1]]).T), np.array([[2, 4], [1, 1], [2, 4], [1, 1]])) def testVectorOnVector(): np.testing.assert_allclose( multFirstColumn(np.array([1, 1, 1, 1])), np.array(np.array([2, 1, 2, 1])))
<commit_before>#pylint: disable=W0104,W0108 import pytest import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" <commit_msg>Test vector, passes matrix and vector input.<commit_after>
#pylint: disable=W0104,W0108 import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" ############ # Vector # ############ @pyop.vector def multFirstColumn(column): img = column.reshape((2, 2), order = 'C') img[:, 0] *= 2 return img.flatten(0) def testVectorOnMatrix(): np.testing.assert_allclose( multFirstColumn(np.array([[1, 1, 1, 1], [2, 1, 2, 1]]).T), np.array([[2, 4], [1, 1], [2, 4], [1, 1]])) def testVectorOnVector(): np.testing.assert_allclose( multFirstColumn(np.array([1, 1, 1, 1])), np.array(np.array([2, 1, 2, 1])))
#pylint: disable=W0104,W0108 import pytest import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" Test vector, passes matrix and vector input.#pylint: disable=W0104,W0108 import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" ############ # Vector # ############ @pyop.vector def multFirstColumn(column): img = column.reshape((2, 2), order = 'C') img[:, 0] *= 2 return img.flatten(0) def testVectorOnMatrix(): np.testing.assert_allclose( multFirstColumn(np.array([[1, 1, 1, 1], [2, 1, 2, 1]]).T), np.array([[2, 4], [1, 1], [2, 4], [1, 1]])) def testVectorOnVector(): np.testing.assert_allclose( multFirstColumn(np.array([1, 1, 1, 1])), np.array(np.array([2, 1, 2, 1])))
<commit_before>#pylint: disable=W0104,W0108 import pytest import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" <commit_msg>Test vector, passes matrix and vector input.<commit_after>#pylint: disable=W0104,W0108 import pyop import numpy as np ####################################################################### # Tests # ####################################################################### def testEnsure2dColumn(capsys): @pyop.ensure2dColumn def printShape(x): print(x.shape) return x input_vec = np.random.rand(10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 1)\n" input_vec = np.random.rand(10, 10) output = printShape(input_vec) print_out, _ = capsys.readouterr() np.testing.assert_allclose(input_vec, output) assert print_out == "(10, 10)\n" ############ # Vector # ############ @pyop.vector def multFirstColumn(column): img = column.reshape((2, 2), order = 'C') img[:, 0] *= 2 return img.flatten(0) def testVectorOnMatrix(): np.testing.assert_allclose( multFirstColumn(np.array([[1, 1, 1, 1], [2, 1, 2, 1]]).T), np.array([[2, 4], [1, 1], [2, 4], [1, 1]])) def testVectorOnVector(): np.testing.assert_allclose( multFirstColumn(np.array([1, 1, 1, 1])), np.array(np.array([2, 1, 2, 1])))
98a6b04b83843861003862d835b3a2f6f2364506
tests/context_tests.py
tests/context_tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) def test_opengl_states_are_set_on_context_creation(self): handle = 'x' bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() bridge.cgGLRegisterStates.assert_called_once_with(handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle)
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle)
Update test to match last changes in the API
Update test to match last changes in the API
Python
mit
jstasiak/python-cg,jstasiak/python-cg
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) def test_opengl_states_are_set_on_context_creation(self): handle = 'x' bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() bridge.cgGLRegisterStates.assert_called_once_with(handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle) Update test to match last changes in the API
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle)
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) def test_opengl_states_are_set_on_context_creation(self): handle = 'x' bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() bridge.cgGLRegisterStates.assert_called_once_with(handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle) <commit_msg>Update test to match last changes in the API<commit_after>
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle)
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) def test_opengl_states_are_set_on_context_creation(self): handle = 'x' bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() bridge.cgGLRegisterStates.assert_called_once_with(handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle) Update test to match last changes in the API# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle)
<commit_before># -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) def test_opengl_states_are_set_on_context_creation(self): handle = 'x' bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() bridge.cgGLRegisterStates.assert_called_once_with(handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle) <commit_msg>Update test to match last changes in the API<commit_after># -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from mock import Mock from nose.tools import eq_ from cg.context import Context, ContextFactory class TestContextFactory(object): def test_context_gets_created_correctly(self): handle = 123 bridge = Mock() bridge.cgCreateContext.return_value = handle cf = ContextFactory(bridge) context = cf.create() eq_(context._cgcontext, handle) class TestContext(object): def test_context_disposes_of_its_resources(self): handle = 234 bridge = Mock() context = Context(handle, bridge) context.dispose() bridge.cgDestroyContext.assert_called_once_with(handle)
4fb1023c461498a080d371e50a5a4971924cb1bc
third_party/__init__.py
third_party/__init__.py
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.append(os.path.dirname(__file__))
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.insert(1, os.path.dirname(__file__))
Insert third_party into the second slot of sys.path rather than the last slot
Insert third_party into the second slot of sys.path rather than the last slot
Python
apache-2.0
somehume/namebench
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.append(os.path.dirname(__file__)) Insert third_party into the second slot of sys.path rather than the last slot
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.insert(1, os.path.dirname(__file__))
<commit_before>import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.append(os.path.dirname(__file__)) <commit_msg>Insert third_party into the second slot of sys.path rather than the last slot<commit_after>
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.insert(1, os.path.dirname(__file__))
import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.append(os.path.dirname(__file__)) Insert third_party into the second slot of sys.path rather than the last slotimport os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.insert(1, os.path.dirname(__file__))
<commit_before>import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.append(os.path.dirname(__file__)) <commit_msg>Insert third_party into the second slot of sys.path rather than the last slot<commit_after>import os.path import sys # This bit of evil should inject third_party into the path for relative imports. sys.path.insert(1, os.path.dirname(__file__))
377beee13a8cd0ca23f8f2e37dd2816571721921
tests/sources_tests.py
tests/sources_tests.py
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"])
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) @istest def can_fetch_package_source_from_local_path(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") source_fetcher = PackageSourceFetcher([]) with source_fetcher.fetch(package_source_dir) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"])
Add test for fetching local package sources
Add test for fetching local package sources
Python
bsd-2-clause
mwilliamson/whack
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"]) Add test for fetching local package sources
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) @istest def can_fetch_package_source_from_local_path(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") source_fetcher = PackageSourceFetcher([]) with source_fetcher.fetch(package_source_dir) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"])
<commit_before>import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"]) <commit_msg>Add test for fetching local package sources<commit_after>
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) @istest def can_fetch_package_source_from_local_path(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") source_fetcher = PackageSourceFetcher([]) with source_fetcher.fetch(package_source_dir) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"])
import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"]) Add test for fetching local package sourcesimport os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) @istest def can_fetch_package_source_from_local_path(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") source_fetcher = PackageSourceFetcher([]) with source_fetcher.fetch(package_source_dir) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"])
<commit_before>import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"]) <commit_msg>Add test for fetching local package sources<commit_after>import os import subprocess from nose.tools import istest, assert_equal from whack.sources import PackageSourceFetcher from whack.tempdir import create_temporary_dir from whack.files import read_file, write_file @istest def can_fetch_package_source_from_source_control(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") _convert_to_git_repo(package_source_dir) source_fetcher = PackageSourceFetcher([]) repo_uri = "git+file://{0}".format(package_source_dir) with source_fetcher.fetch(repo_uri) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) @istest def can_fetch_package_source_from_local_path(): with create_temporary_dir() as package_source_dir: write_file(os.path.join(package_source_dir, "name"), "Bob") source_fetcher = PackageSourceFetcher([]) with source_fetcher.fetch(package_source_dir) as package_source: assert_equal("Bob", read_file(os.path.join(package_source.path, "name"))) def _convert_to_git_repo(cwd): def _git(command): subprocess.check_call(["git"] + command, cwd=cwd) _git(["init"]) _git(["add", "."]) _git(["commit", "-m", "Initial commit"])
c4db09cd2d4dac37afcf75d5cf4d8c8f881aac2d
tests/test_examples.py
tests/test_examples.py
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer)
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer.expressions def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer.expressions)
Test the doc comments in the expressions module.
Test the doc comments in the expressions module.
Python
mit
jvs/sourcer
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer) Test the doc comments in the expressions module.
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer.expressions def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer.expressions)
<commit_before>'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer) <commit_msg>Test the doc comments in the expressions module.<commit_after>
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer.expressions def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer.expressions)
'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer) Test the doc comments in the expressions module.'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer.expressions def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer.expressions)
<commit_before>'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer) <commit_msg>Test the doc comments in the expressions module.<commit_after>'''Search all our doc comments for "Example" blocks and try executing them.''' import re import sourcer.expressions def run_examples(package): pattern = re.compile(r''' (\s*) # initial indent Example # magic keyword ([^\n]*) # optional description \:\: # magic marker # Each line of the example is indented # by four additional spaces: (\n((\1\ \ \ \ .*)?\n)+) ''', re.IGNORECASE | re.VERBOSE ) for k, v in package.__dict__.iteritems(): if k.startswith('__') and k.endswith('__'): continue doc = getattr(v, '__doc__') or '' for m in pattern.finditer(doc): indent = '\n ' + m.group(1) body = m.group(3) example = body.replace(indent, '\n') print ' Running', k, 'example', m.group(2).strip() exec example in {} if __name__ == '__main__': run_examples(sourcer.expressions)
aaae301f62b4e0b3cdd5d1756a03b619a8f18222
tests/test_hamilton.py
tests/test_hamilton.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], )
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention)
Add test for invalid 'convention' in hamilton method
Add test for invalid 'convention' in hamilton method
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) Add test for invalid 'convention' in hamilton method
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) <commit_msg>Add test for invalid 'convention' in hamilton method<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention)
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) Add test for invalid 'convention' in hamilton method#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) <commit_msg>Add test for invalid 'convention' in hamilton method<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the Hamiltonian method.""" import pytest from numpy.testing import assert_allclose from parameters import KPT, T_VALUES @pytest.mark.parametrize("kpt", KPT) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_simple_hamilton(get_model, kpt, t_values, compare_isclose, convention): """ Regression test for the Hamiltonian of a simple model. """ model = get_model(*t_values) compare_isclose(model.hamilton(kpt, convention=convention)) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("convention", [1, 2]) def test_parallel_hamilton(get_model, t_values, convention): """ Test that passing multiple k-points to the Hamiltonian gives the same results as evaluating them individually. """ model = get_model(*t_values) assert_allclose( model.hamilton(KPT, convention=convention), [model.hamilton(k, convention=convention) for k in KPT], ) @pytest.mark.parametrize("convention", ["a", "1", None]) def test_invalid_convention(get_model, convention): """ Test that giving an invalid 'convention' raises an error. """ model = get_model(t1=0, t2=0.1) with pytest.raises(ValueError): model.hamilton((0, 0, 0), convention=convention)
08730308134d0a15be996e8e7bb1a19bc1930f12
tests/test_plotting.py
tests/test_plotting.py
from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path finally: try: os.remove(path) except: pass class TestSeriesPlot(unittest.TestCase): def setUp(self): self.t1 = Polygon([(0, 0), (1, 0), (1, 1)]) self.t2 = Polygon([(1, 0), (2, 1), (2, 1)]) self.polys = GeoSeries([self.t1, self.t2]) def test_poly_plot(self): """ Test plotting a simple series of polygons """ ax = self.polys.plot() self.assertIsInstance(ax, Artist) with get_tempfile() as file: savefig(file) if __name__ == '__main__': unittest.main()
import os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELINE = False BASELINE_DIR = os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_plotting') def save_baseline_image(filename): """ save a baseline image """ savefig(os.path.join(BASELINE_DIR, filename)) @image_comparison(baseline_images=['poly_plot'], extensions=['png']) def test_poly_plot(): """ Test plotting a simple series of polygons """ t1 = Polygon([(0, 0), (1, 0), (1, 1)]) t2 = Polygon([(1, 0), (2, 1), (2, 1)]) polys = GeoSeries([t1, t2]) ax = polys.plot() assert isinstance(ax, Artist) if GENERATE_BASELINE: save_baseline_image('poly_plot.png') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'])
Use matplotlib image_comparison to actually compare plot output
TST: Use matplotlib image_comparison to actually compare plot output
Python
bsd-3-clause
jorisvandenbossche/geopandas,jorisvandenbossche/geopandas,jdmcbr/geopandas,koldunovn/geopandas,ozak/geopandas,maxalbert/geopandas,IamJeffG/geopandas,ozak/geopandas,geopandas/geopandas,fonnesbeck/geopandas,kwinkunks/geopandas,geopandas/geopandas,geopandas/geopandas,jorisvandenbossche/geopandas,urschrei/geopandas,snario/geopandas,scw/geopandas,jdmcbr/geopandas,micahcochran/geopandas,micahcochran/geopandas,perrygeo/geopandas
from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path finally: try: os.remove(path) except: pass class TestSeriesPlot(unittest.TestCase): def setUp(self): self.t1 = Polygon([(0, 0), (1, 0), (1, 1)]) self.t2 = Polygon([(1, 0), (2, 1), (2, 1)]) self.polys = GeoSeries([self.t1, self.t2]) def test_poly_plot(self): """ Test plotting a simple series of polygons """ ax = self.polys.plot() self.assertIsInstance(ax, Artist) with get_tempfile() as file: savefig(file) if __name__ == '__main__': unittest.main() TST: Use matplotlib image_comparison to actually compare plot output
import os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELINE = False BASELINE_DIR = os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_plotting') def save_baseline_image(filename): """ save a baseline image """ savefig(os.path.join(BASELINE_DIR, filename)) @image_comparison(baseline_images=['poly_plot'], extensions=['png']) def test_poly_plot(): """ Test plotting a simple series of polygons """ t1 = Polygon([(0, 0), (1, 0), (1, 1)]) t2 = Polygon([(1, 0), (2, 1), (2, 1)]) polys = GeoSeries([t1, t2]) ax = polys.plot() assert isinstance(ax, Artist) if GENERATE_BASELINE: save_baseline_image('poly_plot.png') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'])
<commit_before>from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path finally: try: os.remove(path) except: pass class TestSeriesPlot(unittest.TestCase): def setUp(self): self.t1 = Polygon([(0, 0), (1, 0), (1, 1)]) self.t2 = Polygon([(1, 0), (2, 1), (2, 1)]) self.polys = GeoSeries([self.t1, self.t2]) def test_poly_plot(self): """ Test plotting a simple series of polygons """ ax = self.polys.plot() self.assertIsInstance(ax, Artist) with get_tempfile() as file: savefig(file) if __name__ == '__main__': unittest.main() <commit_msg>TST: Use matplotlib image_comparison to actually compare plot output<commit_after>
import os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELINE = False BASELINE_DIR = os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_plotting') def save_baseline_image(filename): """ save a baseline image """ savefig(os.path.join(BASELINE_DIR, filename)) @image_comparison(baseline_images=['poly_plot'], extensions=['png']) def test_poly_plot(): """ Test plotting a simple series of polygons """ t1 = Polygon([(0, 0), (1, 0), (1, 1)]) t2 = Polygon([(1, 0), (2, 1), (2, 1)]) polys = GeoSeries([t1, t2]) ax = polys.plot() assert isinstance(ax, Artist) if GENERATE_BASELINE: save_baseline_image('poly_plot.png') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'])
from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path finally: try: os.remove(path) except: pass class TestSeriesPlot(unittest.TestCase): def setUp(self): self.t1 = Polygon([(0, 0), (1, 0), (1, 1)]) self.t2 = Polygon([(1, 0), (2, 1), (2, 1)]) self.polys = GeoSeries([self.t1, self.t2]) def test_poly_plot(self): """ Test plotting a simple series of polygons """ ax = self.polys.plot() self.assertIsInstance(ax, Artist) with get_tempfile() as file: savefig(file) if __name__ == '__main__': unittest.main() TST: Use matplotlib image_comparison to actually compare plot outputimport os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELINE = False BASELINE_DIR = os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_plotting') def save_baseline_image(filename): """ save a baseline image """ savefig(os.path.join(BASELINE_DIR, filename)) @image_comparison(baseline_images=['poly_plot'], extensions=['png']) def test_poly_plot(): """ Test plotting a simple series of polygons """ t1 = Polygon([(0, 0), (1, 0), (1, 1)]) t2 = Polygon([(1, 0), (2, 1), (2, 1)]) polys = GeoSeries([t1, t2]) ax = polys.plot() assert isinstance(ax, Artist) if GENERATE_BASELINE: save_baseline_image('poly_plot.png') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'])
<commit_before>from contextlib import contextmanager import os import tempfile import unittest from matplotlib.pyplot import Artist, savefig from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries @contextmanager def get_tempfile(): f, path = tempfile.mkstemp() try: yield path finally: try: os.remove(path) except: pass class TestSeriesPlot(unittest.TestCase): def setUp(self): self.t1 = Polygon([(0, 0), (1, 0), (1, 1)]) self.t2 = Polygon([(1, 0), (2, 1), (2, 1)]) self.polys = GeoSeries([self.t1, self.t2]) def test_poly_plot(self): """ Test plotting a simple series of polygons """ ax = self.polys.plot() self.assertIsInstance(ax, Artist) with get_tempfile() as file: savefig(file) if __name__ == '__main__': unittest.main() <commit_msg>TST: Use matplotlib image_comparison to actually compare plot output<commit_after>import os import unittest from matplotlib.pyplot import Artist, savefig from matplotlib.testing.decorators import image_comparison from shapely.geometry import Polygon, LineString, Point from geopandas import GeoSeries # If set to True, generate images rather than perform tests (all tests will pass!) GENERATE_BASELINE = False BASELINE_DIR = os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_plotting') def save_baseline_image(filename): """ save a baseline image """ savefig(os.path.join(BASELINE_DIR, filename)) @image_comparison(baseline_images=['poly_plot'], extensions=['png']) def test_poly_plot(): """ Test plotting a simple series of polygons """ t1 = Polygon([(0, 0), (1, 0), (1, 1)]) t2 = Polygon([(1, 0), (2, 1), (2, 1)]) polys = GeoSeries([t1, t2]) ax = polys.plot() assert isinstance(ax, Artist) if GENERATE_BASELINE: save_baseline_image('poly_plot.png') if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'])
331060f37841dccbd8974f01c063dc1b5c112121
formula/openssl.py
formula/openssl.py
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test')
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test')
Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug
Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug
Python
mit
mfichman/winbrew
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test') Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test')
<commit_before>import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test') <commit_msg>Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug<commit_after>
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test')
import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test') Upgrade to OpenSSL 1.0.1g to avoid heartbleed bugimport winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test')
<commit_before>import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1f.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test') <commit_msg>Upgrade to OpenSSL 1.0.1g to avoid heartbleed bug<commit_after>import winbrew class Openssl(winbrew.Formula): url = 'http://www.openssl.org/source/openssl-1.0.1g.tar.gz' homepage = 'http://www.openssl.org' sha1 = '' build_deps = () deps = () def install(self): self.system('perl Configure VC-WIN32 no-asm --prefix=C:\\Winbrew\\lib\\OpenSSL') self.system('ms\\\\do_ms.bat') self.system('nmake -f ms\\\\nt.mak') self.lib('out32\\libeay32.lib') self.lib('out32\\ssleay32.lib') self.includes('include\\openssl', dest='openssl') #self.system('nmake -f ms\\ntdll.mak install') # Dynamic libraries def test(self): self.system('nmake -f ms\\\\nt.mak test')
5b8b210a73282f6176883f3fab1dd0b2801b3f34
wsgi/app.py
wsgi/app.py
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False if newrelic: newrelic_ini = config('NEWRELIC_PYTHON_INI_FILE', default='') if newrelic_ini: newrelic.agent.initialize(newrelic_ini) else: newrelic = False import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application)
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False else: newrelic.agent.initialize() import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application)
Remove unused ability to use custom newrelic.ini
Remove unused ability to use custom newrelic.ini
Python
mpl-2.0
flodolo/bedrock,craigcook/bedrock,hoosteeno/bedrock,sylvestre/bedrock,craigcook/bedrock,pascalchevrel/bedrock,kyoshino/bedrock,kyoshino/bedrock,sgarrity/bedrock,ericawright/bedrock,ericawright/bedrock,MichaelKohler/bedrock,mozilla/bedrock,alexgibson/bedrock,alexgibson/bedrock,hoosteeno/bedrock,ericawright/bedrock,sgarrity/bedrock,flodolo/bedrock,flodolo/bedrock,mozilla/bedrock,pascalchevrel/bedrock,sgarrity/bedrock,craigcook/bedrock,sylvestre/bedrock,MichaelKohler/bedrock,hoosteeno/bedrock,kyoshino/bedrock,sylvestre/bedrock,MichaelKohler/bedrock,alexgibson/bedrock,ericawright/bedrock,craigcook/bedrock,mozilla/bedrock,alexgibson/bedrock,kyoshino/bedrock,sgarrity/bedrock,flodolo/bedrock,MichaelKohler/bedrock,hoosteeno/bedrock,mozilla/bedrock,sylvestre/bedrock,pascalchevrel/bedrock,pascalchevrel/bedrock
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False if newrelic: newrelic_ini = config('NEWRELIC_PYTHON_INI_FILE', default='') if newrelic_ini: newrelic.agent.initialize(newrelic_ini) else: newrelic = False import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application) Remove unused ability to use custom newrelic.ini
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False else: newrelic.agent.initialize() import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application)
<commit_before># flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False if newrelic: newrelic_ini = config('NEWRELIC_PYTHON_INI_FILE', default='') if newrelic_ini: newrelic.agent.initialize(newrelic_ini) else: newrelic = False import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application) <commit_msg>Remove unused ability to use custom newrelic.ini<commit_after>
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False else: newrelic.agent.initialize() import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application)
# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False if newrelic: newrelic_ini = config('NEWRELIC_PYTHON_INI_FILE', default='') if newrelic_ini: newrelic.agent.initialize(newrelic_ini) else: newrelic = False import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application) Remove unused ability to use custom newrelic.ini# flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False else: newrelic.agent.initialize() import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application)
<commit_before># flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False if newrelic: newrelic_ini = config('NEWRELIC_PYTHON_INI_FILE', default='') if newrelic_ini: newrelic.agent.initialize(newrelic_ini) else: newrelic = False import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application) <commit_msg>Remove unused ability to use custom newrelic.ini<commit_after># flake8: noqa # newrelic import & initialization must come first # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration try: import newrelic.agent except ImportError: newrelic = False else: newrelic.agent.initialize() import os from bedrock.base.config_manager import config IS_HTTPS = os.environ.get('HTTPS', '').strip() == 'on' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bedrock.settings') # must be imported after env var is set above. from django.core.handlers.wsgi import WSGIRequest from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise from raven.contrib.django.raven_compat.middleware.wsgi import Sentry class WSGIHTTPSRequest(WSGIRequest): def _get_scheme(self): if IS_HTTPS: return 'https' return super(WSGIHTTPSRequest, self)._get_scheme() application = get_wsgi_application() application.request_class = WSGIHTTPSRequest application = DjangoWhiteNoise(application) application = Sentry(application) if newrelic: application = newrelic.agent.wsgi_application()(application)
0e533ad0cc42431a57758b577cf96783ee4b7484
spacy/tests/test_download.py
spacy/tests/test_download.py
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest @pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
Mark compatibility table test as slow (temporary)
Mark compatibility table test as slow (temporary) Prevent Travis from running test test until models repo is published
Python
mit
oroszgy/spaCy.hu,oroszgy/spaCy.hu,aikramer2/spaCy,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,aikramer2/spaCy,raphael0202/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,raphael0202/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,Gregory-Howard/spaCy
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model) Mark compatibility table test as slow (temporary) Prevent Travis from running test test until models repo is published
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest @pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
<commit_before># coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model) <commit_msg>Mark compatibility table test as slow (temporary) Prevent Travis from running test test until models repo is published<commit_after>
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest @pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model) Mark compatibility table test as slow (temporary) Prevent Travis from running test test until models repo is published# coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest @pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
<commit_before># coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model) <commit_msg>Mark compatibility table test as slow (temporary) Prevent Travis from running test test until models repo is published<commit_after># coding: utf-8 from __future__ import unicode_literals from ..download import download, get_compatibility, get_version, check_error_depr import pytest @pytest.mark.slow def test_download_fetch_compatibility(): compatibility = get_compatibility() assert type(compatibility) == dict @pytest.mark.slow @pytest.mark.parametrize('model', ['en_core_web_md-1.2.0']) def test_download_direct_download(model): download(model, direct=True) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_succeeds(model): comp = { model: ['1.7.0', '0.100.0'] } assert get_version(model, comp) @pytest.mark.parametrize('model', ['en_core_web_md']) def test_download_get_matching_version_fails(model): diff_model = 'test_' + model comp = { diff_model: ['1.7.0', '0.100.0'] } with pytest.raises(SystemExit): assert get_version(model, comp) @pytest.mark.parametrize('model', [False, None, '', 'all']) def test_download_no_model_depr_error(model): with pytest.raises(SystemExit): check_error_depr(model)
a6a4c2920abd099a97839584b96af10dcd25afe2
tests/test_public_api.py
tests/test_public_api.py
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) if __name__ == '__main__': unittest.main()
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_available_markups(self): available_markups = markups.get_available_markups() self.assertIn(markups.MarkdownMarkup, available_markups) if __name__ == '__main__': unittest.main()
Add a test for get_available_markups() function
Add a test for get_available_markups() function
Python
bsd-3-clause
mitya57/pymarkups,retext-project/pymarkups
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) if __name__ == '__main__': unittest.main() Add a test for get_available_markups() function
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_available_markups(self): available_markups = markups.get_available_markups() self.assertIn(markups.MarkdownMarkup, available_markups) if __name__ == '__main__': unittest.main()
<commit_before># This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) if __name__ == '__main__': unittest.main() <commit_msg>Add a test for get_available_markups() function<commit_after>
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_available_markups(self): available_markups = markups.get_available_markups() self.assertIn(markups.MarkdownMarkup, available_markups) if __name__ == '__main__': unittest.main()
# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) if __name__ == '__main__': unittest.main() Add a test for get_available_markups() function# This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_available_markups(self): available_markups = markups.get_available_markups() self.assertIn(markups.MarkdownMarkup, available_markups) if __name__ == '__main__': unittest.main()
<commit_before># This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) if __name__ == '__main__': unittest.main() <commit_msg>Add a test for get_available_markups() function<commit_after># This file is part of python-markups test suite # License: BSD # Copyright: (C) Dmitry Shachnev, 2012-2015 import markups import unittest class APITest(unittest.TestCase): def test_api(self): all_markups = markups.get_all_markups() self.assertIn(markups.MarkdownMarkup, all_markups) self.assertIn(markups.ReStructuredTextMarkup, all_markups) markup_class = markups.find_markup_class_by_name('restructuredtext') self.assertEqual(markups.ReStructuredTextMarkup, markup_class) markup_class = markups.get_markup_for_file_name('myfile.mkd', return_class=True) self.assertEqual(markups.MarkdownMarkup, markup_class) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_api_instance(self): markup = markups.get_markup_for_file_name('myfile.mkd') self.assertIsInstance(markup, markups.MarkdownMarkup) @unittest.skipUnless(markups.MarkdownMarkup.available(), 'Markdown not available') def test_available_markups(self): available_markups = markups.get_available_markups() self.assertIn(markups.MarkdownMarkup, available_markups) if __name__ == '__main__': unittest.main()
9ce5a020ac6e9bbdf7e2fc0c34c98cdfaf9e0a45
tests/formatters/conftest.py
tests/formatters/conftest.py
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.append('description', 'Fee fie foe fum') char.append('type', 'human') return char
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.tags('description').append('Fee fie foe fum') char.tags('type').append('human') return char
Set up defaults using tag syntax
Set up defaults using tag syntax
Python
mit
aurule/npc,aurule/npc
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.append('description', 'Fee fie foe fum') char.append('type', 'human') return char Set up defaults using tag syntax
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.tags('description').append('Fee fie foe fum') char.tags('type').append('human') return char
<commit_before>import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.append('description', 'Fee fie foe fum') char.append('type', 'human') return char <commit_msg>Set up defaults using tag syntax<commit_after>
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.tags('description').append('Fee fie foe fum') char.tags('type').append('human') return char
import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.append('description', 'Fee fie foe fum') char.append('type', 'human') return char Set up defaults using tag syntaximport npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.tags('description').append('Fee fie foe fum') char.tags('type').append('human') return char
<commit_before>import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.append('description', 'Fee fie foe fum') char.append('type', 'human') return char <commit_msg>Set up defaults using tag syntax<commit_after>import npc import pytest @pytest.fixture(scope="module") def character(): char = npc.character.Character() char.tags('description').append('Fee fie foe fum') char.tags('type').append('human') return char
69ec55e0a6b4d314eb1381afc09236a5aa01d3d8
util/git-author-comm.py
util/git-author-comm.py
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
Make it more obvious that you need to use a local repository as an argument, not a url
Make it more obvious that you need to use a local repository as an argument, not a url
Python
mit
baykovr/toolbox,baykovr/toolbox,baykovr/toolbox,baykovr/toolbox,baykovr/toolbox
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author Make it more obvious that you need to use a local repository as an argument, not a url
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
<commit_before>#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author <commit_msg>Make it more obvious that you need to use a local repository as an argument, not a url<commit_after>
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author Make it more obvious that you need to use a local repository as an argument, not a url#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
<commit_before>#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two git repositories.' print 'python2 git-author-comm.py [path-to-git-repo] [path-to-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author <commit_msg>Make it more obvious that you need to use a local repository as an argument, not a url<commit_after>#!/usr/bin/env python # Display authors which appear as contributors in both (two) repositories. import os,sys def usage(): print 'Show authors which appear in two local git repositories.' print 'python2 git-author-comm.py [path-to-local-git-repo] [path-to-local-git-repo]' def sysout(command): return os.popen(command).read() def get_authors(git): cmd = "git --work-tree="+git+" --git-dir="+git+"/.git log --format='%aN' | sort -u" # Split results to a list. authors = sysout(cmd).split('\n') # Remove any empty lines prior to return. return filter(None, authors) def get_same_authors(a1,a2): # Return a set of authors which appear in both repositories. return set(a1).intersection(a2) if __name__ == "__main__": if len(sys.argv) != 3: usage() else: git1 = sys.argv[1] git2 = sys.argv[2] authors = get_same_authors(get_authors(git1),get_authors(git2)) if len(authors) == 0: print 'There are no matches.' else: print 'The folowing appear in both repositories: ' for author in authors: print author
4669a033ee4fbde5e3c2447778657a20a73d5df8
thefuck/shells/powershell.py
thefuck/shells/powershell.py
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thefuck $history);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
Update PowerShell alias to handle no history
Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.
Python
mit
Clpsplug/thefuck,scorphus/thefuck,nvbn/thefuck,nvbn/thefuck,scorphus/thefuck,mlk/thefuck,Clpsplug/thefuck,mlk/thefuck,SimenB/thefuck,SimenB/thefuck
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', } Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thefuck $history);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
<commit_before>from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', } <commit_msg>Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.<commit_after>
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thefuck $history);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', } Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thefuck $history);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
<commit_before>from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' { \n' \ ' $fuck = $(thefuck (Get-History -Count 1).CommandLine);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', } <commit_msg>Update PowerShell alias to handle no history If history is cleared (or the shell is new and there is no history), invoking thefuck results in an error because the alias attempts to execute the usage string. The fix is to check if Get-History returns anything before invoking thefuck.<commit_after>from .generic import Generic class Powershell(Generic): def app_alias(self, fuck): return 'function ' + fuck + ' {\n' \ ' $history = (Get-History -Count 1).CommandLine;\n' \ ' if (-not [string]::IsNullOrWhiteSpace($history)) {\n' \ ' $fuck = $(thefuck $history);\n' \ ' if (-not [string]::IsNullOrWhiteSpace($fuck)) {\n' \ ' if ($fuck.StartsWith("echo")) { $fuck = $fuck.Substring(5); }\n' \ ' else { iex "$fuck"; }\n' \ ' }\n' \ ' }\n' \ '}\n' def and_(self, *commands): return u' -and '.join('({0})'.format(c) for c in commands) def how_to_configure(self): return { 'content': 'iex "thefuck --alias"', 'path': '$profile', 'reload': '& $profile', }
7654d9dcebb0ad1e862e376b5b694234173289ed
twitter_helper/util.py
twitter_helper/util.py
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
Reset pointer to the beginning of file once read it
Reset pointer to the beginning of file once read it Be polite, put things back in the place you found them
Python
mit
kuzeko/Twitter-Importer,kuzeko/Twitter-Importer
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return lineReset pointer to the beginning of file once read it Be polite, put things back in the place you found them
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
<commit_before>import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line<commit_msg>Reset pointer to the beginning of file once read it Be polite, put things back in the place you found them<commit_after>
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return lineReset pointer to the beginning of file once read it Be polite, put things back in the place you found themimport random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
<commit_before>import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line<commit_msg>Reset pointer to the beginning of file once read it Be polite, put things back in the place you found them<commit_after>import random def random_line(afile, max_chars = 123, min_chars = 5): line = next(afile) for num, aline in enumerate(afile): aline = aline.strip() if (len(aline) < min_chars or aline[0].islower() or len(aline) > max_chars) or random.randrange(num + 2): continue line = aline #Be polite, put things back in the place you found them afile.seek(0) return line def prepare_quote(text_file, signature=" -- Hamlet", max_chars = 123, min_chars = 5,): line = random_line(text_file, max_chars, min_chars) number = random.randrange(1,1000,2) line = "{0}] " + line + signature line = line.format(number) return line
8307188a5cbaf0dab824b58a6436affdea1b039b
mesonwrap/inventory.py
mesonwrap/inventory.py
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
Add wrapdevtools to restricted projects
Add wrapdevtools to restricted projects
Python
apache-2.0
mesonbuild/wrapweb,mesonbuild/wrapweb,mesonbuild/wrapweb
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS Add wrapdevtools to restricted projects
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
<commit_before>_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS <commit_msg>Add wrapdevtools to restricted projects<commit_after>
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS Add wrapdevtools to restricted projects_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
<commit_before>_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS <commit_msg>Add wrapdevtools to restricted projects<commit_after>_ORGANIZATION = 'mesonbuild' _RESTRICTED_PROJECTS = [ 'meson', 'meson-ci', 'mesonwrap', 'wrapdevtools', 'wrapweb', ] _RESTRICTED_ORG_PROJECTS = [ _ORGANIZATION + '/' + proj for proj in _RESTRICTED_PROJECTS ] def is_wrap_project_name(project: str) -> bool: return project not in _RESTRICTED_PROJECTS def is_wrap_full_project_name(full_project: str) -> bool: return full_project not in _RESTRICTED_ORG_PROJECTS
82f2fb3c3956e4ad4c65b03b3918ea409593d4ef
gcloud/__init__.py
gcloud/__init__.py
"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2'
"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
Read module version from setup.py
Read module version from setup.py
Python
apache-2.0
googleapis/google-cloud-python,blowmage/gcloud-python,thesandlord/gcloud-python,calpeyser/google-cloud-python,CyrusBiotechnology/gcloud-python,waprin/gcloud-python,VitalLabs/gcloud-python,waprin/google-cloud-python,jonparrott/google-cloud-python,Fkawala/gcloud-python,tswast/google-cloud-python,waprin/gcloud-python,dhermes/gcloud-python,quom/google-cloud-python,tseaver/google-cloud-python,tartavull/google-cloud-python,optimizely/gcloud-python,lucemia/gcloud-python,CyrusBiotechnology/gcloud-python,tswast/google-cloud-python,VitalLabs/gcloud-python,GrimDerp/gcloud-python,tseaver/gcloud-python,blowmage/gcloud-python,vj-ug/gcloud-python,jbuberel/gcloud-python,tswast/google-cloud-python,jonparrott/google-cloud-python,tseaver/google-cloud-python,tartavull/google-cloud-python,dhermes/google-cloud-python,tseaver/google-cloud-python,dhermes/google-cloud-python,quom/google-cloud-python,tseaver/gcloud-python,optimizely/gcloud-python,jonparrott/gcloud-python,dhermes/gcloud-python,googleapis/google-cloud-python,EugenePig/gcloud-python,EugenePig/gcloud-python,GrimDerp/gcloud-python,lucemia/gcloud-python,daspecster/google-cloud-python,jonparrott/gcloud-python,daspecster/google-cloud-python,jgeewax/gcloud-python,GoogleCloudPlatform/gcloud-python,jbuberel/gcloud-python,waprin/google-cloud-python,elibixby/gcloud-python,thesandlord/gcloud-python,GoogleCloudPlatform/gcloud-python,calpeyser/google-cloud-python,Fkawala/gcloud-python,elibixby/gcloud-python,dhermes/google-cloud-python,optimizely/gcloud-python,vj-ug/gcloud-python,jgeewax/gcloud-python
"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2' Read module version from setup.py
"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
<commit_before>"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2' <commit_msg>Read module version from setup.py<commit_after>
"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2' Read module version from setup.py"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
<commit_before>"""GCloud API access in idiomatic Python.""" __version__ = '0.02.2' <commit_msg>Read module version from setup.py<commit_after>"""GCloud API access in idiomatic Python.""" from pkg_resources import get_distribution __version__ = get_distribution('gcloud').version
2e88154eb9ea86bcf686e3cf4c92d5b696ec6efc
neo4j/__init__.py
neo4j/__init__.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ # Export current (v1) API. This should be updated to export the latest # version of the API when a new one is added. This gives the option to # `import neo4j.vX` for a specific version or `import neo4j` for the # latest. from .v1.constants import * from .v1.exceptions import * from .v1.session import * from .v1.types import *
Add option to import neo4j for latest version
Add option to import neo4j for latest version
Python
apache-2.0
neo4j/neo4j-python-driver,neo4j/neo4j-python-driver
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ Add option to import neo4j for latest version
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ # Export current (v1) API. This should be updated to export the latest # version of the API when a new one is added. This gives the option to # `import neo4j.vX` for a specific version or `import neo4j` for the # latest. from .v1.constants import * from .v1.exceptions import * from .v1.session import * from .v1.types import *
<commit_before>#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ <commit_msg>Add option to import neo4j for latest version<commit_after>
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ # Export current (v1) API. This should be updated to export the latest # version of the API when a new one is added. This gives the option to # `import neo4j.vX` for a specific version or `import neo4j` for the # latest. from .v1.constants import * from .v1.exceptions import * from .v1.session import * from .v1.types import *
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ Add option to import neo4j for latest version#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ # Export current (v1) API. This should be updated to export the latest # version of the API when a new one is added. This gives the option to # `import neo4j.vX` for a specific version or `import neo4j` for the # latest. from .v1.constants import * from .v1.exceptions import * from .v1.session import * from .v1.types import *
<commit_before>#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ <commit_msg>Add option to import neo4j for latest version<commit_after>#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2016 "Neo Technology," # Network Engine for Objects in Lund AB [http://neotechnology.com] # # This file is part of Neo4j. # # 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 .meta import version as __version__ # Export current (v1) API. This should be updated to export the latest # version of the API when a new one is added. This gives the option to # `import neo4j.vX` for a specific version or `import neo4j` for the # latest. from .v1.constants import * from .v1.exceptions import * from .v1.session import * from .v1.types import *
dda54c9826b79e213432e5da1d03d171a293d42b
utils/celery_worker.py
utils/celery_worker.py
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Figure out how to do batching. TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
Move rabbit vars to globals
Move rabbit vars to globals
Python
mpl-2.0
MITRECND/multiscanner,mitre/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results Move rabbit vars to globals
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Figure out how to do batching. TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
<commit_before>import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results <commit_msg>Move rabbit vars to globals<commit_after>
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Figure out how to do batching. TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results Move rabbit vars to globalsimport os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Figure out how to do batching. TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
<commit_before>import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results <commit_msg>Move rabbit vars to globals<commit_after>import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery RABBIT_USER = 'guest' RABBIT_HOST = 'localhost' app = Celery('celery_worker', broker='pyamqp://%s@%s//' % (RABBIT_USER, RABBIT_HOST)) @app.task def multiscanner_celery(filelist, config=multiscanner.CONFIG): ''' TODO: Figure out how to do batching. TODO: Add other ars + config options... This function essentially takes in a file list and runs multiscanner on them. Results are stored in the storage configured in storage.ini. Usage: from celery_worker import multiscanner_celery multiscanner_celery.delay([list, of, files, to, scan]) ''' storage_conf = multiscanner.common.get_storage_config_path(config) storage_handler = multiscanner.storage.StorageHandler(configfile=storage_conf) resultlist = multiscanner.multiscan(filelist, configfile=config) results = multiscanner.parse_reports(resultlist, python=True) storage_handler.store(results, wait=False) storage_handler.close() return results
205682120cfa77aca2b279e2ee87065e489b5e69
settings_example.py
settings_example.py
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ # TODO: Allow separate settings for different subject matches. # Email formats and CSV names may change over the years, and this could # be detected by subject matches. import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
Remove TODO from settings example.
Remove TODO from settings example. This work has been started with the Yaml settings file.
Python
mit
AustralianAntarcticDataCentre/save_emails_to_files,AustralianAntarcticDataCentre/save_emails_to_files
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ # TODO: Allow separate settings for different subject matches. # Email formats and CSV names may change over the years, and this could # be detected by subject matches. import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') Remove TODO from settings example. This work has been started with the Yaml settings file.
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
<commit_before>""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ # TODO: Allow separate settings for different subject matches. # Email formats and CSV names may change over the years, and this could # be detected by subject matches. import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') <commit_msg>Remove TODO from settings example. This work has been started with the Yaml settings file.<commit_after>
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ # TODO: Allow separate settings for different subject matches. # Email formats and CSV names may change over the years, and this could # be detected by subject matches. import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') Remove TODO from settings example. This work has been started with the Yaml settings file.""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
<commit_before>""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ # TODO: Allow separate settings for different subject matches. # Email formats and CSV names may change over the years, and this could # be detected by subject matches. import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password') <commit_msg>Remove TODO from settings example. This work has been started with the Yaml settings file.<commit_after>""" Example settings module. This should be copied as `settings.py` and the values modified there. That file is ignored by the repo, since it will contain environment specific and sensitive information (like passwords). """ import logging import os import re import yaml from imap import EmailCheckError, EmailServer from postgresql import DatabaseServer # If this is set to a valid path, all CSV files extracted from emails will be # stored in sub-folders within it. CSV_FOLDER = os.getcwd() SETTINGS_YAML_PATH = os.path.join(os.getcwd(), 'settings.yaml') LOGGING_FORMAT = ''' - file: %(pathname)s level: %(levelname)s line: %(lineno)s message: | %(message)s time: %(asctime)s '''.strip() LOGGING_LEVEL = logging.DEBUG def get_csv_file_types(): csv_file_types = None with open(SETTINGS_YAML_PATH) as r: csv_file_types = yaml.load(r) return csv_file_types def get_database_client(): con = 'my_username/my_password@database.example.com:5432/my_database' return DatabaseServer(con) def get_email_client(): return EmailServer('mail.example.com', 'my_username', 'my_password')
df3ab8bcae326ceb157106d076eaa90f13717107
astroquery/astrometry_net/tests/setup_package.py
astroquery/astrometry_net/tests/setup_package.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths}
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths}
Include gzipped fits files in test data
Include gzipped fits files in test data
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths} Include gzipped fits files in test data
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths}
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths} <commit_msg>Include gzipped fits files in test data<commit_after>
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths}
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths} Include gzipped fits files in test data# Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths}
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths} <commit_msg>Include gzipped fits files in test data<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.fit')] + [os.path.join('data', '*.fit.gz')] # finally construct and return a dict for the sub module return {'astroquery.astrometry_net.tests': paths}
cee291799e9aa19e23593b3618a45f7cee16d0ed
modules/cah/CAHGame.py
modules/cah/CAHGame.py
#Cards Against Humanity game engine class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck ={ 'questions' : [ "_? There's an app for that.", "I got 99 problems but _ ain't one.", ], 'answers' : [ "Flying sex snakes.", "Michelle Obama's arms.", "German dungeon porn.", "White people.", "Getting so angry that you pop a boner.", "Freedom of Speech", ] } #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass def draw(self, color): '''Draws a random card of <color> from the databse and returns a Card object.''' pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False #Utiliy class for a Card class Card: def __init__(self, color, body): self.color = color self.body = body
#Cards Against Humanity game engine from cards import Deck, NoMoreCards class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck = Deck() #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False
Use the new Deck class
Use the new Deck class
Python
mit
tcoppi/scrappy,tcoppi/scrappy,johnmiked15/scrappy,johnmiked15/scrappy
#Cards Against Humanity game engine class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck ={ 'questions' : [ "_? There's an app for that.", "I got 99 problems but _ ain't one.", ], 'answers' : [ "Flying sex snakes.", "Michelle Obama's arms.", "German dungeon porn.", "White people.", "Getting so angry that you pop a boner.", "Freedom of Speech", ] } #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass def draw(self, color): '''Draws a random card of <color> from the databse and returns a Card object.''' pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False #Utiliy class for a Card class Card: def __init__(self, color, body): self.color = color self.body = body Use the new Deck class
#Cards Against Humanity game engine from cards import Deck, NoMoreCards class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck = Deck() #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False
<commit_before>#Cards Against Humanity game engine class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck ={ 'questions' : [ "_? There's an app for that.", "I got 99 problems but _ ain't one.", ], 'answers' : [ "Flying sex snakes.", "Michelle Obama's arms.", "German dungeon porn.", "White people.", "Getting so angry that you pop a boner.", "Freedom of Speech", ] } #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass def draw(self, color): '''Draws a random card of <color> from the databse and returns a Card object.''' pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False #Utiliy class for a Card class Card: def __init__(self, color, body): self.color = color self.body = body <commit_msg>Use the new Deck class<commit_after>
#Cards Against Humanity game engine from cards import Deck, NoMoreCards class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck = Deck() #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False
#Cards Against Humanity game engine class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck ={ 'questions' : [ "_? There's an app for that.", "I got 99 problems but _ ain't one.", ], 'answers' : [ "Flying sex snakes.", "Michelle Obama's arms.", "German dungeon porn.", "White people.", "Getting so angry that you pop a boner.", "Freedom of Speech", ] } #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass def draw(self, color): '''Draws a random card of <color> from the databse and returns a Card object.''' pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False #Utiliy class for a Card class Card: def __init__(self, color, body): self.color = color self.body = body Use the new Deck class#Cards Against Humanity game engine from cards import Deck, NoMoreCards class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck = Deck() #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False
<commit_before>#Cards Against Humanity game engine class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck ={ 'questions' : [ "_? There's an app for that.", "I got 99 problems but _ ain't one.", ], 'answers' : [ "Flying sex snakes.", "Michelle Obama's arms.", "German dungeon porn.", "White people.", "Getting so angry that you pop a boner.", "Freedom of Speech", ] } #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass def draw(self, color): '''Draws a random card of <color> from the databse and returns a Card object.''' pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False #Utiliy class for a Card class Card: def __init__(self, color, body): self.color = color self.body = body <commit_msg>Use the new Deck class<commit_after>#Cards Against Humanity game engine from cards import Deck, NoMoreCards class CAHGame: def __init__(self): self.status = "Loaded CAHGame." #flag to keep track of whether or not game is running self.running = False #list of active players in a game self.players = [] #dummy with a small deck for testing. #replace with actual card loading from DB later self.deck = Deck() #add a new player to the game def add_player(self, name): self.players.append(Player(name)) #start the game def start(self): pass #Utility class to manage Players class Player: def __init__(self, name): self.name = name #Player name (IRC nick) self.score = 0 self.hand = {} self.isCzar = False
962fd486afe25031d5fb6332f623e970b694b321
tsstats/tests/test_config.py
tsstats/tests/test_config.py
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html'
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' def test_read(): config = load(path='tsstats/tests/res/config.ini') # test defaults assert not config.getboolean('General', 'debug') # test written values assert config.get('General', 'log') == 'tsstats/tests/res/test.log' assert config.get('General', 'output') == 'tsstats/tests/res/output.html'
Test reading config from disk again
Test reading config from disk again
Python
mit
Thor77/TeamspeakStats,Thor77/TeamspeakStats
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' Test reading config from disk again
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' def test_read(): config = load(path='tsstats/tests/res/config.ini') # test defaults assert not config.getboolean('General', 'debug') # test written values assert config.get('General', 'log') == 'tsstats/tests/res/test.log' assert config.get('General', 'output') == 'tsstats/tests/res/output.html'
<commit_before>import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' <commit_msg>Test reading config from disk again<commit_after>
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' def test_read(): config = load(path='tsstats/tests/res/config.ini') # test defaults assert not config.getboolean('General', 'debug') # test written values assert config.get('General', 'log') == 'tsstats/tests/res/test.log' assert config.get('General', 'output') == 'tsstats/tests/res/output.html'
import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' Test reading config from disk againimport pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' def test_read(): config = load(path='tsstats/tests/res/config.ini') # test defaults assert not config.getboolean('General', 'debug') # test written values assert config.get('General', 'log') == 'tsstats/tests/res/test.log' assert config.get('General', 'output') == 'tsstats/tests/res/output.html'
<commit_before>import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' <commit_msg>Test reading config from disk again<commit_after>import pytest from tsstats.config import load @pytest.fixture def config(): return load() def test_config(config): assert not config.getboolean('General', 'debug') assert config.getboolean('General', 'onlinedc') config.set('General', 'idmap', 'tsstats/tests/res/id_map.json') assert config.get('General', 'idmap') ==\ 'tsstats/tests/res/id_map.json' config.set('General', 'log', 'tsstats/tests/res/test.log') assert config.get('General', 'log') == 'tsstats/tests/res/test.log' config.set('General', 'output', 'output.html') assert config.get('General', 'output') == 'output.html' def test_read(): config = load(path='tsstats/tests/res/config.ini') # test defaults assert not config.getboolean('General', 'debug') # test written values assert config.get('General', 'log') == 'tsstats/tests/res/test.log' assert config.get('General', 'output') == 'tsstats/tests/res/output.html'
a2f4b30cab3dafe119e42181772f4d77b575ec0e
05/test_find_password.py
05/test_find_password.py
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30'
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' assert find_password('abc', length=8, complex=True) == '05ace8e3'
Add test for part 2 of day 5.
Add test for part 2 of day 5.
Python
mit
machinelearningdeveloper/aoc_2016
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' Add test for part 2 of day 5.
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' assert find_password('abc', length=8, complex=True) == '05ace8e3'
<commit_before>import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' <commit_msg>Add test for part 2 of day 5.<commit_after>
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' assert find_password('abc', length=8, complex=True) == '05ace8e3'
import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' Add test for part 2 of day 5.import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' assert find_password('abc', length=8, complex=True) == '05ace8e3'
<commit_before>import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' <commit_msg>Add test for part 2 of day 5.<commit_after>import unittest from find_password import find_password class TestFindPassword(unittest.TestCase): def test_find_password(self): assert find_password('abc', length=8) == '18f47a30' assert find_password('abc', length=8, complex=True) == '05ace8e3'
6943bb0c665cd40e7516b7277fe55af95b814ccb
playa/conf.py
playa/conf.py
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = ['/Volumes/Storage/Music/iTunes/iTunes Media/Music/Blink-182/'] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = [] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')
Remove my awesome default audio path
Remove my awesome default audio path
Python
apache-2.0
disqus/playa,disqus/playa
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = ['/Volumes/Storage/Music/iTunes/iTunes Media/Music/Blink-182/'] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')Remove my awesome default audio path
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = [] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')
<commit_before>""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = ['/Volumes/Storage/Music/iTunes/iTunes Media/Music/Blink-182/'] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')<commit_msg>Remove my awesome default audio path<commit_after>
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = [] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')
""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = ['/Volumes/Storage/Music/iTunes/iTunes Media/Music/Blink-182/'] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')Remove my awesome default audio path""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = [] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')
<commit_before>""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = ['/Volumes/Storage/Music/iTunes/iTunes Media/Music/Blink-182/'] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')<commit_msg>Remove my awesome default audio path<commit_after>""" Represents the default values for all Sentry settings. """ import logging import os import os.path class PlayaConfig(object): ROOT = os.path.normpath(os.path.dirname(__file__)) DEBUG = True SQLITE3_DATABASE = os.path.join(ROOT, 'playa.db') AUDIO_PATHS = [] WEB_HOST = '0.0.0.0' WEB_PORT = 9000 WEB_LOG_FILE = os.path.join(ROOT, 'playa.log') WEB_PID_FILE = os.path.join(ROOT, 'playa.pid')
e64101e31fadaf54f8c1d7a6acb9b302060efefc
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
Upgrade libchromiumcontent to use the static_library build
Upgrade libchromiumcontent to use the static_library build
Python
mit
wan-qy/electron,deed02392/electron,John-Lin/electron,aliib/electron,nicobot/electron,Andrey-Pavlov/electron,leethomas/electron,Jonekee/electron,simongregory/electron,leolujuyi/electron,michaelchiche/electron,greyhwndz/electron,sircharleswatson/electron,jacksondc/electron,jsutcodes/electron,bpasero/electron,tylergibson/electron,christian-bromann/electron,egoist/electron,medixdev/electron,howmuchcomputer/electron,egoist/electron,michaelchiche/electron,kenmozi/electron,brave/muon,smczk/electron,seanchas116/electron,ianscrivener/electron,Zagorakiss/electron,pandoraui/electron,renaesop/electron,shiftkey/electron,farmisen/electron,astoilkov/electron,nicobot/electron,thomsonreuters/electron,beni55/electron,setzer777/electron,vHanda/electron,Zagorakiss/electron,JussMee15/electron,christian-bromann/electron,SufianHassan/electron,shaundunne/electron,fomojola/electron,aichingm/electron,webmechanicx/electron,the-ress/electron,neutrous/electron,chriskdon/electron,pombredanne/electron,zhakui/electron,etiktin/electron,smczk/electron,dongjoon-hyun/electron,iftekeriba/electron,tylergibson/electron,Rokt33r/electron,vipulroxx/electron,kazupon/electron,egoist/electron,fritx/electron,digideskio/electron,bobwol/electron,bright-sparks/electron,davazp/electron,rajatsingla28/electron,beni55/electron,mattotodd/electron,abhishekgahlot/electron,ankitaggarwal011/electron,JussMee15/electron,kenmozi/electron,meowlab/electron,MaxGraey/electron,tonyganch/electron,miniak/electron,kcrt/electron,egoist/electron,roadev/electron,Zagorakiss/electron,iftekeriba/electron,ervinb/electron,micalan/electron,jcblw/electron,mubassirhayat/electron,carsonmcdonald/electron,rreimann/electron,yan-foto/electron,timruffles/electron,JesselJohn/electron,tonyganch/electron,thompsonemerson/electron,destan/electron,gerhardberger/electron,icattlecoder/electron,brave/electron,sircharleswatson/electron,noikiy/electron,lrlna/electron,takashi/electron,vipulroxx/electron,sshiting/electron,systembugtj/electron,beni55/electron,bpasero/electron,jacksondc/electron,kenmozi/electron,Jacobichou/electron,carsonmcdonald/electron,voidbridge/electron,smczk/electron,trigrass2/electron,tinydew4/electron,noikiy/electron,soulteary/electron,aliib/electron,biblerule/UMCTelnetHub,jhen0409/electron,the-ress/electron,jjz/electron,bpasero/electron,mirrh/electron,natgolov/electron,hokein/atom-shell,Jonekee/electron,gamedevsam/electron,saronwei/electron,rsvip/electron,pandoraui/electron,jannishuebl/electron,gabriel/electron,electron/electron,simonfork/electron,MaxWhere/electron,eric-seekas/electron,gerhardberger/electron,etiktin/electron,thomsonreuters/electron,bright-sparks/electron,biblerule/UMCTelnetHub,preco21/electron,BionicClick/electron,Jacobichou/electron,sshiting/electron,jtburke/electron,christian-bromann/electron,brave/muon,icattlecoder/electron,astoilkov/electron,jiaz/electron,miniak/electron,shockone/electron,shennushi/electron,Ivshti/electron,brenca/electron,Gerhut/electron,anko/electron,tinydew4/electron,voidbridge/electron,setzer777/electron,trankmichael/electron,simongregory/electron,pirafrank/electron,mrwizard82d1/electron,joaomoreno/atom-shell,jlhbaseball15/electron,jcblw/electron,simongregory/electron,Jonekee/electron,kazupon/electron,miniak/electron,adamjgray/electron,farmisen/electron,medixdev/electron,minggo/electron,bbondy/electron,twolfson/electron,roadev/electron,nekuz0r/electron,oiledCode/electron,davazp/electron,brenca/electron,sircharleswatson/electron,zhakui/electron,ianscrivener/electron,vipulroxx/electron,jhen0409/electron,coderhaoxin/electron,setzer777/electron,vaginessa/electron,eriser/electron,Gerhut/electron,cqqccqc/electron,jiaz/electron,Andrey-Pavlov/electron,electron/electron,jsutcodes/electron,IonicaBizauKitchen/electron,abhishekgahlot/electron,astoilkov/electron,arusakov/electron,chriskdon/electron,evgenyzinoviev/electron,bitemyapp/electron,xfstudio/electron,rajatsingla28/electron,hokein/atom-shell,yan-foto/electron,cqqccqc/electron,deed02392/electron,sshiting/electron,egoist/electron,jiaz/electron,arusakov/electron,davazp/electron,saronwei/electron,kokdemo/electron,mattotodd/electron,Faiz7412/electron,leolujuyi/electron,takashi/electron,Evercoder/electron,jaanus/electron,Evercoder/electron,soulteary/electron,leethomas/electron,miniak/electron,JussMee15/electron,sircharleswatson/electron,cqqccqc/electron,fffej/electron,jannishuebl/electron,minggo/electron,kcrt/electron,aichingm/electron,saronwei/electron,SufianHassan/electron,brave/electron,rsvip/electron,evgenyzinoviev/electron,kostia/electron,thomsonreuters/electron,aliib/electron,hokein/atom-shell,shennushi/electron,d-salas/electron,trigrass2/electron,ankitaggarwal011/electron,cos2004/electron,nicobot/electron,bpasero/electron,adcentury/electron,yalexx/electron,tincan24/electron,pandoraui/electron,jcblw/electron,fritx/electron,mrwizard82d1/electron,hokein/atom-shell,icattlecoder/electron,webmechanicx/electron,astoilkov/electron,bbondy/electron,mattdesl/electron,jtburke/electron,Floato/electron,bruce/electron,Andrey-Pavlov/electron,eric-seekas/electron,d-salas/electron,IonicaBizauKitchen/electron,LadyNaggaga/electron,stevemao/electron,bright-sparks/electron,benweissmann/electron,Rokt33r/electron,bitemyapp/electron,tinydew4/electron,leftstick/electron,tylergibson/electron,thingsinjars/electron,anko/electron,preco21/electron,kcrt/electron,pandoraui/electron,digideskio/electron,takashi/electron,Rokt33r/electron,mirrh/electron,shockone/electron,meowlab/electron,shaundunne/electron,rsvip/electron,arusakov/electron,LadyNaggaga/electron,lrlna/electron,jsutcodes/electron,MaxGraey/electron,RIAEvangelist/electron,nicobot/electron,gerhardberger/electron,fffej/electron,shennushi/electron,trankmichael/electron,gabrielPeart/electron,wan-qy/electron,robinvandernoord/electron,destan/electron,fomojola/electron,thomsonreuters/electron,medixdev/electron,edulan/electron,ervinb/electron,tincan24/electron,arturts/electron,xiruibing/electron,Zagorakiss/electron,meowlab/electron,ankitaggarwal011/electron,coderhaoxin/electron,jonatasfreitasv/electron,dkfiresky/electron,brave/muon,dongjoon-hyun/electron,voidbridge/electron,miniak/electron,leftstick/electron,DivyaKMenon/electron,wan-qy/electron,pirafrank/electron,mattotodd/electron,rreimann/electron,dongjoon-hyun/electron,seanchas116/electron,gabriel/electron,trigrass2/electron,DivyaKMenon/electron,sircharleswatson/electron,farmisen/electron,xiruibing/electron,bobwol/electron,d-salas/electron,matiasinsaurralde/electron,Gerhut/electron,minggo/electron,adcentury/electron,yan-foto/electron,micalan/electron,seanchas116/electron,deed02392/electron,wolfflow/electron,thingsinjars/electron,shiftkey/electron,Gerhut/electron,leftstick/electron,iftekeriba/electron,rreimann/electron,MaxWhere/electron,medixdev/electron,Floato/electron,shockone/electron,twolfson/electron,LadyNaggaga/electron,sshiting/electron,chriskdon/electron,baiwyc119/electron,smczk/electron,ervinb/electron,mhkeller/electron,fritx/electron,coderhaoxin/electron,jhen0409/electron,thompsonemerson/electron,pombredanne/electron,noikiy/electron,jhen0409/electron,faizalpribadi/electron,LadyNaggaga/electron,bobwol/electron,twolfson/electron,mirrh/electron,eric-seekas/electron,tonyganch/electron,brave/electron,sky7sea/electron,thingsinjars/electron,pombredanne/electron,edulan/electron,RIAEvangelist/electron,Ivshti/electron,mhkeller/electron,kazupon/electron,joaomoreno/atom-shell,RobertJGabriel/electron,natgolov/electron,benweissmann/electron,Rokt33r/electron,pombredanne/electron,setzer777/electron,gabriel/electron,cos2004/electron,stevemao/electron,fabien-d/electron,pirafrank/electron,fomojola/electron,shaundunne/electron,baiwyc119/electron,mjaniszew/electron,darwin/electron,ervinb/electron,BionicClick/electron,thomsonreuters/electron,Floato/electron,evgenyzinoviev/electron,coderhaoxin/electron,Rokt33r/electron,lrlna/electron,benweissmann/electron,SufianHassan/electron,bobwol/electron,bbondy/electron,rajatsingla28/electron,gamedevsam/electron,nicholasess/electron,roadev/electron,synaptek/electron,electron/electron,christian-bromann/electron,bitemyapp/electron,rreimann/electron,greyhwndz/electron,lrlna/electron,zhakui/electron,neutrous/electron,systembugtj/electron,tinydew4/electron,leethomas/electron,SufianHassan/electron,jsutcodes/electron,gerhardberger/electron,rhencke/electron,setzer777/electron,gbn972/electron,trankmichael/electron,rajatsingla28/electron,pombredanne/electron,Evercoder/electron,edulan/electron,farmisen/electron,JesselJohn/electron,mjaniszew/electron,jacksondc/electron,vipulroxx/electron,shiftkey/electron,abhishekgahlot/electron,meowlab/electron,JussMee15/electron,ankitaggarwal011/electron,minggo/electron,Floato/electron,farmisen/electron,aaron-goshine/electron,jaanus/electron,dongjoon-hyun/electron,jlhbaseball15/electron,LadyNaggaga/electron,jannishuebl/electron,fomojola/electron,RobertJGabriel/electron,oiledCode/electron,joaomoreno/atom-shell,tomashanacek/electron,bwiggs/electron,soulteary/electron,bpasero/electron,fabien-d/electron,trigrass2/electron,joaomoreno/atom-shell,preco21/electron,timruffles/electron,jcblw/electron,fomojola/electron,yan-foto/electron,deed02392/electron,DivyaKMenon/electron,seanchas116/electron,jaanus/electron,aecca/electron,subblue/electron,miniak/electron,synaptek/electron,bwiggs/electron,vaginessa/electron,John-Lin/electron,GoooIce/electron,meowlab/electron,wan-qy/electron,bruce/electron,jannishuebl/electron,wolfflow/electron,Neron-X5/electron,davazp/electron,tincan24/electron,renaesop/electron,jonatasfreitasv/electron,ankitaggarwal011/electron,d-salas/electron,abhishekgahlot/electron,subblue/electron,jacksondc/electron,tomashanacek/electron,IonicaBizauKitchen/electron,Jacobichou/electron,aecca/electron,yalexx/electron,leolujuyi/electron,Floato/electron,Jonekee/electron,noikiy/electron,timruffles/electron,IonicaBizauKitchen/electron,jiaz/electron,brave/muon,meowlab/electron,gerhardberger/electron,gerhardberger/electron,nekuz0r/electron,felixrieseberg/electron,dkfiresky/electron,timruffles/electron,dahal/electron,minggo/electron,felixrieseberg/electron,stevekinney/electron,eriser/electron,the-ress/electron,joneit/electron,xfstudio/electron,mattdesl/electron,oiledCode/electron,smczk/electron,trigrass2/electron,dahal/electron,kenmozi/electron,mattdesl/electron,bright-sparks/electron,chriskdon/electron,voidbridge/electron,adcentury/electron,aaron-goshine/electron,cos2004/electron,vHanda/electron,setzer777/electron,voidbridge/electron,subblue/electron,sky7sea/electron,sky7sea/electron,preco21/electron,dkfiresky/electron,faizalpribadi/electron,benweissmann/electron,rsvip/electron,howmuchcomputer/electron,micalan/electron,yan-foto/electron,neutrous/electron,mhkeller/electron,Evercoder/electron,joaomoreno/atom-shell,eric-seekas/electron,tincan24/electron,jlord/electron,John-Lin/electron,adamjgray/electron,dongjoon-hyun/electron,the-ress/electron,RobertJGabriel/electron,chrisswk/electron,cqqccqc/electron,posix4e/electron,John-Lin/electron,tomashanacek/electron,kenmozi/electron,rhencke/electron,wan-qy/electron,aecca/electron,RobertJGabriel/electron,kostia/electron,tinydew4/electron,fffej/electron,rhencke/electron,nicholasess/electron,etiktin/electron,carsonmcdonald/electron,cos2004/electron,d-salas/electron,jcblw/electron,destan/electron,jacksondc/electron,thompsonemerson/electron,aaron-goshine/electron,anko/electron,greyhwndz/electron,GoooIce/electron,robinvandernoord/electron,rsvip/electron,faizalpribadi/electron,icattlecoder/electron,twolfson/electron,systembugtj/electron,vipulroxx/electron,leethomas/electron,rhencke/electron,electron/electron,fritx/electron,bruce/electron,Rokt33r/electron,shockone/electron,shockone/electron,bpasero/electron,bitemyapp/electron,gbn972/electron,BionicClick/electron,aaron-goshine/electron,Jacobichou/electron,matiasinsaurralde/electron,chriskdon/electron,nicholasess/electron,leftstick/electron,howmuchcomputer/electron,edulan/electron,bruce/electron,nicholasess/electron,MaxGraey/electron,Faiz7412/electron,vHanda/electron,simongregory/electron,adamjgray/electron,joneit/electron,digideskio/electron,JussMee15/electron,BionicClick/electron,renaesop/electron,howmuchcomputer/electron,rajatsingla28/electron,cos2004/electron,nicobot/electron,brave/electron,jjz/electron,robinvandernoord/electron,destan/electron,fabien-d/electron,brenca/electron,jaanus/electron,natgolov/electron,brenca/electron,IonicaBizauKitchen/electron,tincan24/electron,shennushi/electron,astoilkov/electron,adcentury/electron,gabrielPeart/electron,Gerhut/electron,leftstick/electron,evgenyzinoviev/electron,simonfork/electron,SufianHassan/electron,christian-bromann/electron,mattdesl/electron,tonyganch/electron,stevekinney/electron,michaelchiche/electron,jannishuebl/electron,shaundunne/electron,webmechanicx/electron,systembugtj/electron,gbn972/electron,xiruibing/electron,pirafrank/electron,renaesop/electron,d-salas/electron,anko/electron,minggo/electron,adcentury/electron,preco21/electron,gbn972/electron,adamjgray/electron,tomashanacek/electron,fireball-x/atom-shell,jcblw/electron,fireball-x/atom-shell,vipulroxx/electron,soulteary/electron,subblue/electron,jacksondc/electron,aliib/electron,thingsinjars/electron,mrwizard82d1/electron,rreimann/electron,kokdemo/electron,kostia/electron,lzpfmh/electron,MaxWhere/electron,adcentury/electron,SufianHassan/electron,aaron-goshine/electron,micalan/electron,mattotodd/electron,noikiy/electron,arusakov/electron,gabrielPeart/electron,leolujuyi/electron,dahal/electron,digideskio/electron,destan/electron,ianscrivener/electron,leolujuyi/electron,mirrh/electron,synaptek/electron,eric-seekas/electron,IonicaBizauKitchen/electron,oiledCode/electron,adamjgray/electron,aliib/electron,jiaz/electron,joneit/electron,deed02392/electron,jtburke/electron,yalexx/electron,fritx/electron,brenca/electron,aaron-goshine/electron,matiasinsaurralde/electron,howmuchcomputer/electron,bwiggs/electron,gamedevsam/electron,medixdev/electron,xfstudio/electron,Neron-X5/electron,bitemyapp/electron,GoooIce/electron,jlhbaseball15/electron,wolfflow/electron,gamedevsam/electron,Andrey-Pavlov/electron,michaelchiche/electron,neutrous/electron,Jacobichou/electron,wolfflow/electron,tylergibson/electron,bbondy/electron,bwiggs/electron,faizalpribadi/electron,saronwei/electron,roadev/electron,mattotodd/electron,BionicClick/electron,twolfson/electron,dkfiresky/electron,systembugtj/electron,Faiz7412/electron,jsutcodes/electron,aichingm/electron,oiledCode/electron,kazupon/electron,shaundunne/electron,zhakui/electron,RobertJGabriel/electron,felixrieseberg/electron,leolujuyi/electron,trigrass2/electron,thompsonemerson/electron,shennushi/electron,fabien-d/electron,gabrielPeart/electron,seanchas116/electron,darwin/electron,gabrielPeart/electron,GoooIce/electron,Faiz7412/electron,lzpfmh/electron,beni55/electron,jhen0409/electron,jlord/electron,kcrt/electron,benweissmann/electron,jonatasfreitasv/electron,pandoraui/electron,shennushi/electron,sky7sea/electron,aecca/electron,astoilkov/electron,icattlecoder/electron,gabriel/electron,brave/muon,vHanda/electron,pirafrank/electron,abhishekgahlot/electron,sshiting/electron,fireball-x/atom-shell,chrisswk/electron,jaanus/electron,felixrieseberg/electron,xfstudio/electron,chriskdon/electron,posix4e/electron,dkfiresky/electron,preco21/electron,RIAEvangelist/electron,stevemao/electron,Neron-X5/electron,Gerhut/electron,kcrt/electron,GoooIce/electron,vHanda/electron,bwiggs/electron,eric-seekas/electron,bitemyapp/electron,felixrieseberg/electron,howmuchcomputer/electron,xiruibing/electron,kokdemo/electron,mjaniszew/electron,aichingm/electron,iftekeriba/electron,evgenyzinoviev/electron,faizalpribadi/electron,mrwizard82d1/electron,stevemao/electron,takashi/electron,arturts/electron,leethomas/electron,tylergibson/electron,jlord/electron,fffej/electron,gbn972/electron,kenmozi/electron,brenca/electron,bright-sparks/electron,stevemao/electron,eriser/electron,sky7sea/electron,felixrieseberg/electron,pirafrank/electron,biblerule/UMCTelnetHub,renaesop/electron,gabriel/electron,lzpfmh/electron,simonfork/electron,bbondy/electron,lrlna/electron,michaelchiche/electron,jlhbaseball15/electron,ervinb/electron,baiwyc119/electron,kostia/electron,jiaz/electron,the-ress/electron,ianscrivener/electron,DivyaKMenon/electron,MaxGraey/electron,micalan/electron,kazupon/electron,the-ress/electron,oiledCode/electron,Zagorakiss/electron,baiwyc119/electron,jonatasfreitasv/electron,jaanus/electron,nicholasess/electron,chrisswk/electron,JussMee15/electron,John-Lin/electron,Andrey-Pavlov/electron,gamedevsam/electron,vaginessa/electron,robinvandernoord/electron,thomsonreuters/electron,leethomas/electron,medixdev/electron,chrisswk/electron,rajatsingla28/electron,davazp/electron,dahal/electron,rreimann/electron,carsonmcdonald/electron,mubassirhayat/electron,kcrt/electron,yalexx/electron,arturts/electron,chrisswk/electron,posix4e/electron,trankmichael/electron,edulan/electron,joneit/electron,nekuz0r/electron,xiruibing/electron,tomashanacek/electron,nekuz0r/electron,stevekinney/electron,gerhardberger/electron,Evercoder/electron,nicobot/electron,joneit/electron,jlord/electron,yalexx/electron,roadev/electron,stevekinney/electron,mrwizard82d1/electron,JesselJohn/electron,digideskio/electron,Evercoder/electron,simonfork/electron,vHanda/electron,brave/electron,roadev/electron,soulteary/electron,Faiz7412/electron,JesselJohn/electron,GoooIce/electron,icattlecoder/electron,gamedevsam/electron,arturts/electron,yan-foto/electron,arturts/electron,Ivshti/electron,ankitaggarwal011/electron,mubassirhayat/electron,xfstudio/electron,darwin/electron,carsonmcdonald/electron,mattotodd/electron,takashi/electron,hokein/atom-shell,jlhbaseball15/electron,lrlna/electron,MaxWhere/electron,tonyganch/electron,mjaniszew/electron,aliib/electron,darwin/electron,ervinb/electron,kokdemo/electron,mhkeller/electron,yalexx/electron,MaxWhere/electron,christian-bromann/electron,JesselJohn/electron,synaptek/electron,wolfflow/electron,beni55/electron,rhencke/electron,coderhaoxin/electron,fritx/electron,ianscrivener/electron,rhencke/electron,sshiting/electron,jannishuebl/electron,eriser/electron,vaginessa/electron,etiktin/electron,cos2004/electron,mirrh/electron,simongregory/electron,twolfson/electron,electron/electron,destan/electron,arturts/electron,synaptek/electron,sircharleswatson/electron,digideskio/electron,Neron-X5/electron,joneit/electron,thingsinjars/electron,Floato/electron,beni55/electron,jlhbaseball15/electron,mjaniszew/electron,Andrey-Pavlov/electron,tonyganch/electron,arusakov/electron,dkfiresky/electron,davazp/electron,dahal/electron,mubassirhayat/electron,mubassirhayat/electron,leftstick/electron,DivyaKMenon/electron,sky7sea/electron,joaomoreno/atom-shell,jtburke/electron,bobwol/electron,baiwyc119/electron,simongregory/electron,jhen0409/electron,natgolov/electron,deed02392/electron,coderhaoxin/electron,Zagorakiss/electron,edulan/electron,natgolov/electron,iftekeriba/electron,thompsonemerson/electron,jonatasfreitasv/electron,electron/electron,jsutcodes/electron,shiftkey/electron,MaxGraey/electron,shiftkey/electron,kostia/electron,Jonekee/electron,aecca/electron,farmisen/electron,nicholasess/electron,kazupon/electron,bpasero/electron,anko/electron,matiasinsaurralde/electron,bruce/electron,webmechanicx/electron,mattdesl/electron,gabriel/electron,aichingm/electron,biblerule/UMCTelnetHub,stevekinney/electron,JesselJohn/electron,vaginessa/electron,seanchas116/electron,John-Lin/electron,Ivshti/electron,posix4e/electron,benweissmann/electron,Neron-X5/electron,jjz/electron,eriser/electron,thompsonemerson/electron,wan-qy/electron,tinydew4/electron,jonatasfreitasv/electron,fabien-d/electron,neutrous/electron,synaptek/electron,greyhwndz/electron,MaxWhere/electron,saronwei/electron,noikiy/electron,tylergibson/electron,wolfflow/electron,jjz/electron,bobwol/electron,thingsinjars/electron,RIAEvangelist/electron,takashi/electron,fireball-x/atom-shell,micalan/electron,darwin/electron,bbondy/electron,subblue/electron,webmechanicx/electron,jjz/electron,michaelchiche/electron,Jacobichou/electron,zhakui/electron,matiasinsaurralde/electron,gbn972/electron,Ivshti/electron,fomojola/electron,renaesop/electron,shockone/electron,kokdemo/electron,etiktin/electron,subblue/electron,biblerule/UMCTelnetHub,bruce/electron,robinvandernoord/electron,posix4e/electron,zhakui/electron,mhkeller/electron,smczk/electron,etiktin/electron,iftekeriba/electron,faizalpribadi/electron,carsonmcdonald/electron,BionicClick/electron,arusakov/electron,timruffles/electron,cqqccqc/electron,Neron-X5/electron,lzpfmh/electron,eriser/electron,electron/electron,pombredanne/electron,jjz/electron,bright-sparks/electron,simonfork/electron,RIAEvangelist/electron,LadyNaggaga/electron,aecca/electron,RIAEvangelist/electron,anko/electron,mrwizard82d1/electron,greyhwndz/electron,evgenyzinoviev/electron,xiruibing/electron,mjaniszew/electron,abhishekgahlot/electron,jtburke/electron,mirrh/electron,mhkeller/electron,lzpfmh/electron,tomashanacek/electron,neutrous/electron,fffej/electron,simonfork/electron,RobertJGabriel/electron,biblerule/UMCTelnetHub,baiwyc119/electron,egoist/electron,jlord/electron,Jonekee/electron,jtburke/electron,stevemao/electron,webmechanicx/electron,voidbridge/electron,kokdemo/electron,cqqccqc/electron,vaginessa/electron,the-ress/electron,brave/electron,adamjgray/electron,gabrielPeart/electron,systembugtj/electron,matiasinsaurralde/electron,ianscrivener/electron,nekuz0r/electron,kostia/electron,trankmichael/electron,lzpfmh/electron,natgolov/electron,robinvandernoord/electron,bwiggs/electron,nekuz0r/electron,mattdesl/electron,shaundunne/electron,fffej/electron,DivyaKMenon/electron,posix4e/electron,saronwei/electron,xfstudio/electron,aichingm/electron,stevekinney/electron,shiftkey/electron,trankmichael/electron,dongjoon-hyun/electron,dahal/electron,pandoraui/electron,soulteary/electron,brave/muon,fireball-x/atom-shell,greyhwndz/electron,tincan24/electron
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode Upgrade libchromiumcontent to use the static_library build
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
<commit_before>#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode <commit_msg>Upgrade libchromiumcontent to use the static_library build<commit_after>
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode Upgrade libchromiumcontent to use the static_library build#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
<commit_before>#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'c01b10faf0d478e48f537210ec263fabd551578d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode <commit_msg>Upgrade libchromiumcontent to use the static_library build<commit_after>#!/usr/bin/env python import platform import sys BASE_URL = 'http://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = 'e0213676879061470efe50720368bce9b99aaa12' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', }[sys.platform] DIST_ARCH = { '32bit': 'ia32', '64bit': 'x64', }[ARCH] TARGET_PLATFORM = { 'cygwin': 'win32', 'darwin': 'darwin', 'linux2': 'linux', 'win32': 'win32', }[sys.platform] verbose_mode = False def enable_verbose_mode(): print 'Running in verbose mode' global verbose_mode verbose_mode = True def is_verbose_mode(): return verbose_mode
d5a578e6b72fae3c92827895055ed32baf8aa806
coney/response_codes.py
coney/response_codes.py
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
Add additional codes used by server implementation
Add additional codes used by server implementation
Python
mit
cbigler/jackrabbit
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code' Add additional codes used by server implementation
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
<commit_before> class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code' <commit_msg>Add additional codes used by server implementation<commit_after>
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code' Add additional codes used by server implementation class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
<commit_before> class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 1 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 2 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 3 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code' <commit_msg>Add additional codes used by server implementation<commit_after> class ResponseCodes(object): SUCCESS = 0 USER_CODE_START = 1 USER_CODE_END = 0x7fffffff RESERVED_CODE_START = 0x80000000 MALFORMED_RESPONSE = RESERVED_CODE_START MALFORMED_REQUEST = RESERVED_CODE_START + 1 REQUEST_ENCODING_FAILURE = RESERVED_CODE_START + 2 REMOTE_UNHANDLED_EXCEPTION = RESERVED_CODE_START + 3 CALL_REPLY_TIMEOUT = RESERVED_CODE_START + 4 METHOD_NOT_FOUND = RESERVED_CODE_START + 5 VERSION_NOT_FOUND = RESERVED_CODE_START + 6 UNEXPECTED_DISPATCH_EXCEPTION = RESERVED_CODE_START + 7 RESERVED_CODE_END = 0xffffffff _desc = { SUCCESS: 'Success', MALFORMED_RESPONSE: 'Response message was malformed', MALFORMED_REQUEST: 'Request message was malformed', REQUEST_ENCODING_FAILURE: 'The data in the request could not be encoded', REMOTE_UNHANDLED_EXCEPTION: 'An unhandled exception occurred while processing the remote call', CALL_REPLY_TIMEOUT: 'The request did not receive a reply within the call timeout', METHOD_NOT_FOUND: 'The requested method is not supported by the server', VERSION_NOT_FOUND: 'The requested method version is not supported by the server', UNEXPECTED_DISPATCH_EXCEPTION: 'An unexpected exception occurred during message dispatch' } @staticmethod def describe(code): try: return ResponseCodes._desc[code] except KeyError: if ResponseCodes.USER_CODE_START >= code <= ResponseCodes.USER_CODE_END: return 'RPC endpoint specific error response' else: return 'Unknown response code'
adc3fa70c32bce764a6b6a7efd7a39c349d3a685
quick_sort.py
quick_sort.py
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while right >= left and un_list[right] >= pivot: right += 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': pass
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while un_list[right] >= pivot and right >= left: right -= 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': from random import shuffle rands = [2 for num in range(0, 1001)] nums = range(0, 1001) BEST_CASE = shuffle(nums) WORST_CASE = nums from timeit import Timer SETUP = """from __main__ import BEST_CASE, WORST_CASE, quick_srt""" best = Timer('quick_srt({})'.format(BEST_CASE), SETUP).timeit(100) worst = Timer('quick_srt({})'.format(WORST_CASE), SETUP).timeit(100) print(""" Best case represented as a list that is Worst case represented as a list that is """) print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
Update index error in _sort method
Update index error in _sort method
Python
mit
jonathanstallings/data-structures
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while right >= left and un_list[right] >= pivot: right += 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': pass Update index error in _sort method
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while un_list[right] >= pivot and right >= left: right -= 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': from random import shuffle rands = [2 for num in range(0, 1001)] nums = range(0, 1001) BEST_CASE = shuffle(nums) WORST_CASE = nums from timeit import Timer SETUP = """from __main__ import BEST_CASE, WORST_CASE, quick_srt""" best = Timer('quick_srt({})'.format(BEST_CASE), SETUP).timeit(100) worst = Timer('quick_srt({})'.format(WORST_CASE), SETUP).timeit(100) print(""" Best case represented as a list that is Worst case represented as a list that is """) print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
<commit_before>"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while right >= left and un_list[right] >= pivot: right += 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': pass <commit_msg>Update index error in _sort method<commit_after>
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while un_list[right] >= pivot and right >= left: right -= 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': from random import shuffle rands = [2 for num in range(0, 1001)] nums = range(0, 1001) BEST_CASE = shuffle(nums) WORST_CASE = nums from timeit import Timer SETUP = """from __main__ import BEST_CASE, WORST_CASE, quick_srt""" best = Timer('quick_srt({})'.format(BEST_CASE), SETUP).timeit(100) worst = Timer('quick_srt({})'.format(WORST_CASE), SETUP).timeit(100) print(""" Best case represented as a list that is Worst case represented as a list that is """) print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while right >= left and un_list[right] >= pivot: right += 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': pass Update index error in _sort method"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while un_list[right] >= pivot and right >= left: right -= 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': from random import shuffle rands = [2 for num in range(0, 1001)] nums = range(0, 1001) BEST_CASE = shuffle(nums) WORST_CASE = nums from timeit import Timer SETUP = """from __main__ import BEST_CASE, WORST_CASE, quick_srt""" best = Timer('quick_srt({})'.format(BEST_CASE), SETUP).timeit(100) worst = Timer('quick_srt({})'.format(WORST_CASE), SETUP).timeit(100) print(""" Best case represented as a list that is Worst case represented as a list that is """) print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
<commit_before>"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while right >= left and un_list[right] >= pivot: right += 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': pass <commit_msg>Update index error in _sort method<commit_after>"""Doc string to end all doc strings""" def quick_srt(un_list): _helper(un_list, 0, len(un_list)-1) def _helper(un_list, first, last): if first < last: split = _split(un_list, first, last) _helper(un_list, first, split-1) _helper(un_list, split+1, last) def _split(un_list, first, last): pivot = un_list[first] left = first + 1 right = last while True: while left <= right and un_list[left] <= pivot: left += 1 while un_list[right] >= pivot and right >= left: right -= 1 if right < left: break else: temp = un_list[left] un_list[left] = un_list[right] un_list[right] = temp temp = un_list[first] un_list[first] = un_list[right] un_list[right] = temp return right if __name__ == '__main__': from random import shuffle rands = [2 for num in range(0, 1001)] nums = range(0, 1001) BEST_CASE = shuffle(nums) WORST_CASE = nums from timeit import Timer SETUP = """from __main__ import BEST_CASE, WORST_CASE, quick_srt""" best = Timer('quick_srt({})'.format(BEST_CASE), SETUP).timeit(100) worst = Timer('quick_srt({})'.format(WORST_CASE), SETUP).timeit(100) print(""" Best case represented as a list that is Worst case represented as a list that is """) print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
fc7aac4f68c4b694162ed146b8b5ab2b4401895c
test/features/test_create_pages.py
test/features/test_create_pages.py
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/aboutData") assert_that(browser.is_text_present('About the transactions data'), is_(True))
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html") assert_that(browser.is_text_present('High-volume services'), is_(True))
Test for page existing on master branch
Test for page existing on master branch
Python
mit
alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/aboutData") assert_that(browser.is_text_present('About the transactions data'), is_(True)) Test for page existing on master branch
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html") assert_that(browser.is_text_present('High-volume services'), is_(True))
<commit_before>import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/aboutData") assert_that(browser.is_text_present('About the transactions data'), is_(True)) <commit_msg>Test for page existing on master branch<commit_after>
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html") assert_that(browser.is_text_present('High-volume services'), is_(True))
import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/aboutData") assert_that(browser.is_text_present('About the transactions data'), is_(True)) Test for page existing on master branchimport time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html") assert_that(browser.is_text_present('High-volume services'), is_(True))
<commit_before>import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/aboutData") assert_that(browser.is_text_present('About the transactions data'), is_(True)) <commit_msg>Test for page existing on master branch<commit_after>import time import unittest from hamcrest import * from splinter import Browser from support.stub_server import HttpStub class test_create_pages(unittest.TestCase): def setUp(self): HttpStub.start() time.sleep(2) def tearDown(self): HttpStub.stop() def test_about_page(self): with Browser() as browser: browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html") assert_that(browser.is_text_present('High-volume services'), is_(True))
209fef39f72a625e154f4455eaa6754d6a85e98b
zeus/utils/revisions.py
zeus/utils/revisions.py
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision result = next(vcs_client.log(repository.id, parent=ref, limit=1)) revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision try: result = vcs_client.log(repository.id, parent=ref, limit=1)[0] except IndexError: raise UnknownRevision revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision
Fix invalid next() call on api result
Fix invalid next() call on api result
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision result = next(vcs_client.log(repository.id, parent=ref, limit=1)) revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision Fix invalid next() call on api result
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision try: result = vcs_client.log(repository.id, parent=ref, limit=1)[0] except IndexError: raise UnknownRevision revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision
<commit_before>from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision result = next(vcs_client.log(repository.id, parent=ref, limit=1)) revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision <commit_msg>Fix invalid next() call on api result<commit_after>
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision try: result = vcs_client.log(repository.id, parent=ref, limit=1)[0] except IndexError: raise UnknownRevision revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision
from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision result = next(vcs_client.log(repository.id, parent=ref, limit=1)) revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision Fix invalid next() call on api resultfrom dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision try: result = vcs_client.log(repository.id, parent=ref, limit=1)[0] except IndexError: raise UnknownRevision revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision
<commit_before>from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision result = next(vcs_client.log(repository.id, parent=ref, limit=1)) revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision <commit_msg>Fix invalid next() call on api result<commit_after>from dataclasses import dataclass from typing import List, Tuple from zeus.exceptions import UnknownRevision from zeus.models import Repository, Revision from zeus.vcs import vcs_client @dataclass class RevisionResult: sha: str message: str author: str author_date: str committer: str committer_date: str parents: List[str] authors: List[Tuple[str, str]] def identify_revision( repository: Repository, ref: str, with_vcs: bool = True ) -> Revision: """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from the database first if len(ref) == 40: revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == ref ).first() if revision: return revision if not with_vcs: raise UnknownRevision try: result = vcs_client.log(repository.id, parent=ref, limit=1)[0] except IndexError: raise UnknownRevision revision = Revision.query.filter( Revision.repository_id == repository.id, Revision.sha == result["sha"] ).first() if not revision: raise UnknownRevision
4ab14b3de299b58aee94511910d199cd1d1737a5
zou/app/utils/emails.py
zou/app/utils/emails.py
from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
Fix email sending in production environment
Fix email sending in production environment
Python
agpl-3.0
cgwire/zou
from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message) Fix email sending in production environment
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
<commit_before>from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message) <commit_msg>Fix email sending in production environment<commit_after>
from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message) Fix email sending in production environmentfrom flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
<commit_before>from flask_mail import Message from zou.app import mail def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message) <commit_msg>Fix email sending in production environment<commit_after>from flask_mail import Message from zou.app import mail, app def send_email(subject, body, recipient_email, html=None): """ Send an email with given subject and body to given recipient. """ if html is None: html = body with app.app_context(): message = Message( body=body, html=html, subject=subject, recipients=[recipient_email] ) mail.send(message)
8639f91fba318c4b8c64f7c25885f8fe95e0ebe4
robot/game.py
robot/game.py
import logging import time from enum import Enum from threading import Thread from typing import NewType import _thread from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ end_time = time.time() + timeout_seconds def worker(): while time.time() < end_time: remaining = end_time - time.time() time.sleep(max(remaining, 0.01)) LOGGER.info("Timeout %rs expired: Game over!", timeout_seconds) # Interrupt the main thread to kill the user code _thread.interrupt_main() # type: ignore worker_thread = Thread(target=worker, daemon=True) worker_thread.start() return worker_thread class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value)
import logging import signal from enum import Enum from typing import NewType from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def timeout_handler(signum, stack): """ Handle the `SIGALRM` to kill the current process. """ raise SystemExit("Timeout expired: Game Over!") def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(timeout_seconds) class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value)
Replace thread killing with SIGALRM
Replace thread killing with SIGALRM
Python
mit
sourcebots/robot-api,sourcebots/robot-api
import logging import time from enum import Enum from threading import Thread from typing import NewType import _thread from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ end_time = time.time() + timeout_seconds def worker(): while time.time() < end_time: remaining = end_time - time.time() time.sleep(max(remaining, 0.01)) LOGGER.info("Timeout %rs expired: Game over!", timeout_seconds) # Interrupt the main thread to kill the user code _thread.interrupt_main() # type: ignore worker_thread = Thread(target=worker, daemon=True) worker_thread.start() return worker_thread class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value) Replace thread killing with SIGALRM
import logging import signal from enum import Enum from typing import NewType from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def timeout_handler(signum, stack): """ Handle the `SIGALRM` to kill the current process. """ raise SystemExit("Timeout expired: Game Over!") def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(timeout_seconds) class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value)
<commit_before>import logging import time from enum import Enum from threading import Thread from typing import NewType import _thread from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ end_time = time.time() + timeout_seconds def worker(): while time.time() < end_time: remaining = end_time - time.time() time.sleep(max(remaining, 0.01)) LOGGER.info("Timeout %rs expired: Game over!", timeout_seconds) # Interrupt the main thread to kill the user code _thread.interrupt_main() # type: ignore worker_thread = Thread(target=worker, daemon=True) worker_thread.start() return worker_thread class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value) <commit_msg>Replace thread killing with SIGALRM<commit_after>
import logging import signal from enum import Enum from typing import NewType from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def timeout_handler(signum, stack): """ Handle the `SIGALRM` to kill the current process. """ raise SystemExit("Timeout expired: Game Over!") def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(timeout_seconds) class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value)
import logging import time from enum import Enum from threading import Thread from typing import NewType import _thread from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ end_time = time.time() + timeout_seconds def worker(): while time.time() < end_time: remaining = end_time - time.time() time.sleep(max(remaining, 0.01)) LOGGER.info("Timeout %rs expired: Game over!", timeout_seconds) # Interrupt the main thread to kill the user code _thread.interrupt_main() # type: ignore worker_thread = Thread(target=worker, daemon=True) worker_thread.start() return worker_thread class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value) Replace thread killing with SIGALRMimport logging import signal from enum import Enum from typing import NewType from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def timeout_handler(signum, stack): """ Handle the `SIGALRM` to kill the current process. """ raise SystemExit("Timeout expired: Game Over!") def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(timeout_seconds) class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value)
<commit_before>import logging import time from enum import Enum from threading import Thread from typing import NewType import _thread from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ end_time = time.time() + timeout_seconds def worker(): while time.time() < end_time: remaining = end_time - time.time() time.sleep(max(remaining, 0.01)) LOGGER.info("Timeout %rs expired: Game over!", timeout_seconds) # Interrupt the main thread to kill the user code _thread.interrupt_main() # type: ignore worker_thread = Thread(target=worker, daemon=True) worker_thread.start() return worker_thread class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value) <commit_msg>Replace thread killing with SIGALRM<commit_after>import logging import signal from enum import Enum from typing import NewType from robot.board import Board Zone = NewType('Zone', int) LOGGER = logging.getLogger(__name__) def timeout_handler(signum, stack): """ Handle the `SIGALRM` to kill the current process. """ raise SystemExit("Timeout expired: Game Over!") def kill_after_delay(timeout_seconds): """ Interrupts main process after the given delay. """ signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(timeout_seconds) class GameMode(Enum): """Possible modes the robot can be in.""" COMPETITION = 'competition' DEVELOPMENT = 'development' class GameState(Board): """A description of the initial game state the robot is operating under.""" @property def zone(self) -> Zone: """ The zone in which the robot starts the match. This is configured by inserting a competition zone USB stick into the robot. :return: zone ID the robot started in (0-3) """ return self._send_and_receive({})['zone'] @property def mode(self) -> GameMode: """ :return: The ``GameMode`` that the robot is currently in. """ value = self._send_and_receive({})['mode'] return GameMode(value)
5c88f210644cbe59cf3b3a71345a3fc64dfc542a
spiff/api/plugins.py
spiff/api/plugins.py
from django.conf import settings import importlib import inspect def find_api_classes(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield cls
from django.conf import settings import importlib import inspect def find_api_classes(*args, **kwargs): for app, cls in find_api_implementations(*args, **kwargs): yield cls def find_api_implementations(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield (app, cls)
Add a method to also easily find what app an api object was found in
Add a method to also easily find what app an api object was found in
Python
agpl-3.0
SYNHAK/spiff,SYNHAK/spiff,SYNHAK/spiff
from django.conf import settings import importlib import inspect def find_api_classes(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield cls Add a method to also easily find what app an api object was found in
from django.conf import settings import importlib import inspect def find_api_classes(*args, **kwargs): for app, cls in find_api_implementations(*args, **kwargs): yield cls def find_api_implementations(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield (app, cls)
<commit_before>from django.conf import settings import importlib import inspect def find_api_classes(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield cls <commit_msg>Add a method to also easily find what app an api object was found in<commit_after>
from django.conf import settings import importlib import inspect def find_api_classes(*args, **kwargs): for app, cls in find_api_implementations(*args, **kwargs): yield cls def find_api_implementations(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield (app, cls)
from django.conf import settings import importlib import inspect def find_api_classes(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield cls Add a method to also easily find what app an api object was found infrom django.conf import settings import importlib import inspect def find_api_classes(*args, **kwargs): for app, cls in find_api_implementations(*args, **kwargs): yield cls def find_api_implementations(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield (app, cls)
<commit_before>from django.conf import settings import importlib import inspect def find_api_classes(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield cls <commit_msg>Add a method to also easily find what app an api object was found in<commit_after>from django.conf import settings import importlib import inspect def find_api_classes(*args, **kwargs): for app, cls in find_api_implementations(*args, **kwargs): yield cls def find_api_implementations(module, superclass, test=lambda x: True): for app in map(lambda x:'%s.%s'%(x, module), settings.INSTALLED_APPS): try: appAPI = importlib.import_module(app) except ImportError, e: continue for name, cls in inspect.getmembers(appAPI): if inspect.isclass(cls) and issubclass(cls, superclass) and not cls is superclass and test(cls): yield (app, cls)
d36ac9a113608aadbda79c724f6aa6f6da5ec0bd
cellcounter/mixins.py
cellcounter/mixins.py
import simplejson as json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4)
import json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4)
Use json rather than simplejson
Use json rather than simplejson
Python
mit
haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,haematologic/cellcounter
import simplejson as json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4) Use json rather than simplejson
import json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4)
<commit_before>import simplejson as json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4) <commit_msg>Use json rather than simplejson<commit_after>
import json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4)
import simplejson as json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4) Use json rather than simplejsonimport json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4)
<commit_before>import simplejson as json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4) <commit_msg>Use json rather than simplejson<commit_after>import json from django.http import HttpResponse class JSONResponseMixin(object): """ A Mixin that renders context as a JSON response """ def render_to_response(self, context): """ Returns a JSON response containing 'context' as payload """ return self.get_json_response(self.convert_context_to_json(context)) def get_json_response(self, content, **httpresponse_kwargs): """ Construct an `HttpResponse` object. """ response = HttpResponse(content, content_type='application/json', **httpresponse_kwargs) return response def convert_context_to_json(self, context): """ Convert the context dictionary into a JSON object """ return json.dumps(context, indent=4)
85e10e4c4eaf46ed89bc4b148b9c483df79cf410
test/test_fields.py
test/test_fields.py
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 def test_field_component_boundary_1(): fc = fds.FieldComponent(100) fc.values = np.random.rand(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = 23 fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [23, 23, 23]) def test_field_component_boundary_2(): fc = fds.FieldComponent(100) fc.values = np.ones(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = [23, 42, 23] fc.boundaries[0].additive = True fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [24, 43, 24]) def test_field_component_output(): fc = fds.FieldComponent(100) fc.outputs = [fds.Output(fds.LineRegion([0, 1, 2], [0, 0.2], 'test output'))] fc.write_outputs() fc.write_outputs() assert np.allclose(fc.outputs[0].signals, [[0, 0], [0, 0], [0, 0]])
Add test cases for FieldComponent class.
Add test cases for FieldComponent class.
Python
bsd-3-clause
emtpb/pyfds
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 Add test cases for FieldComponent class.
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 def test_field_component_boundary_1(): fc = fds.FieldComponent(100) fc.values = np.random.rand(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = 23 fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [23, 23, 23]) def test_field_component_boundary_2(): fc = fds.FieldComponent(100) fc.values = np.ones(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = [23, 42, 23] fc.boundaries[0].additive = True fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [24, 43, 24]) def test_field_component_output(): fc = fds.FieldComponent(100) fc.outputs = [fds.Output(fds.LineRegion([0, 1, 2], [0, 0.2], 'test output'))] fc.write_outputs() fc.write_outputs() assert np.allclose(fc.outputs[0].signals, [[0, 0], [0, 0], [0, 0]])
<commit_before>import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 <commit_msg>Add test cases for FieldComponent class.<commit_after>
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 def test_field_component_boundary_1(): fc = fds.FieldComponent(100) fc.values = np.random.rand(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = 23 fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [23, 23, 23]) def test_field_component_boundary_2(): fc = fds.FieldComponent(100) fc.values = np.ones(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = [23, 42, 23] fc.boundaries[0].additive = True fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [24, 43, 24]) def test_field_component_output(): fc = fds.FieldComponent(100) fc.outputs = [fds.Output(fds.LineRegion([0, 1, 2], [0, 0.2], 'test output'))] fc.write_outputs() fc.write_outputs() assert np.allclose(fc.outputs[0].signals, [[0, 0], [0, 0], [0, 0]])
import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 Add test cases for FieldComponent class.import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 def test_field_component_boundary_1(): fc = fds.FieldComponent(100) fc.values = np.random.rand(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = 23 fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [23, 23, 23]) def test_field_component_boundary_2(): fc = fds.FieldComponent(100) fc.values = np.ones(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = [23, 42, 23] fc.boundaries[0].additive = True fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [24, 43, 24]) def test_field_component_output(): fc = fds.FieldComponent(100) fc.outputs = [fds.Output(fds.LineRegion([0, 1, 2], [0, 0.2], 'test output'))] fc.write_outputs() fc.write_outputs() assert np.allclose(fc.outputs[0].signals, [[0, 0], [0, 0], [0, 0]])
<commit_before>import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 <commit_msg>Add test cases for FieldComponent class.<commit_after>import numpy as np import pyfds as fds def test_dimension(): dim = fds.Dimension(3, 0.1) assert np.allclose(dim.vector, np.asarray([0, 0.1, 0.2])) assert dim.get_index(0.1) == 1 def test_field_component_boundary_1(): fc = fds.FieldComponent(100) fc.values = np.random.rand(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = 23 fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [23, 23, 23]) def test_field_component_boundary_2(): fc = fds.FieldComponent(100) fc.values = np.ones(100) fc.boundaries = [fds.Boundary(fds.LineRegion([5, 6, 7], [0, 0.2], 'test boundary'))] fc.boundaries[0].value = [23, 42, 23] fc.boundaries[0].additive = True fc.apply_bounds() assert np.allclose(fc.values[[5, 6, 7]], [24, 43, 24]) def test_field_component_output(): fc = fds.FieldComponent(100) fc.outputs = [fds.Output(fds.LineRegion([0, 1, 2], [0, 0.2], 'test output'))] fc.write_outputs() fc.write_outputs() assert np.allclose(fc.outputs[0].signals, [[0, 0], [0, 0], [0, 0]])
32d23eb7764178cedcf6b648f959fbf49d7ff657
app/models.py
app/models.py
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return '<Essay {0}>: {1}. Created at:{2}'.format(self.text, self.score, self.time)
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return u'<Essay {0}>: {1}. Created at:{2}'.format(self.id, self.score, self.time)
Modify repr of model Essay
Modify repr of model Essay
Python
apache-2.0
kigawas/essai,kigawas/essai
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return '<Essay {0}>: {1}. Created at:{2}'.format(self.text, self.score, self.time) Modify repr of model Essay
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return u'<Essay {0}>: {1}. Created at:{2}'.format(self.id, self.score, self.time)
<commit_before>from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return '<Essay {0}>: {1}. Created at:{2}'.format(self.text, self.score, self.time) <commit_msg>Modify repr of model Essay<commit_after>
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return u'<Essay {0}>: {1}. Created at:{2}'.format(self.id, self.score, self.time)
from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return '<Essay {0}>: {1}. Created at:{2}'.format(self.text, self.score, self.time) Modify repr of model Essayfrom . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return u'<Essay {0}>: {1}. Created at:{2}'.format(self.id, self.score, self.time)
<commit_before>from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return '<Essay {0}>: {1}. Created at:{2}'.format(self.text, self.score, self.time) <commit_msg>Modify repr of model Essay<commit_after>from . import db class Essay(db.Model): __tablename__ = 'essays' id = db.Column(db.Integer, primary_key=True) text = db.Column(db.Text) time = db.Column(db.DateTime(True)) score = db.Column(db.Float) spell_errors = db.Column(db.Text) grammar_errors = db.Column(db.Text) coherence = db.Column(db.Text) def __repr__(self): return u'<Essay {0}>: {1}. Created at:{2}'.format(self.id, self.score, self.time)
845192bb91a2421c54a9bbb924e1e09e700aee66
Lib/dialogKit/__init__.py
Lib/dialogKit/__init__.py
""" dialogKit: easy bake dialogs """ # determine the environment try: import FL haveFL = True except ImportError: haveFL = False try: import vanilla haveVanilla = True except ImportError: haveVanilla = False # perform the environment specific import if haveFL: from _dkFL import * if haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b"
""" dialogKit: easy bake dialogs """ # determine the environment haveFL = False haveVanilla = False try: import FL haveFL = True except ImportError: pass if not haveFL: try: import vanilla haveVanilla = True except ImportError: pass # perform the environment specific import if haveFL: from _dkFL import * elif haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b"
Stop trying imports after something has been successfully loaded.
Stop trying imports after something has been successfully loaded.
Python
mit
anthrotype/dialogKit,daltonmaag/dialogKit,typesupply/dialogKit
""" dialogKit: easy bake dialogs """ # determine the environment try: import FL haveFL = True except ImportError: haveFL = False try: import vanilla haveVanilla = True except ImportError: haveVanilla = False # perform the environment specific import if haveFL: from _dkFL import * if haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b" Stop trying imports after something has been successfully loaded.
""" dialogKit: easy bake dialogs """ # determine the environment haveFL = False haveVanilla = False try: import FL haveFL = True except ImportError: pass if not haveFL: try: import vanilla haveVanilla = True except ImportError: pass # perform the environment specific import if haveFL: from _dkFL import * elif haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b"
<commit_before>""" dialogKit: easy bake dialogs """ # determine the environment try: import FL haveFL = True except ImportError: haveFL = False try: import vanilla haveVanilla = True except ImportError: haveVanilla = False # perform the environment specific import if haveFL: from _dkFL import * if haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b" <commit_msg>Stop trying imports after something has been successfully loaded.<commit_after>
""" dialogKit: easy bake dialogs """ # determine the environment haveFL = False haveVanilla = False try: import FL haveFL = True except ImportError: pass if not haveFL: try: import vanilla haveVanilla = True except ImportError: pass # perform the environment specific import if haveFL: from _dkFL import * elif haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b"
""" dialogKit: easy bake dialogs """ # determine the environment try: import FL haveFL = True except ImportError: haveFL = False try: import vanilla haveVanilla = True except ImportError: haveVanilla = False # perform the environment specific import if haveFL: from _dkFL import * if haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b" Stop trying imports after something has been successfully loaded.""" dialogKit: easy bake dialogs """ # determine the environment haveFL = False haveVanilla = False try: import FL haveFL = True except ImportError: pass if not haveFL: try: import vanilla haveVanilla = True except ImportError: pass # perform the environment specific import if haveFL: from _dkFL import * elif haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b"
<commit_before>""" dialogKit: easy bake dialogs """ # determine the environment try: import FL haveFL = True except ImportError: haveFL = False try: import vanilla haveVanilla = True except ImportError: haveVanilla = False # perform the environment specific import if haveFL: from _dkFL import * if haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b" <commit_msg>Stop trying imports after something has been successfully loaded.<commit_after>""" dialogKit: easy bake dialogs """ # determine the environment haveFL = False haveVanilla = False try: import FL haveFL = True except ImportError: pass if not haveFL: try: import vanilla haveVanilla = True except ImportError: pass # perform the environment specific import if haveFL: from _dkFL import * elif haveVanilla: from _dkVanilla import * else: raise ImportError, 'dialogKit is not available in this environment' numberVersion = (0, 0, "beta", 1) version = "0.0.1b"
992e0e2f50418bd87052741f7f1937f8efd052c0
tests/mpath_test.py
tests/mpath_test.py
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0")) def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file)
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0"))
Make the tearDown method of the mpath test case better visible
Make the tearDown method of the mpath test case better visible By moving it to the beginning of the file.
Python
lgpl-2.1
vpodzime/libblockdev,atodorov/libblockdev,vpodzime/libblockdev,vpodzime/libblockdev,snbueno/libblockdev,dashea/libblockdev,atodorov/libblockdev,snbueno/libblockdev,rhinstaller/libblockdev,atodorov/libblockdev,rhinstaller/libblockdev,dashea/libblockdev,rhinstaller/libblockdev
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0")) def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) Make the tearDown method of the mpath test case better visible By moving it to the beginning of the file.
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0"))
<commit_before>import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0")) def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) <commit_msg>Make the tearDown method of the mpath test case better visible By moving it to the beginning of the file.<commit_after>
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0"))
import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0")) def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) Make the tearDown method of the mpath test case better visible By moving it to the beginning of the file.import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0"))
<commit_before>import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0")) def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) <commit_msg>Make the tearDown method of the mpath test case better visible By moving it to the beginning of the file.<commit_after>import unittest import os from utils import create_sparse_tempfile from gi.repository import BlockDev if not BlockDev.is_initialized(): BlockDev.init(None, None) class MpathTestCase(unittest.TestCase): def setUp(self): self.dev_file = create_sparse_tempfile("mpath_test", 1024**3) succ, loop = BlockDev.loop_setup(self.dev_file) if not succ: raise RuntimeError("Failed to setup loop device for testing") self.loop_dev = "/dev/%s" % loop def tearDown(self): succ = BlockDev.loop_teardown(self.loop_dev) if not succ: os.unlink(self.dev_file) raise RuntimeError("Failed to tear down loop device used for testing") os.unlink(self.dev_file) def test_is_mpath_member(self): """Verify that is_mpath_member works as expected""" # just test that some non-mpath is not reported as a multipath member # device and no error is reported self.assertFalse(BlockDev.mpath_is_mpath_member("/dev/loop0"))
437c8b59148ccb31ac7480ab6c9e9784e2dd6295
js2xml/__init__.py
js2xml/__init__.py
import lxml.etree from slimit.parser import Parser from js2xml.xmlvisitor import XmlVisitor _parser = Parser() _visitor = XmlVisitor() def parse(text, debug=False): tree = _parser.parse(text, debug=debug) xml = _visitor.visit(tree) return xml
Add js2xml.parse() method that wraps the slimit visitor/xml-builder
Add js2xml.parse() method that wraps the slimit visitor/xml-builder
Python
mit
redapple/js2xml,redapple/js2xml,redapple/js2xml,redapple/js2xml
Add js2xml.parse() method that wraps the slimit visitor/xml-builder
import lxml.etree from slimit.parser import Parser from js2xml.xmlvisitor import XmlVisitor _parser = Parser() _visitor = XmlVisitor() def parse(text, debug=False): tree = _parser.parse(text, debug=debug) xml = _visitor.visit(tree) return xml
<commit_before> <commit_msg>Add js2xml.parse() method that wraps the slimit visitor/xml-builder<commit_after>
import lxml.etree from slimit.parser import Parser from js2xml.xmlvisitor import XmlVisitor _parser = Parser() _visitor = XmlVisitor() def parse(text, debug=False): tree = _parser.parse(text, debug=debug) xml = _visitor.visit(tree) return xml
Add js2xml.parse() method that wraps the slimit visitor/xml-builderimport lxml.etree from slimit.parser import Parser from js2xml.xmlvisitor import XmlVisitor _parser = Parser() _visitor = XmlVisitor() def parse(text, debug=False): tree = _parser.parse(text, debug=debug) xml = _visitor.visit(tree) return xml
<commit_before> <commit_msg>Add js2xml.parse() method that wraps the slimit visitor/xml-builder<commit_after>import lxml.etree from slimit.parser import Parser from js2xml.xmlvisitor import XmlVisitor _parser = Parser() _visitor = XmlVisitor() def parse(text, debug=False): tree = _parser.parse(text, debug=debug) xml = _visitor.visit(tree) return xml
290f0beb0103ee8f8d3d59bf2fabc227ed743d30
lib/smisk/mvc/model.py
lib/smisk/mvc/model.py
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False # Control wheretere to include module name or not in table names. # If True, project.fruits.Apple -> table apples. # If False, project.fruits.Apple -> table project_fruits_apples. options_defaults['shortnames'] = True
Set sqlalchemy option shortnames to True by default.
Set sqlalchemy option shortnames to True by default.
Python
mit
rsms/smisk,rsms/smisk,rsms/smisk
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False Set sqlalchemy option shortnames to True by default.
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False # Control wheretere to include module name or not in table names. # If True, project.fruits.Apple -> table apples. # If False, project.fruits.Apple -> table project_fruits_apples. options_defaults['shortnames'] = True
<commit_before># encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False <commit_msg>Set sqlalchemy option shortnames to True by default.<commit_after>
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False # Control wheretere to include module name or not in table names. # If True, project.fruits.Apple -> table apples. # If False, project.fruits.Apple -> table project_fruits_apples. options_defaults['shortnames'] = True
# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False Set sqlalchemy option shortnames to True by default.# encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False # Control wheretere to include module name or not in table names. # If True, project.fruits.Apple -> table apples. # If False, project.fruits.Apple -> table project_fruits_apples. options_defaults['shortnames'] = True
<commit_before># encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False <commit_msg>Set sqlalchemy option shortnames to True by default.<commit_after># encoding: utf-8 '''Model in MVC :requires: `elixir <http://elixir.ematia.de/>`__ ''' # Ignore the SA string type depr warning from sqlalchemy.exceptions import SADeprecationWarning from warnings import filterwarnings filterwarnings('ignore', 'Using String type with no length for CREATE TABLE', SADeprecationWarning) # Import Elixir & SQLAlchemy from elixir import * from sqlalchemy import func # Disable autosetup by recommendation from Jason R. Coombs: # http://groups.google.com/group/sqlelixir/msg/ed698d986bfeefdb options_defaults['autosetup'] = False # Control wheretere to include module name or not in table names. # If True, project.fruits.Apple -> table apples. # If False, project.fruits.Apple -> table project_fruits_apples. options_defaults['shortnames'] = True
80b8ef8b227baa1f4af842716ebfb83dcabf9703
tests/scoring_engine/web/views/test_auth.py
tests/scoring_engine/web/views/test_auth.py
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services')
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') def test_wrong_password_login(self): user = self.create_default_user() user.username = 'RandomName' self.session.add(user) self.session.commit() self.auth_and_get_path('/') assert user.authenticated is False
Add test for incorrect password auth view
Add test for incorrect password auth view
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') Add test for incorrect password auth view
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') def test_wrong_password_login(self): user = self.create_default_user() user.username = 'RandomName' self.session.add(user) self.session.commit() self.auth_and_get_path('/') assert user.authenticated is False
<commit_before>from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') <commit_msg>Add test for incorrect password auth view<commit_after>
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') def test_wrong_password_login(self): user = self.create_default_user() user.username = 'RandomName' self.session.add(user) self.session.commit() self.auth_and_get_path('/') assert user.authenticated is False
from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') Add test for incorrect password auth viewfrom tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') def test_wrong_password_login(self): user = self.create_default_user() user.username = 'RandomName' self.session.add(user) self.session.commit() self.auth_and_get_path('/') assert user.authenticated is False
<commit_before>from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') <commit_msg>Add test for incorrect password auth view<commit_after>from tests.scoring_engine.web.web_test import WebTest class TestAuth(WebTest): def test_login_page_auth_required(self): resp = self.client.get('/login') assert resp.status_code == 200 def test_unauthorized(self): resp = self.client.get('/unauthorized') assert resp.status_code == 200 def test_auth_required_logout(self): self.verify_auth_required('/logout') def test_login_logout(self): user = self.create_default_user() assert user.authenticated is False self.auth_and_get_path('/') assert user.authenticated is True logout_resp = self.client.get('/logout') assert user.authenticated is False assert logout_resp.status_code == 302 self.verify_auth_required('/services') def test_wrong_password_login(self): user = self.create_default_user() user.username = 'RandomName' self.session.add(user) self.session.commit() self.auth_and_get_path('/') assert user.authenticated is False
a23774fe4646db1bf4b25cf67d855dcc4cc4c8f7
celery/loaders/default.py
celery/loaders/default.py
from celery.loaders.base import BaseLoader DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconf.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], [''])
import os from celery.loaders.base import BaseLoader DEFAULT_CONFIG_MODULE = "celeryconfig" DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconfig.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) configname = os.environ.get("CELERY_CONFIG_MODULE", DEFAULT_CONFIG_MODULE) celeryconfig = __import__(configname, {}, {}, ['']) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], [''])
Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS
Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS
Python
bsd-3-clause
ask/celery,frac/celery,mitsuhiko/celery,ask/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,WoLpH/celery,WoLpH/celery,cbrepo/celery
from celery.loaders.base import BaseLoader DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconf.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], ['']) Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS
import os from celery.loaders.base import BaseLoader DEFAULT_CONFIG_MODULE = "celeryconfig" DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconfig.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) configname = os.environ.get("CELERY_CONFIG_MODULE", DEFAULT_CONFIG_MODULE) celeryconfig = __import__(configname, {}, {}, ['']) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], [''])
<commit_before>from celery.loaders.base import BaseLoader DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconf.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], ['']) <commit_msg>Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS<commit_after>
import os from celery.loaders.base import BaseLoader DEFAULT_CONFIG_MODULE = "celeryconfig" DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconfig.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) configname = os.environ.get("CELERY_CONFIG_MODULE", DEFAULT_CONFIG_MODULE) celeryconfig = __import__(configname, {}, {}, ['']) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], [''])
from celery.loaders.base import BaseLoader DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconf.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], ['']) Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPSimport os from celery.loaders.base import BaseLoader DEFAULT_CONFIG_MODULE = "celeryconfig" DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconfig.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) configname = os.environ.get("CELERY_CONFIG_MODULE", DEFAULT_CONFIG_MODULE) celeryconfig = __import__(configname, {}, {}, ['']) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], [''])
<commit_before>from celery.loaders.base import BaseLoader DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconf.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], ['']) <commit_msg>Add possibility to set celeryconfig module with ENV["CELERY_CONFIG_MODULE"] + always add celery to INSTALLED_APPS<commit_after>import os from celery.loaders.base import BaseLoader DEFAULT_CONFIG_MODULE = "celeryconfig" DEFAULT_SETTINGS = { "DEBUG": False, "DATABASE_ENGINE": "sqlite3", "DATABASE_NAME": "celery.sqlite", "INSTALLED_APPS": ("celery", ), } def wanted_module_item(item): is_private = item.startswith("_") return not is_private class Loader(BaseLoader): """The default loader. See the FAQ for example usage. """ def read_configuration(self): """Read configuration from ``celeryconfig.py`` and configure celery and Django so it can be used by regular Python.""" config = dict(DEFAULT_SETTINGS) configname = os.environ.get("CELERY_CONFIG_MODULE", DEFAULT_CONFIG_MODULE) celeryconfig = __import__(configname, {}, {}, ['']) import celeryconfig usercfg = dict((key, getattr(celeryconfig, key)) for key in dir(celeryconfig) if wanted_module_item(key)) config.update(usercfg) from django.conf import settings if not settings.configured: settings.configure() for config_key, config_value in usercfg.items(): setattr(settings, config_key, config_value) return settings def on_worker_init(self): """Imports modules at worker init so tasks can be registered and used by the worked. The list of modules to import is taken from the ``CELERY_IMPORTS`` setting in ``celeryconf.py``. """ imports = getattr(self.conf, "CELERY_IMPORTS", []) for module in imports: __import__(module, [], [], [''])
349bb1ce2c15239ae3f9c066ed774b20369b9c0d
src/ggrc/settings/app_engine.py
src/ggrc/settings/app_engine.py
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True CALENDAR_MECHANISM = True
Enable Calendar integration on App Engine deployments
Enable Calendar integration on App Engine deployments
Python
apache-2.0
NejcZupec/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,hyperNURb/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,vladan-m/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,vladan-m/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,plamut/ggrc-core,andrei-karalionak/ggrc-core,selahssea/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,uskudnik/ggrc-core,VinnieJohns/ggrc-core,hyperNURb/ggrc-core,josthkko/ggrc-core,josthkko/ggrc-core,hasanalom/ggrc-core,kr41/ggrc-core,jmakov/ggrc-core,uskudnik/ggrc-core,josthkko/ggrc-core,prasannav7/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,hasanalom/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,hasanalom/ggrc-core,uskudnik/ggrc-core,edofic/ggrc-core,uskudnik/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,hasanalom/ggrc-core,jmakov/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,VinnieJohns/ggrc-core,hyperNURb/ggrc-core,vladan-m/ggrc-core,vladan-m/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True Enable Calendar integration on App Engine deployments
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True CALENDAR_MECHANISM = True
<commit_before># Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True <commit_msg>Enable Calendar integration on App Engine deployments<commit_after>
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True CALENDAR_MECHANISM = True
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True Enable Calendar integration on App Engine deployments# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True CALENDAR_MECHANISM = True
<commit_before># Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True <commit_msg>Enable Calendar integration on App Engine deployments<commit_after># Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: dan@reciprocitylabs.com # Maintained By: dan@reciprocitylabs.com APP_ENGINE = True ENABLE_JASMINE = False LOGIN_MANAGER = 'ggrc.login.appengine' FULLTEXT_INDEXER = 'ggrc.fulltext.mysql.MysqlIndexer' # Cannot access filesystem on AppEngine or when using SDK AUTOBUILD_ASSETS = False SQLALCHEMY_RECORD_QUERIES = True MEMCACHE_MECHANISM = True CALENDAR_MECHANISM = True
5a84249b7e96d9d2f82ee1b27a33b7978d63b16e
src/urls.py
src/urls.py
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. try: from django.conf.urls import patterns, include, url except ImportError: # pragma: no cover # for Django version less than 1.4 from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error"
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error"
Remove django < 1.4 code
Remove django < 1.4 code
Python
agpl-3.0
rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. try: from django.conf.urls import patterns, include, url except ImportError: # pragma: no cover # for Django version less than 1.4 from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error" Remove django < 1.4 code
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error"
<commit_before># -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. try: from django.conf.urls import patterns, include, url except ImportError: # pragma: no cover # for Django version less than 1.4 from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error" <commit_msg>Remove django < 1.4 code<commit_after>
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error"
# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. try: from django.conf.urls import patterns, include, url except ImportError: # pragma: no cover # for Django version less than 1.4 from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error" Remove django < 1.4 code# -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error"
<commit_before># -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. try: from django.conf.urls import patterns, include, url except ImportError: # pragma: no cover # for Django version less than 1.4 from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error" <commit_msg>Remove django < 1.4 code<commit_after># -*- coding: utf-8 -*- # urls.py used as base for developing wirecloud. from django.conf.urls import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns import wirecloud.platform.urls admin.autodiscover() urlpatterns = patterns('', # Showcase (r'^showcase/', include('wirecloud.platform.widget.showcase_urls')), # Catalogue (r'^catalogue', include('wirecloud.catalogue.urls')), # Proxy (r'^proxy', include('wirecloud.proxy.urls')), # Login/logout url(r'^login/?$', 'django.contrib.auth.views.login', name="login"), url(r'^logout/?$', 'wirecloud.commons.authentication.logout', name="logout"), url(r'^admin/logout/?$', 'wirecloud.commons.authentication.logout'), # Admin interface (r'^admin/', include(admin.site.urls)), ) urlpatterns += wirecloud.platform.urls.urlpatterns urlpatterns += staticfiles_urlpatterns() handler404 = "django.views.defaults.page_not_found" handler500 = "wirecloud.commons.views.server_error"
8ec8929595bd7c4d9b794fe016da64532e517a53
producers/producers.py
producers/producers.py
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` - to run the producer - ``configure(jvm, *options)`` - to configure itself with the given jvm and options (must set configured to True if fully configured) """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` to run the producer, after running `out` attribute has to be set to path to produced output - ``configure(jvm, *options)`` to configure itself with the given jvm and options (must set configured to True if fully configured) - ``is_runable`` to state if producer can be run in current state """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def is_runable(): """ :returns: if producer is runable :rtype: bool """ raise NotImplementedError("runable must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
Add `is_runable` to Producer base class.
Add `is_runable` to Producer base class. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
Python
mit
fhirschmann/penchy,fhirschmann/penchy
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` - to run the producer - ``configure(jvm, *options)`` - to configure itself with the given jvm and options (must set configured to True if fully configured) """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass Add `is_runable` to Producer base class. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` to run the producer, after running `out` attribute has to be set to path to produced output - ``configure(jvm, *options)`` to configure itself with the given jvm and options (must set configured to True if fully configured) - ``is_runable`` to state if producer can be run in current state """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def is_runable(): """ :returns: if producer is runable :rtype: bool """ raise NotImplementedError("runable must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
<commit_before>class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` - to run the producer - ``configure(jvm, *options)`` - to configure itself with the given jvm and options (must set configured to True if fully configured) """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass <commit_msg>Add `is_runable` to Producer base class. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com><commit_after>
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` to run the producer, after running `out` attribute has to be set to path to produced output - ``configure(jvm, *options)`` to configure itself with the given jvm and options (must set configured to True if fully configured) - ``is_runable`` to state if producer can be run in current state """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def is_runable(): """ :returns: if producer is runable :rtype: bool """ raise NotImplementedError("runable must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` - to run the producer - ``configure(jvm, *options)`` - to configure itself with the given jvm and options (must set configured to True if fully configured) """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass Add `is_runable` to Producer base class. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` to run the producer, after running `out` attribute has to be set to path to produced output - ``configure(jvm, *options)`` to configure itself with the given jvm and options (must set configured to True if fully configured) - ``is_runable`` to state if producer can be run in current state """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def is_runable(): """ :returns: if producer is runable :rtype: bool """ raise NotImplementedError("runable must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
<commit_before>class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` - to run the producer - ``configure(jvm, *options)`` - to configure itself with the given jvm and options (must set configured to True if fully configured) """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass <commit_msg>Add `is_runable` to Producer base class. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com><commit_after>class Producer(object): """ Base class for producers. __init__ must be called by inheriting classes. Inheriting classes must implement: - ``_run`` to run the producer, after running `out` attribute has to be set to path to produced output - ``configure(jvm, *options)`` to configure itself with the given jvm and options (must set configured to True if fully configured) - ``is_runable`` to state if producer can be run in current state """ DEPENDENCIES = [] def __init__(self): self._pre_hooks = [] self._post_hooks = [] self.configured = False def add_pre_hooks(self, *hooks): self._pre_hooks.extend(hooks) def add_post_hooks(self, *hooks): self._post_hooks.extend(hooks) def _run(): raise NotImplementedError("_run must be implemented by actual producers") def is_runable(): """ :returns: if producer is runable :rtype: bool """ raise NotImplementedError("runable must be implemented by actual producers") def configure(jvm, **options): """ Configure producer with :param:`jvm` and :param:`options`. :param jvm: Instance of an JVM-Class :param options: keywords that are understood by ``JVM.get_commandline()`` """ raise NotImplementedError("configure must be implemented by actual producers") def run(): """ Run Producer """ for hook in self._pre_hooks: hook() self.run_() for hook in self._post_hooks: hook() class Dacapo(Producer): #TODO pass class Tamiflex(Producer): #TODO pass class HProf(Producer): #TODO pass
b704a92c919d7fa950a65ee0c569864c4549331f
glue/core/tests/util.py
glue/core/tests/util.py
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: os.unlink(fname) @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: try: os.unlink(fname) except WindowsError: # on Windows the unlink can fail pass @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result
Add workaround for failing unlink on Windows
Add workaround for failing unlink on Windows
Python
bsd-3-clause
saimn/glue,stscieisenhamer/glue,JudoWill/glue,saimn/glue,JudoWill/glue,stscieisenhamer/glue
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: os.unlink(fname) @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result Add workaround for failing unlink on Windows
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: try: os.unlink(fname) except WindowsError: # on Windows the unlink can fail pass @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result
<commit_before>from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: os.unlink(fname) @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result <commit_msg>Add workaround for failing unlink on Windows<commit_after>
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: try: os.unlink(fname) except WindowsError: # on Windows the unlink can fail pass @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result
from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: os.unlink(fname) @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result Add workaround for failing unlink on Windowsfrom __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: try: os.unlink(fname) except WindowsError: # on Windows the unlink can fail pass @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result
<commit_before>from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: os.unlink(fname) @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result <commit_msg>Add workaround for failing unlink on Windows<commit_after>from __future__ import absolute_import, division, print_function import tempfile from contextlib import contextmanager import os import zlib from mock import MagicMock from ... import core from ...core.application_base import Application @contextmanager def make_file(contents, suffix, decompress=False): """Context manager to write data to a temporary file, and delete on exit :param contents: Data to write. string :param suffix: File suffix. string """ if decompress: contents = zlib.decompress(contents) try: _, fname = tempfile.mkstemp(suffix=suffix) with open(fname, 'wb') as outfile: outfile.write(contents) yield fname finally: try: os.unlink(fname) except WindowsError: # on Windows the unlink can fail pass @contextmanager def simple_catalog(): """Context manager to create a temporary data file :param suffix: File suffix. string """ with make_file(b'#a, b\n1, 2\n3, 4', '.csv') as result: yield result def simple_session(): collect = core.data_collection.DataCollection() hub = core.hub.Hub() result = core.Session(data_collection=collect, hub=hub, application=MagicMock(Application), command_stack=core.CommandStack()) result.command_stack.session = result return result
17fe6d36a34218e74b53e9617212f0e67b05297d
pysteps/io/__init__.py
pysteps/io/__init__.py
from .interface import get_method from .archive import * from .importers import * from .readers import *
from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
Add missing import of the exporters module
Add missing import of the exporters module
Python
bsd-3-clause
pySTEPS/pysteps
from .interface import get_method from .archive import * from .importers import * from .readers import * Add missing import of the exporters module
from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
<commit_before>from .interface import get_method from .archive import * from .importers import * from .readers import * <commit_msg>Add missing import of the exporters module<commit_after>
from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
from .interface import get_method from .archive import * from .importers import * from .readers import * Add missing import of the exporters modulefrom .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
<commit_before>from .interface import get_method from .archive import * from .importers import * from .readers import * <commit_msg>Add missing import of the exporters module<commit_after>from .interface import get_method from .archive import * from .exporters import * from .importers import * from .readers import *
29b7a69a39ac66ebd8f61c6c9c65e7e60b40b4a0
numpy/_array_api/_types.py
numpy/_array_api/_types.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) Array = ndarray Device = TypeVar('device') Dtype = Literal[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule')
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Any Dtype = Type[Union[[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64]]] SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
Use better type definitions for the array API custom types
Use better type definitions for the array API custom types
Python
bsd-3-clause
anntzer/numpy,simongibbons/numpy,jakirkham/numpy,rgommers/numpy,pdebuyl/numpy,endolith/numpy,simongibbons/numpy,mhvk/numpy,pdebuyl/numpy,charris/numpy,rgommers/numpy,jakirkham/numpy,mattip/numpy,mhvk/numpy,mattip/numpy,rgommers/numpy,charris/numpy,numpy/numpy,simongibbons/numpy,endolith/numpy,anntzer/numpy,anntzer/numpy,pdebuyl/numpy,mhvk/numpy,numpy/numpy,jakirkham/numpy,anntzer/numpy,simongibbons/numpy,seberg/numpy,seberg/numpy,simongibbons/numpy,jakirkham/numpy,seberg/numpy,numpy/numpy,mattip/numpy,pdebuyl/numpy,charris/numpy,mattip/numpy,mhvk/numpy,rgommers/numpy,numpy/numpy,seberg/numpy,charris/numpy,jakirkham/numpy,endolith/numpy,mhvk/numpy,endolith/numpy
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) Array = ndarray Device = TypeVar('device') Dtype = Literal[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule') Use better type definitions for the array API custom types
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Any Dtype = Type[Union[[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64]]] SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
<commit_before>""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) Array = ndarray Device = TypeVar('device') Dtype = Literal[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule') <commit_msg>Use better type definitions for the array API custom types<commit_after>
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Any Dtype = Type[Union[[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64]]] SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) Array = ndarray Device = TypeVar('device') Dtype = Literal[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule') Use better type definitions for the array API custom types""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Any Dtype = Type[Union[[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64]]] SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
<commit_before>""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) Array = ndarray Device = TypeVar('device') Dtype = Literal[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64] SupportsDLPack = TypeVar('SupportsDLPack') SupportsBufferProtocol = TypeVar('SupportsBufferProtocol') PyCapsule = TypeVar('PyCapsule') <commit_msg>Use better type definitions for the array API custom types<commit_after>""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ __all__ = ['Array', 'Device', 'Dtype', 'SupportsDLPack', 'SupportsBufferProtocol', 'PyCapsule'] from typing import Any, Sequence, Type, Union from . import (Array, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64) # This should really be recursive, but that isn't supported yet. See the # similar comment in numpy/typing/_array_like.py NestedSequence = Sequence[Sequence[Any]] Device = Any Dtype = Type[Union[[int8, int16, int32, int64, uint8, uint16, uint32, uint64, float32, float64]]] SupportsDLPack = Any SupportsBufferProtocol = Any PyCapsule = Any
5277d6d5caf075ce6fbb8d46c558bdc29eb62e19
docs/conf.py
docs/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/jaraco/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/pytest-dev/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), }
Update org URL for issue linkage
Update org URL for issue linkage
Python
mit
pytest-dev/pytest-runner
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/jaraco/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), } Update org URL for issue linkage
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/pytest-dev/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), }
<commit_before>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/jaraco/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), } <commit_msg>Update org URL for issue linkage<commit_after>
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/pytest-dev/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/jaraco/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), } Update org URL for issue linkage#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/pytest-dev/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), }
<commit_before>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/jaraco/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), } <commit_msg>Update org URL for issue linkage<commit_after>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import setuptools_scm extensions = [ 'sphinx.ext.autodoc', 'rst.linker', ] # General information about the project. project = 'pytest-runner' copyright = '2015,2016 Jason R. Coombs' # The short X.Y version. version = setuptools_scm.get_version(root='..', relative_to=__file__) # The full version, including alpha/beta/rc tags. release = version master_doc = 'index' link_files = { 'CHANGES.rst': dict( using=dict( GH='https://github.com', project=project, ), replace=[ dict( pattern=r"(Issue )?#(?P<issue>\d+)", url='{GH}/pytest-dev/{project}/issues/{issue}', ), dict( pattern=r"^(?m)((?P<scm_version>v?\d+(\.\d+){1,2}))\n[-=]+\n", with_scm="{text}\n{rev[timestamp]:%d %b %Y}\n", ), ], ), }
56856ac1103ec9f3ba0f2da81832a59e7e773256
doc/ext/nova_autodoc.py
doc/ext/nova_autodoc.py
import os from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
import gettext import os gettext.install('nova') from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
Fix doc building endpoint for gettext.
Fix doc building endpoint for gettext.
Python
apache-2.0
blueboxgroup/nova,BeyondTheClouds/nova,russellb/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,SUSE-Cloud/nova,termie/nova-migration-demo,shahar-stratoscale/nova,rajalokan/nova,devendermishrajio/nova_test_latest,aristanetworks/arista-ovs-nova,NoBodyCam/TftpPxeBootBareMetal,virtualopensystems/nova,dims/nova,bclau/nova,gooddata/openstack-nova,anotherjesse/nova,sridevikoushik31/nova,Yuriy-Leonov/nova,zhimin711/nova,tanglei528/nova,sridevikoushik31/openstack,gooddata/openstack-nova,orbitfp7/nova,eneabio/nova,ruslanloman/nova,cyx1231st/nova,ted-gould/nova,dstroppa/openstack-smartos-nova-grizzly,Yusuke1987/openstack_template,anotherjesse/nova,gspilio/nova,zhimin711/nova,paulmathews/nova,josephsuh/extra-specs,KarimAllah/nova,KarimAllah/nova,usc-isi/nova,russellb/nova,leilihh/novaha,yosshy/nova,eonpatapon/nova,badock/nova,adelina-t/nova,openstack/nova,yatinkumbhare/openstack-nova,ted-gould/nova,Yusuke1987/openstack_template,Triv90/Nova,usc-isi/extra-specs,barnsnake351/nova,tudorvio/nova,dawnpower/nova,edulramirez/nova,jianghuaw/nova,cloudbase/nova,maheshp/novatest,luogangyi/bcec-nova,scripnichenko/nova,adelina-t/nova,viggates/nova,double12gzh/nova,CiscoSystems/nova,belmiromoreira/nova,raildo/nova,alexandrucoman/vbox-nova-driver,DirectXMan12/nova-hacking,petrutlucian94/nova,maoy/zknova,savi-dev/nova,dawnpower/nova,TwinkleChawla/nova,mahak/nova,imsplitbit/nova,cernops/nova,cernops/nova,phenoxim/nova,maelnor/nova,silenceli/nova,JioCloud/nova_test_latest,felixma/nova,salv-orlando/MyRepo,berrange/nova,joker946/nova,thomasem/nova,leilihh/novaha,CEG-FYP-OpenStack/scheduler,badock/nova,petrutlucian94/nova_dev,akash1808/nova,alaski/nova,takeshineshiro/nova,orbitfp7/nova,yrobla/nova,termie/pupa,zaina/nova,belmiromoreira/nova,sridevikoushik31/nova,alexandrucoman/vbox-nova-driver,maheshp/novatest,sebrandon1/nova,Tehsmash/nova,houshengbo/nova_vmware_compute_driver,KarimAllah/nova,projectcalico/calico-nova,rickerc/nova_audit,NewpTone/stacklab-nova,barnsnake351/nova,plumgrid/plumgrid-nova,yatinkumbhare/openstack-nova,eneabio/nova,fnordahl/nova,sridevikoushik31/openstack,savi-dev/nova,NewpTone/stacklab-nova,sridevikoushik31/nova,nikesh-mahalka/nova,eharney/nova,maheshp/novatest,psiwczak/openstack,fajoy/nova,rahulunair/nova,DirectXMan12/nova-hacking,yrobla/nova,hanlind/nova,CCI-MOC/nova,noironetworks/nova,devendermishrajio/nova,thomasem/nova,vmturbo/nova,JianyuWang/nova,OpenAcademy-OpenStack/nova-scheduler,klmitch/nova,saleemjaveds/https-github.com-openstack-nova,jeffrey4l/nova,dstroppa/openstack-smartos-nova-grizzly,mikalstill/nova,isyippee/nova,jeffrey4l/nova,ruslanloman/nova,shahar-stratoscale/nova,tanglei528/nova,alaski/nova,isyippee/nova,vmturbo/nova,fajoy/nova,eayunstack/nova,NewpTone/stacklab-nova,mgagne/nova,DirectXMan12/nova-hacking,shail2810/nova,rajalokan/nova,sileht/deb-openstack-nova,blueboxgroup/nova,superstack/nova,Tehsmash/nova,cloudbase/nova-virtualbox,akash1808/nova_test_latest,cernops/nova,gooddata/openstack-nova,zzicewind/nova,alvarolopez/nova,mgagne/nova,eharney/nova,eneabio/nova,Metaswitch/calico-nova,cloudbase/nova,watonyweng/nova,maoy/zknova,whitepages/nova,klmitch/nova,BeyondTheClouds/nova,saleemjaveds/https-github.com-openstack-nova,projectcalico/calico-nova,raildo/nova,tangfeixiong/nova,citrix-openstack-build/nova,Triv90/Nova,j-carpentier/nova,akash1808/nova,josephsuh/extra-specs,Juniper/nova,fajoy/nova,devendermishrajio/nova_test_latest,Juniper/nova,tudorvio/nova,devendermishrajio/nova,usc-isi/extra-specs,usc-isi/nova,BeyondTheClouds/nova,vladikr/nova_drafts,cloudbau/nova,bgxavier/nova,redhat-openstack/nova,termie/pupa,houshengbo/nova_vmware_compute_driver,hanlind/nova,mmnelemane/nova,NoBodyCam/TftpPxeBootBareMetal,TieWei/nova,sridevikoushik31/nova,rrader/nova-docker-plugin,Francis-Liu/animated-broccoli,JianyuWang/nova,rahulunair/nova,TieWei/nova,virtualopensystems/nova,yrobla/nova,gspilio/nova,LoHChina/nova,akash1808/nova_test_latest,kimjaejoong/nova,plumgrid/plumgrid-nova,imsplitbit/nova,apporc/nova,eonpatapon/nova,leilihh/nova,affo/nova,scripnichenko/nova,Stavitsky/nova,bclau/nova,spring-week-topos/nova-week,savi-dev/nova,silenceli/nova,iuliat/nova,OpenAcademy-OpenStack/nova-scheduler,eayunstack/nova,vmturbo/nova,shail2810/nova,TwinkleChawla/nova,LoHChina/nova,varunarya10/nova_test_latest,ntt-sic/nova,openstack/nova,superstack/nova,CCI-MOC/nova,NeCTAR-RC/nova,jianghuaw/nova,rajalokan/nova,Francis-Liu/animated-broccoli,mmnelemane/nova,Yuriy-Leonov/nova,varunarya10/nova_test_latest,josephsuh/extra-specs,tealover/nova,phenoxim/nova,petrutlucian94/nova,sileht/deb-openstack-nova,klmitch/nova,rrader/nova-docker-plugin,edulramirez/nova,double12gzh/nova,paulmathews/nova,iuliat/nova,ntt-sic/nova,felixma/nova,takeshineshiro/nova,mikalstill/nova,usc-isi/extra-specs,vladikr/nova_drafts,russellb/nova,rajalokan/nova,angdraug/nova,salv-orlando/MyRepo,jianghuaw/nova,bigswitch/nova,tianweizhang/nova,sacharya/nova,gooddata/openstack-nova,rickerc/nova_audit,devoid/nova,paulmathews/nova,MountainWei/nova,SUSE-Cloud/nova,qwefi/nova,ewindisch/nova,Triv90/Nova,petrutlucian94/nova_dev,kimjaejoong/nova,superstack/nova,Metaswitch/calico-nova,CiscoSystems/nova,dstroppa/openstack-smartos-nova-grizzly,qwefi/nova,termie/pupa,spring-week-topos/nova-week,sileht/deb-openstack-nova,citrix-openstack-build/nova,berrange/nova,JioCloud/nova_test_latest,houshengbo/nova_vmware_compute_driver,shootstar/novatest,joker946/nova,usc-isi/nova,mahak/nova,sridevikoushik31/openstack,CloudServer/nova,zaina/nova,Juniper/nova,openstack/nova,Brocade-OpenSource/OpenStack-DNRM-Nova,alvarolopez/nova,gspilio/nova,psiwczak/openstack,salv-orlando/MyRepo,affo/nova,leilihh/nova,cloudbau/nova,termie/nova-migration-demo,Stavitsky/nova,mikalstill/nova,JioCloud/nova,klmitch/nova,watonyweng/nova,redhat-openstack/nova,nikesh-mahalka/nova,maoy/zknova,tianweizhang/nova,dims/nova,jianghuaw/nova,zzicewind/nova,apporc/nova,noironetworks/nova,NoBodyCam/TftpPxeBootBareMetal,CEG-FYP-OpenStack/scheduler,tealover/nova,vmturbo/nova,yosshy/nova,cloudbase/nova,mahak/nova,aristanetworks/arista-ovs-nova,sebrandon1/nova,whitepages/nova,ewindisch/nova,shootstar/novatest,angdraug/nova,NeCTAR-RC/nova,sacharya/nova,tangfeixiong/nova,mandeepdhami/nova,anotherjesse/nova,fnordahl/nova,cyx1231st/nova,luogangyi/bcec-nova,viggates/nova,MountainWei/nova,rahulunair/nova,CloudServer/nova,j-carpentier/nova,mandeepdhami/nova,Juniper/nova,maelnor/nova,psiwczak/openstack,bgxavier/nova,cloudbase/nova-virtualbox,bigswitch/nova,sebrandon1/nova,aristanetworks/arista-ovs-nova,termie/nova-migration-demo,devoid/nova,hanlind/nova,JioCloud/nova
import os from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0] Fix doc building endpoint for gettext.
import gettext import os gettext.install('nova') from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
<commit_before>import os from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0] <commit_msg>Fix doc building endpoint for gettext.<commit_after>
import gettext import os gettext.install('nova') from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
import os from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0] Fix doc building endpoint for gettext.import gettext import os gettext.install('nova') from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
<commit_before>import os from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0] <commit_msg>Fix doc building endpoint for gettext.<commit_after>import gettext import os gettext.install('nova') from nova import utils def setup(app): rootdir = os.path.abspath(app.srcdir + '/..') print "**Autodocumenting from %s" % rootdir rv = utils.execute('cd %s && ./generate_autodoc_index.sh' % rootdir) print rv[0]
74a2e0825f3029b6d3a3164221d11fbdf551b8d1
demo/demo/widgets/live.py
demo/demo/widgets/live.py
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <ul id="data"/> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <form onsubmit="return send_msg()"> <input name="text" id="text"/> </form> <ul id="data"/> <script> function send_msg() { moksha.send_message('helloworld', {'msg': $('#text').val()}); $('#text').val(''); return false; } </script> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
Allow people to send messages in our basic HelloWorldWidget demo
Allow people to send messages in our basic HelloWorldWidget demo
Python
apache-2.0
ralphbean/moksha,ralphbean/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,lmacken/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <ul id="data"/> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """ Allow people to send messages in our basic HelloWorldWidget demo
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <form onsubmit="return send_msg()"> <input name="text" id="text"/> </form> <ul id="data"/> <script> function send_msg() { moksha.send_message('helloworld', {'msg': $('#text').val()}); $('#text').val(''); return false; } </script> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
<commit_before>from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <ul id="data"/> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """ <commit_msg>Allow people to send messages in our basic HelloWorldWidget demo<commit_after>
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <form onsubmit="return send_msg()"> <input name="text" id="text"/> </form> <ul id="data"/> <script> function send_msg() { moksha.send_message('helloworld', {'msg': $('#text').val()}); $('#text').val(''); return false; } </script> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <ul id="data"/> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """ Allow people to send messages in our basic HelloWorldWidget demofrom moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <form onsubmit="return send_msg()"> <input name="text" id="text"/> </form> <ul id="data"/> <script> function send_msg() { moksha.send_message('helloworld', {'msg': $('#text').val()}); $('#text').val(''); return false; } </script> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
<commit_before>from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <ul id="data"/> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """ <commit_msg>Allow people to send messages in our basic HelloWorldWidget demo<commit_after>from moksha.api.widgets.live import LiveWidget class HelloWorldWidget(LiveWidget): topic = "helloworld" template = """ <b>Hello World Widget</b> <form onsubmit="return send_msg()"> <input name="text" id="text"/> </form> <ul id="data"/> <script> function send_msg() { moksha.send_message('helloworld', {'msg': $('#text').val()}); $('#text').val(''); return false; } </script> """ onmessage = """ $('<li/>').text(json.msg).prependTo('#data'); """
26581b24dd00c3b0a0928fe0b24ae129c701fb58
jarbas/frontend/tests/test_bundle_dependecies.py
jarbas/frontend/tests/test_bundle_dependecies.py
from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files)
from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files)
Fix test for Elm files lookup
Fix test for Elm files lookup
Python
mit
datasciencebr/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,marcusrehm/serenata-de-amor,marcusrehm/serenata-de-amor,datasciencebr/jarbas,marcusrehm/serenata-de-amor,Guilhermeslucas/jarbas,datasciencebr/jarbas,Guilhermeslucas/jarbas,rogeriochaves/jarbas,rogeriochaves/jarbas,Guilhermeslucas/jarbas,datasciencebr/jarbas,datasciencebr/serenata-de-amor,rogeriochaves/jarbas,datasciencebr/serenata-de-amor,marcusrehm/serenata-de-amor
from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files) Fix test for Elm files lookup
from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files)
<commit_before>from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files) <commit_msg>Fix test for Elm files lookup<commit_after>
from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files)
from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files) Fix test for Elm files lookupfrom glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files)
<commit_before>from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): files = set(get_all_bundle_files(elm)) self.assertEqual(9, len(files), files) <commit_msg>Fix test for Elm files lookup<commit_after>from glob import glob from django.test import TestCase from webassets.bundle import get_all_bundle_files from jarbas.frontend.assets import elm class TestDependencies(TestCase): def test_dependencies(self): expected = len(glob('jarbas/frontend/elm/**/*.elm', recursive=True)) files = set(get_all_bundle_files(elm)) self.assertEqual(expected, len(files), files)
cd199c379145c6dcabd66f1771397c82e445c932
test_installation.py
test_installation.py
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise try: import conda except ImportError: print("conda is needed (either anaconda or miniconda from https://www.continuum.io/downloads)") print("(try rerunning this script under conda if you are using for system's python distribution)") else: major, minor, patch = map(int, conda.__version__.split('.')) if major > 4 or (major == 4 and minor >= 1): pass else: print("please update conda ($ conda update conda), we need conda >= 4.1.0") exit(1) try: import matplotlib except ImportError: print("matplotlib is required for the tutorial") try: import notebook except ImportError: print("notebook (jupyter notebook) is required for the tutorial")
Make test script more extensive (conda, notebook, matplotlib)
Make test script more extensive (conda, notebook, matplotlib)
Python
bsd-3-clause
sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial,sympy/scipy-2017-codegen-tutorial
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise Make test script more extensive (conda, notebook, matplotlib)
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise try: import conda except ImportError: print("conda is needed (either anaconda or miniconda from https://www.continuum.io/downloads)") print("(try rerunning this script under conda if you are using for system's python distribution)") else: major, minor, patch = map(int, conda.__version__.split('.')) if major > 4 or (major == 4 and minor >= 1): pass else: print("please update conda ($ conda update conda), we need conda >= 4.1.0") exit(1) try: import matplotlib except ImportError: print("matplotlib is required for the tutorial") try: import notebook except ImportError: print("notebook (jupyter notebook) is required for the tutorial")
<commit_before>#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise <commit_msg>Make test script more extensive (conda, notebook, matplotlib)<commit_after>
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise try: import conda except ImportError: print("conda is needed (either anaconda or miniconda from https://www.continuum.io/downloads)") print("(try rerunning this script under conda if you are using for system's python distribution)") else: major, minor, patch = map(int, conda.__version__.split('.')) if major > 4 or (major == 4 and minor >= 1): pass else: print("please update conda ($ conda update conda), we need conda >= 4.1.0") exit(1) try: import matplotlib except ImportError: print("matplotlib is required for the tutorial") try: import notebook except ImportError: print("notebook (jupyter notebook) is required for the tutorial")
#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise Make test script more extensive (conda, notebook, matplotlib)#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise try: import conda except ImportError: print("conda is needed (either anaconda or miniconda from https://www.continuum.io/downloads)") print("(try rerunning this script under conda if you are using for system's python distribution)") else: major, minor, patch = map(int, conda.__version__.split('.')) if major > 4 or (major == 4 and minor >= 1): pass else: print("please update conda ($ conda update conda), we need conda >= 4.1.0") exit(1) try: import matplotlib except ImportError: print("matplotlib is required for the tutorial") try: import notebook except ImportError: print("notebook (jupyter notebook) is required for the tutorial")
<commit_before>#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise <commit_msg>Make test script more extensive (conda, notebook, matplotlib)<commit_after>#!/usr/bin/env python from sys import exit try: import sympy except ImportError: print("SymPy must be installed for the tutorial") if sympy.__version__ != '1.1': print("SymPy 1.1 is required for the tutorial. Note SymPy 1.1 will be released before July 10.") try: import numpy except ImportError: print("NumPy is required for the tutorial") try: import Cython except ImportError: print("Cython is required for the tutorial") try: import scipy except ImportError: print("scipy is required for the tutorial") from sympy.utilities.autowrap import ufuncify from sympy.abc import x from sympy import sin try: f = ufuncify(x, sin(x)) assert f(0) == 0 except: print("sympy.utilities.autowrap.ufuncify does not work") raise try: import conda except ImportError: print("conda is needed (either anaconda or miniconda from https://www.continuum.io/downloads)") print("(try rerunning this script under conda if you are using for system's python distribution)") else: major, minor, patch = map(int, conda.__version__.split('.')) if major > 4 or (major == 4 and minor >= 1): pass else: print("please update conda ($ conda update conda), we need conda >= 4.1.0") exit(1) try: import matplotlib except ImportError: print("matplotlib is required for the tutorial") try: import notebook except ImportError: print("notebook (jupyter notebook) is required for the tutorial")
4a8170079e2b715d40e94f5d407d110a635f8a5d
InvenTree/common/apps.py
InvenTree/common/apps.py
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settings() def add_instance_name(self): """ Check if an InstanceName has been defined for this database. If not, create a random one! """ # See note above from .models import InvenTreeSetting """ Note: The "old" instance name was stored under the key 'InstanceName', but has now been renamed to 'INVENTREE_INSTANCE'. """ try: # Quick exit if a value already exists for 'inventree_instance' if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): return # Default instance name instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') # Use the old name if it exists if InvenTreeSetting.objects.filter(key='InstanceName').exists(): instance = InvenTreeSetting.objects.get(key='InstanceName') instance_name = instance.value # Delete the legacy key instance.delete() # Create new value InvenTreeSetting.objects.create( key='INVENTREE_INSTANCE', value=instance_name ) except (OperationalError, ProgrammingError, IntegrityError): # Migrations have not yet been applied - table does not exist pass def add_default_settings(self): """ Create all required settings, if they do not exist. """ from .models import InvenTreeSetting for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): try: settings = InvenTreeSetting.objects.filter(key__iexact=key) if settings.count() == 0: value = InvenTreeSetting.get_default_value(key) print(f"Creating default setting for {key} -> '{value}'") InvenTreeSetting.objects.create( key=key, value=value ) return elif settings.count() > 1: # Prevent multiple shadow copies of the same setting! for setting in settings[1:]: setting.delete() # Ensure that the key has the correct case setting = settings[0] if not setting.key == key: setting.key = key setting.save() except (OperationalError, ProgrammingError, IntegrityError): # Table might not yet exist pass
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
Remove code which automatically created settings objects on server launch
Remove code which automatically created settings objects on server launch
Python
mit
inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settings() def add_instance_name(self): """ Check if an InstanceName has been defined for this database. If not, create a random one! """ # See note above from .models import InvenTreeSetting """ Note: The "old" instance name was stored under the key 'InstanceName', but has now been renamed to 'INVENTREE_INSTANCE'. """ try: # Quick exit if a value already exists for 'inventree_instance' if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): return # Default instance name instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') # Use the old name if it exists if InvenTreeSetting.objects.filter(key='InstanceName').exists(): instance = InvenTreeSetting.objects.get(key='InstanceName') instance_name = instance.value # Delete the legacy key instance.delete() # Create new value InvenTreeSetting.objects.create( key='INVENTREE_INSTANCE', value=instance_name ) except (OperationalError, ProgrammingError, IntegrityError): # Migrations have not yet been applied - table does not exist pass def add_default_settings(self): """ Create all required settings, if they do not exist. """ from .models import InvenTreeSetting for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): try: settings = InvenTreeSetting.objects.filter(key__iexact=key) if settings.count() == 0: value = InvenTreeSetting.get_default_value(key) print(f"Creating default setting for {key} -> '{value}'") InvenTreeSetting.objects.create( key=key, value=value ) return elif settings.count() > 1: # Prevent multiple shadow copies of the same setting! for setting in settings[1:]: setting.delete() # Ensure that the key has the correct case setting = settings[0] if not setting.key == key: setting.key = key setting.save() except (OperationalError, ProgrammingError, IntegrityError): # Table might not yet exist pass Remove code which automatically created settings objects on server launch
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
<commit_before>from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settings() def add_instance_name(self): """ Check if an InstanceName has been defined for this database. If not, create a random one! """ # See note above from .models import InvenTreeSetting """ Note: The "old" instance name was stored under the key 'InstanceName', but has now been renamed to 'INVENTREE_INSTANCE'. """ try: # Quick exit if a value already exists for 'inventree_instance' if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): return # Default instance name instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') # Use the old name if it exists if InvenTreeSetting.objects.filter(key='InstanceName').exists(): instance = InvenTreeSetting.objects.get(key='InstanceName') instance_name = instance.value # Delete the legacy key instance.delete() # Create new value InvenTreeSetting.objects.create( key='INVENTREE_INSTANCE', value=instance_name ) except (OperationalError, ProgrammingError, IntegrityError): # Migrations have not yet been applied - table does not exist pass def add_default_settings(self): """ Create all required settings, if they do not exist. """ from .models import InvenTreeSetting for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): try: settings = InvenTreeSetting.objects.filter(key__iexact=key) if settings.count() == 0: value = InvenTreeSetting.get_default_value(key) print(f"Creating default setting for {key} -> '{value}'") InvenTreeSetting.objects.create( key=key, value=value ) return elif settings.count() > 1: # Prevent multiple shadow copies of the same setting! for setting in settings[1:]: setting.delete() # Ensure that the key has the correct case setting = settings[0] if not setting.key == key: setting.key = key setting.save() except (OperationalError, ProgrammingError, IntegrityError): # Table might not yet exist pass <commit_msg>Remove code which automatically created settings objects on server launch<commit_after>
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settings() def add_instance_name(self): """ Check if an InstanceName has been defined for this database. If not, create a random one! """ # See note above from .models import InvenTreeSetting """ Note: The "old" instance name was stored under the key 'InstanceName', but has now been renamed to 'INVENTREE_INSTANCE'. """ try: # Quick exit if a value already exists for 'inventree_instance' if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): return # Default instance name instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') # Use the old name if it exists if InvenTreeSetting.objects.filter(key='InstanceName').exists(): instance = InvenTreeSetting.objects.get(key='InstanceName') instance_name = instance.value # Delete the legacy key instance.delete() # Create new value InvenTreeSetting.objects.create( key='INVENTREE_INSTANCE', value=instance_name ) except (OperationalError, ProgrammingError, IntegrityError): # Migrations have not yet been applied - table does not exist pass def add_default_settings(self): """ Create all required settings, if they do not exist. """ from .models import InvenTreeSetting for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): try: settings = InvenTreeSetting.objects.filter(key__iexact=key) if settings.count() == 0: value = InvenTreeSetting.get_default_value(key) print(f"Creating default setting for {key} -> '{value}'") InvenTreeSetting.objects.create( key=key, value=value ) return elif settings.count() > 1: # Prevent multiple shadow copies of the same setting! for setting in settings[1:]: setting.delete() # Ensure that the key has the correct case setting = settings[0] if not setting.key == key: setting.key = key setting.save() except (OperationalError, ProgrammingError, IntegrityError): # Table might not yet exist pass Remove code which automatically created settings objects on server launchfrom django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
<commit_before>from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): """ Will be called when the Common app is first loaded """ self.add_instance_name() self.add_default_settings() def add_instance_name(self): """ Check if an InstanceName has been defined for this database. If not, create a random one! """ # See note above from .models import InvenTreeSetting """ Note: The "old" instance name was stored under the key 'InstanceName', but has now been renamed to 'INVENTREE_INSTANCE'. """ try: # Quick exit if a value already exists for 'inventree_instance' if InvenTreeSetting.objects.filter(key='INVENTREE_INSTANCE').exists(): return # Default instance name instance_name = InvenTreeSetting.get_default_value('INVENTREE_INSTANCE') # Use the old name if it exists if InvenTreeSetting.objects.filter(key='InstanceName').exists(): instance = InvenTreeSetting.objects.get(key='InstanceName') instance_name = instance.value # Delete the legacy key instance.delete() # Create new value InvenTreeSetting.objects.create( key='INVENTREE_INSTANCE', value=instance_name ) except (OperationalError, ProgrammingError, IntegrityError): # Migrations have not yet been applied - table does not exist pass def add_default_settings(self): """ Create all required settings, if they do not exist. """ from .models import InvenTreeSetting for key in InvenTreeSetting.GLOBAL_SETTINGS.keys(): try: settings = InvenTreeSetting.objects.filter(key__iexact=key) if settings.count() == 0: value = InvenTreeSetting.get_default_value(key) print(f"Creating default setting for {key} -> '{value}'") InvenTreeSetting.objects.create( key=key, value=value ) return elif settings.count() > 1: # Prevent multiple shadow copies of the same setting! for setting in settings[1:]: setting.delete() # Ensure that the key has the correct case setting = settings[0] if not setting.key == key: setting.key = key setting.save() except (OperationalError, ProgrammingError, IntegrityError): # Table might not yet exist pass <commit_msg>Remove code which automatically created settings objects on server launch<commit_after>from django.apps import AppConfig from django.db.utils import OperationalError, ProgrammingError, IntegrityError class CommonConfig(AppConfig): name = 'common' def ready(self): pass
f9dca979768ea17cee0993dac5bac4257bda623e
settings.py
settings.py
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False}
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar #INSTALLED_APPS += ('debug_toolbar',) #MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False}
Comment out the debug tool bar
Comment out the debug tool bar
Python
agpl-3.0
sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False} Comment out the debug tool bar
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar #INSTALLED_APPS += ('debug_toolbar',) #MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False}
<commit_before>from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False} <commit_msg>Comment out the debug tool bar<commit_after>
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar #INSTALLED_APPS += ('debug_toolbar',) #MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False}
from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False} Comment out the debug tool barfrom settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar #INSTALLED_APPS += ('debug_toolbar',) #MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False}
<commit_before>from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar INSTALLED_APPS += ('debug_toolbar',) MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False} <commit_msg>Comment out the debug tool bar<commit_after>from settings_common import * DEBUG = TEMPLATE_DEBUG = True DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_NAME = 'daisyproducer_dev' DATABASE_USER = 'eglic' DATABASE_PASSWORD = '' DAISY_PIPELINE_PATH = os.path.join(PROJECT_DIR, '..', '..', 'tmp', 'pipeline-20090410') # debug toolbar #INSTALLED_APPS += ('debug_toolbar',) #MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',) INTERNAL_IPS = ('127.0.0.1',) DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS' : False}
ec42a3cfcb491b265c87160ed9dae0005552acb4
tests/test_result.py
tests/test_result.py
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None with pytest.raises(RelatableObject.DoesNotExist): RelatableObject.search_objects.get(id=test_object.id) @pytest.mark.django_db def test_related_get(es_client): management.call_command("sync_es") test_object = mommy.make(RelatableObject) time.sleep(1) # Let the index refresh from_es = RelatableObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None
Work on testing, bulk indexing, etc
Work on testing, bulk indexing, etc
Python
mit
theonion/djes
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None Work on testing, bulk indexing, etc
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None with pytest.raises(RelatableObject.DoesNotExist): RelatableObject.search_objects.get(id=test_object.id) @pytest.mark.django_db def test_related_get(es_client): management.call_command("sync_es") test_object = mommy.make(RelatableObject) time.sleep(1) # Let the index refresh from_es = RelatableObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None
<commit_before>from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None <commit_msg>Work on testing, bulk indexing, etc<commit_after>
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None with pytest.raises(RelatableObject.DoesNotExist): RelatableObject.search_objects.get(id=test_object.id) @pytest.mark.django_db def test_related_get(es_client): management.call_command("sync_es") test_object = mommy.make(RelatableObject) time.sleep(1) # Let the index refresh from_es = RelatableObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None
from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None Work on testing, bulk indexing, etcfrom django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None with pytest.raises(RelatableObject.DoesNotExist): RelatableObject.search_objects.get(id=test_object.id) @pytest.mark.django_db def test_related_get(es_client): management.call_command("sync_es") test_object = mommy.make(RelatableObject) time.sleep(1) # Let the index refresh from_es = RelatableObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None
<commit_before>from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject @pytest.mark.django_db def test_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None <commit_msg>Work on testing, bulk indexing, etc<commit_after>from django.core import management import pytest from model_mommy import mommy import time from example.app.models import SimpleObject, RelatableObject @pytest.mark.django_db def test_simple_get(es_client): management.call_command("sync_es") test_object = mommy.make(SimpleObject) time.sleep(1) # Let the index refresh from_es = SimpleObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None with pytest.raises(RelatableObject.DoesNotExist): RelatableObject.search_objects.get(id=test_object.id) @pytest.mark.django_db def test_related_get(es_client): management.call_command("sync_es") test_object = mommy.make(RelatableObject) time.sleep(1) # Let the index refresh from_es = RelatableObject.search_objects.get(id=test_object.id) assert from_es.foo == test_object.foo assert from_es.bar == test_object.bar assert from_es.baz == test_object.baz assert from_es.__class__.__name__ == "SimpleObject_ElasticSearchResult" assert from_es.save is None
517bb590edb65baedc603d8ea64a5b6f5988f076
polyaxon/polyaxon/config_settings/scheduler/__init__.py
polyaxon/polyaxon/config_settings/scheduler/__init__.py
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from .apps import *
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from polyaxon.config_settings.volume_claims import * from .apps import *
Add volume claims to scheduler
Add volume claims to scheduler
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from .apps import * Add volume claims to scheduler
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from polyaxon.config_settings.volume_claims import * from .apps import *
<commit_before>from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from .apps import * <commit_msg>Add volume claims to scheduler<commit_after>
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from polyaxon.config_settings.volume_claims import * from .apps import *
from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from .apps import * Add volume claims to schedulerfrom polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from polyaxon.config_settings.volume_claims import * from .apps import *
<commit_before>from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from .apps import * <commit_msg>Add volume claims to scheduler<commit_after>from polyaxon.config_settings.cors import * from polyaxon.config_settings.dirs import * from polyaxon.config_settings.k8s import * from polyaxon.config_settings.spawner import * from polyaxon.config_settings.registry import * from polyaxon.config_settings.volume_claims import * from .apps import *
39077720e2fcc340b0cc26a4720aa8d895c53263
src/txamqp/queue.py
src/txamqp/queue.py
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result): if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) deferred.addCallback(self._raiseIfClosed) if timeout: deferred.setTimeout(timeout, timeoutFunc=self._timeout) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result, call_id): if call_id is not None: call_id.cancel() if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) call_id = None if timeout: from twisted.internet import reactor call_id = reactor.callLater(timeout, self._timeout, deferred) deferred.addCallback(self._raiseIfClosed, call_id) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
Remove call to setTimeout and use callLater instead.
Remove call to setTimeout and use callLater instead.
Python
apache-2.0
williamsjj/txamqp,dotsent/txamqp,txamqp/txamqp
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result): if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) deferred.addCallback(self._raiseIfClosed) if timeout: deferred.setTimeout(timeout, timeoutFunc=self._timeout) return deferred def close(self): self.put(TimeoutDeferredQueue.END) Remove call to setTimeout and use callLater instead.
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result, call_id): if call_id is not None: call_id.cancel() if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) call_id = None if timeout: from twisted.internet import reactor call_id = reactor.callLater(timeout, self._timeout, deferred) deferred.addCallback(self._raiseIfClosed, call_id) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
<commit_before># coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result): if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) deferred.addCallback(self._raiseIfClosed) if timeout: deferred.setTimeout(timeout, timeoutFunc=self._timeout) return deferred def close(self): self.put(TimeoutDeferredQueue.END) <commit_msg>Remove call to setTimeout and use callLater instead.<commit_after>
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result, call_id): if call_id is not None: call_id.cancel() if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) call_id = None if timeout: from twisted.internet import reactor call_id = reactor.callLater(timeout, self._timeout, deferred) deferred.addCallback(self._raiseIfClosed, call_id) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result): if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) deferred.addCallback(self._raiseIfClosed) if timeout: deferred.setTimeout(timeout, timeoutFunc=self._timeout) return deferred def close(self): self.put(TimeoutDeferredQueue.END) Remove call to setTimeout and use callLater instead.# coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result, call_id): if call_id is not None: call_id.cancel() if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) call_id = None if timeout: from twisted.internet import reactor call_id = reactor.callLater(timeout, self._timeout, deferred) deferred.addCallback(self._raiseIfClosed, call_id) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
<commit_before># coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result): if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) deferred.addCallback(self._raiseIfClosed) if timeout: deferred.setTimeout(timeout, timeoutFunc=self._timeout) return deferred def close(self): self.put(TimeoutDeferredQueue.END) <commit_msg>Remove call to setTimeout and use callLater instead.<commit_after># coding: utf-8 from twisted.internet.defer import DeferredQueue class Empty(Exception): pass class Closed(Exception): pass class TimeoutDeferredQueue(DeferredQueue): END = object() def _timeout(self, deferred): if not deferred.called: if deferred in self.waiting: self.waiting.remove(deferred) deferred.errback(Empty()) def _raiseIfClosed(self, result, call_id): if call_id is not None: call_id.cancel() if result == TimeoutDeferredQueue.END: self.put(TimeoutDeferredQueue.END) raise Closed() else: return result def get(self, timeout=None): deferred = DeferredQueue.get(self) call_id = None if timeout: from twisted.internet import reactor call_id = reactor.callLater(timeout, self._timeout, deferred) deferred.addCallback(self._raiseIfClosed, call_id) return deferred def close(self): self.put(TimeoutDeferredQueue.END)
7eeb990644f387741ff4c217e1eaeddbe250988f
style_grader_main.py
style_grader_main.py
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): student_file_names = get_arguments(sys.argv[1:]) sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main()
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') # Quick fix for now - ultimately this should be handled using argparse (TODO) if len(sys.argv) == 1: # No files were provided sys.stderr.write("Error: No files provided\n") # Should print usage info here, but argparse will autogen that - skipping this until that's decided sys.stderr.write("<Generic usage info>\n") student_file_names = get_arguments(sys.argv[1:]) rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main()
Check at least one file was provided
Check at least one file was provided
Python
mit
vianuevm/cppStyle,vianuevm/cppStyle,vianuevm/cppStyle,vianuevm/cppStyle
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): student_file_names = get_arguments(sys.argv[1:]) sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main() Check at least one file was provided
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') # Quick fix for now - ultimately this should be handled using argparse (TODO) if len(sys.argv) == 1: # No files were provided sys.stderr.write("Error: No files provided\n") # Should print usage info here, but argparse will autogen that - skipping this until that's decided sys.stderr.write("<Generic usage info>\n") student_file_names = get_arguments(sys.argv[1:]) rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): student_file_names = get_arguments(sys.argv[1:]) sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main() <commit_msg>Check at least one file was provided<commit_after>
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') # Quick fix for now - ultimately this should be handled using argparse (TODO) if len(sys.argv) == 1: # No files were provided sys.stderr.write("Error: No files provided\n") # Should print usage info here, but argparse will autogen that - skipping this until that's decided sys.stderr.write("<Generic usage info>\n") student_file_names = get_arguments(sys.argv[1:]) rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main()
#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): student_file_names = get_arguments(sys.argv[1:]) sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main() Check at least one file was provided#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') # Quick fix for now - ultimately this should be handled using argparse (TODO) if len(sys.argv) == 1: # No files were provided sys.stderr.write("Error: No files provided\n") # Should print usage info here, but argparse will autogen that - skipping this until that's decided sys.stderr.write("<Generic usage info>\n") student_file_names = get_arguments(sys.argv[1:]) rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): student_file_names = get_arguments(sys.argv[1:]) sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main() <commit_msg>Check at least one file was provided<commit_after>#!/usr/bin/python from style_grader_functions import * #TODO: Set up standard error to print properly def main(): sys.stderr = codecs.StreamReaderWriter(sys.stderr, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace') # Quick fix for now - ultimately this should be handled using argparse (TODO) if len(sys.argv) == 1: # No files were provided sys.stderr.write("Error: No files provided\n") # Should print usage info here, but argparse will autogen that - skipping this until that's decided sys.stderr.write("<Generic usage info>\n") student_file_names = get_arguments(sys.argv[1:]) rubric = StyleRubric() #rubric.reset_error_count() # Is this line necessary? operator_space_tracker = OperatorSpace() for filename in student_file_names: rubric.reset_for_new_file() # Fixes issue with multiple command-line arguments grade_student_file(filename, rubric, operator_space_tracker) #For debugging purposes only print "Total Errors: " + str(rubric.total_errors) for x, y in rubric.error_types.items(): print x, y #function called on each filename function(fileName, rubric) #print / send results if __name__ == '__main__': main()
baabb3a84418516e5a76a61b334b7879737b3d4b
goog/urls.py
goog/urls.py
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), )
try: from django.conf.urls.defaults import patterns, url except ImportError: # Django >= 1.6 from django.conf.urls import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), )
Fix imports for Django >= 1.6
Fix imports for Django >= 1.6
Python
bsd-3-clause
andialbrecht/django-goog
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), ) Fix imports for Django >= 1.6
try: from django.conf.urls.defaults import patterns, url except ImportError: # Django >= 1.6 from django.conf.urls import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), )
<commit_before>from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), ) <commit_msg>Fix imports for Django >= 1.6<commit_after>
try: from django.conf.urls.defaults import patterns, url except ImportError: # Django >= 1.6 from django.conf.urls import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), )
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), ) Fix imports for Django >= 1.6try: from django.conf.urls.defaults import patterns, url except ImportError: # Django >= 1.6 from django.conf.urls import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), )
<commit_before>from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), ) <commit_msg>Fix imports for Django >= 1.6<commit_after>try: from django.conf.urls.defaults import patterns, url except ImportError: # Django >= 1.6 from django.conf.urls import patterns, url urlpatterns = patterns( 'goog.views', url('^__goog__/(?P<path>.*)$', 'serve_closure', name='goog_serve_closure'), # FIXME(andi): That's a bit ugly to cover third_party as an URL... url('^third_party/(?P<path>.*)$', 'serve_closure_thirdparty', name='goog_serve_closure_tp'), )
ed46ee16ed1b8efcee3697d3da909f72b0755a13
webcomix/tests/test_docker.py
webcomix/tests/test_docker.py
import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill() def test_no_javascript_spawns_no_container(cleanup_container): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(cleanup_container): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(cleanup_container): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
Add test fixture for docker tests
Add test fixture for docker tests
Python
mit
J-CPelletier/webcomix,J-CPelletier/webcomix
import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None Add test fixture for docker tests
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill() def test_no_javascript_spawns_no_container(cleanup_container): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(cleanup_container): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(cleanup_container): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
<commit_before>import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None <commit_msg>Add test fixture for docker tests<commit_after>
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill() def test_no_javascript_spawns_no_container(cleanup_container): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(cleanup_container): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(cleanup_container): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None Add test fixture for docker testsimport docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill() def test_no_javascript_spawns_no_container(cleanup_container): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(cleanup_container): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(cleanup_container): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
<commit_before>import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None <commit_msg>Add test fixture for docker tests<commit_after>import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill() def test_no_javascript_spawns_no_container(cleanup_container): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(cleanup_container): manager = DockerManager(True) manager.__enter__() assert manager._get_container() is not None manager.__exit__(None, None, None) def test_javascript_exit_removes_container(cleanup_container): manager = DockerManager(True) manager.__enter__() manager.__exit__(None, None, None) assert manager._get_container() is None
16b07dd961cbe55ee452ed6057048ec452ffbd72
custom/icds/management/commands/copy_icds_app.py
custom/icds/management/commands/copy_icds_app.py
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name})
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) old_to_new = get_old_to_new_config_ids(old_app, new_app) for form in new_app.get_forms(): for old_id, new_id in old_to_new: form.source = form.source.replace(old_id, new_id) new_app.save() def get_old_to_new_config_ids(old_app, new_app): return [ (old_config.uuid, new_config.uuid) for old_module, new_module in zip(old_app.get_report_modules(), new_app.get_report_modules()) for old_config, new_config in zip(old_module.report_configs, new_module.report_configs) ]
Replace old config IDs with the new ones
Replace old config IDs with the new ones
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) Replace old config IDs with the new ones
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) old_to_new = get_old_to_new_config_ids(old_app, new_app) for form in new_app.get_forms(): for old_id, new_id in old_to_new: form.source = form.source.replace(old_id, new_id) new_app.save() def get_old_to_new_config_ids(old_app, new_app): return [ (old_config.uuid, new_config.uuid) for old_module, new_module in zip(old_app.get_report_modules(), new_app.get_report_modules()) for old_config, new_config in zip(old_module.report_configs, new_module.report_configs) ]
<commit_before>from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) <commit_msg>Replace old config IDs with the new ones<commit_after>
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) old_to_new = get_old_to_new_config_ids(old_app, new_app) for form in new_app.get_forms(): for old_id, new_id in old_to_new: form.source = form.source.replace(old_id, new_id) new_app.save() def get_old_to_new_config_ids(old_app, new_app): return [ (old_config.uuid, new_config.uuid) for old_module, new_module in zip(old_app.get_report_modules(), new_app.get_report_modules()) for old_config, new_config in zip(old_module.report_configs, new_module.report_configs) ]
from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) Replace old config IDs with the new onesfrom __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) old_to_new = get_old_to_new_config_ids(old_app, new_app) for form in new_app.get_forms(): for old_id, new_id in old_to_new: form.source = form.source.replace(old_id, new_id) new_app.save() def get_old_to_new_config_ids(old_app, new_app): return [ (old_config.uuid, new_config.uuid) for old_module, new_module in zip(old_app.get_report_modules(), new_app.get_report_modules()) for old_config, new_config in zip(old_module.report_configs, new_module.report_configs) ]
<commit_before>from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) <commit_msg>Replace old config IDs with the new ones<commit_after>from __future__ import absolute_import, print_function, unicode_literals from django.core.management import BaseCommand from corehq.apps.app_manager.dbaccessors import get_build_doc_by_version, wrap_app from corehq.apps.app_manager.models import import_app class Command(BaseCommand): help = "Make a copy of a specific version of an application on the same domain" def add_arguments(self, parser): parser.add_argument('domain') parser.add_argument('app_id') parser.add_argument('version') parser.add_argument('new_name') def handle(self, domain, app_id, version, new_name, **options): old_app = get_build_doc_by_version(domain, app_id, version) if not old_app: raise Exception("No app found with id '{}' and version '{}', on '{}'" .format(app_id, version, domain)) old_app = wrap_app(old_app) old_app.convert_build_to_app() new_app = import_app(old_app.to_json(), domain, source_properties={'name': new_name}) old_to_new = get_old_to_new_config_ids(old_app, new_app) for form in new_app.get_forms(): for old_id, new_id in old_to_new: form.source = form.source.replace(old_id, new_id) new_app.save() def get_old_to_new_config_ids(old_app, new_app): return [ (old_config.uuid, new_config.uuid) for old_module, new_module in zip(old_app.get_report_modules(), new_app.get_report_modules()) for old_config, new_config in zip(old_module.report_configs, new_module.report_configs) ]
6f356a94c56053b47fb38670a93e04f46740f21e
tartpy/eventloop.py
tartpy/eventloop.py
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.loop.stop() def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.thread_do(self.loop.stop) def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)
Make sure that 'stop' works from everywhere
Make sure that 'stop' works from everywhere
Python
mit
waltermoreira/tartpy
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.loop.stop() def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)Make sure that 'stop' works from everywhere
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.thread_do(self.loop.stop) def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)
<commit_before>""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.loop.stop() def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)<commit_msg>Make sure that 'stop' works from everywhere<commit_after>
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.thread_do(self.loop.stop) def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)
""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.loop.stop() def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)Make sure that 'stop' works from everywhere""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.thread_do(self.loop.stop) def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)
<commit_before>""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.loop.stop() def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)<commit_msg>Make sure that 'stop' works from everywhere<commit_after>""" Very basic implementation of an event loop ========================================== The eventloop is a singleton to schedule and run events. Exports ------- - ``EventLoop``: the basic eventloop """ import asyncio import queue import sched import threading import time from .singleton import Singleton class EventLoop(object, metaclass=Singleton): def __init__(self): self.loop = asyncio.get_event_loop() self.do = self.sync_do def sync_do(self, f, *args, **kwargs): f(*args, **kwargs) def thread_do(self, f, *args, **kwargs): self.loop.call_soon_threadsafe(f, *args, **kwargs) def schedule(self, target, event): self.do(self.loop.call_soon, event) def later(self, delay, event): self.do(self.loop.call_later, delay, event) def run(self): self.do = self.sync_do self.loop.run_forever() def run_once(self): self.stop_later() self.run() def run_in_thread(self): self.do = self.thread_do self.thread = threading.Thread(target=self.loop.run_forever, name='asyncio_event_loop') self.thread.daemon = True self.thread.start() def stop(self): self.thread_do(self.loop.stop) def stop_later(self): self.do = self.sync_do self.schedule(self, self.stop)
39b5f794503149351d03879083d336dfe5f2351b
openprescribing/frontend/tests/test_api_utils.py
openprescribing/frontend/tests/test_api_utils.py
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query)
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) def test_param_to_list(self): from api.view_utils import param_to_list self.assertEquals(param_to_list('foo'), ['foo']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list(None), []) self.assertEquals(param_to_list([]), [])
Add a missing test for param-parsing
Add a missing test for param-parsing
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) Add a missing test for param-parsing
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) def test_param_to_list(self): from api.view_utils import param_to_list self.assertEquals(param_to_list('foo'), ['foo']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list(None), []) self.assertEquals(param_to_list([]), [])
<commit_before>from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) <commit_msg>Add a missing test for param-parsing<commit_after>
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) def test_param_to_list(self): from api.view_utils import param_to_list self.assertEquals(param_to_list('foo'), ['foo']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list(None), []) self.assertEquals(param_to_list([]), [])
from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) Add a missing test for param-parsingfrom django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) def test_param_to_list(self): from api.view_utils import param_to_list self.assertEquals(param_to_list('foo'), ['foo']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list(None), []) self.assertEquals(param_to_list([]), [])
<commit_before>from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) <commit_msg>Add a missing test for param-parsing<commit_after>from django.test import TestCase from django.db import OperationalError class ApiTestUtils(TestCase): def test_db_timeout(self): from api.view_utils import db_timeout @db_timeout(1) def do_long_running_query(): from django.db import connection cursor = connection.cursor() cursor.execute("select pg_sleep(0.01);") self.assertRaises(OperationalError, do_long_running_query) def test_param_to_list(self): from api.view_utils import param_to_list self.assertEquals(param_to_list('foo'), ['foo']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list('foo,bar'), ['foo', 'bar']) self.assertEquals(param_to_list(None), []) self.assertEquals(param_to_list([]), [])
bed98e0769d067857dadf69079dc049d76d65fd0
kitchen/lib/__init__.py
kitchen/lib/__init__.py
import os import json from kitchen.settings import KITCHEN_LOCATION def load_nodes(): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes') for filename in os.listdir(nodes_dir): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close() return retval
Add function to load data from nodes files
Add function to load data from nodes files
Python
apache-2.0
edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen
Add function to load data from nodes files
import os import json from kitchen.settings import KITCHEN_LOCATION def load_nodes(): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes') for filename in os.listdir(nodes_dir): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close() return retval
<commit_before><commit_msg>Add function to load data from nodes files<commit_after>
import os import json from kitchen.settings import KITCHEN_LOCATION def load_nodes(): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes') for filename in os.listdir(nodes_dir): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close() return retval
Add function to load data from nodes filesimport os import json from kitchen.settings import KITCHEN_LOCATION def load_nodes(): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes') for filename in os.listdir(nodes_dir): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close() return retval
<commit_before><commit_msg>Add function to load data from nodes files<commit_after>import os import json from kitchen.settings import KITCHEN_LOCATION def load_nodes(): retval = {} nodes_dir = os.path.join(KITCHEN_LOCATION, 'nodes') for filename in os.listdir(nodes_dir): f = open(os.path.join(nodes_dir, filename), 'r') retval[filename[:-5]] = json.load(f) f.close() return retval
27467c09abe01a6e6a2b66f9f7553bb36cb8a977
uploader/uploader.py
uploader/uploader.py
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz')) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main()
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main()
Sort files before choosing one to upload
Sort files before choosing one to upload
Python
mit
Frogging101/ArchiveBot,emijrp/ArchiveBot,emijrp/ArchiveBot,Frogging101/ArchiveBot,Asparagirl/ArchiveBot,ArchiveTeam/ArchiveBot,JesseWeinstein/ArchiveBot,falconkirtaran/ArchiveBot,emijrp/ArchiveBot,Frogging101/ArchiveBot,JesseWeinstein/ArchiveBot,Asparagirl/ArchiveBot,Frogging101/ArchiveBot,emijrp/ArchiveBot,emijrp/ArchiveBot,JesseWeinstein/ArchiveBot,JesseWeinstein/ArchiveBot,ArchiveTeam/ArchiveBot,falconkirtaran/ArchiveBot,falconkirtaran/ArchiveBot,falconkirtaran/ArchiveBot,Frogging101/ArchiveBot,Asparagirl/ArchiveBot,ArchiveTeam/ArchiveBot,ArchiveTeam/ArchiveBot,Asparagirl/ArchiveBot,Asparagirl/ArchiveBot,falconkirtaran/ArchiveBot,JesseWeinstein/ArchiveBot,ArchiveTeam/ArchiveBot
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz')) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main() Sort files before choosing one to upload
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz')) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main() <commit_msg>Sort files before choosing one to upload<commit_after>
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main()
#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz')) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main() Sort files before choosing one to upload#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main()
<commit_before>#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = list(f for f in os.listdir(directory) if f.endswith('.warc.gz')) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main() <commit_msg>Sort files before choosing one to upload<commit_after>#!/usr/bin/python3 from __future__ import print_function import os import time import subprocess import sys WAIT = 30 def main(): directory = sys.argv[1] url = os.environ['RSYNC_URL'] while True: fnames = sorted(list(f for f in os.listdir(directory) if f.endswith('.warc.gz'))) if len(fnames): fname = os.path.join(directory, fnames[0]) print("Uploading %r" % (fname,)) exit = subprocess.call(["ionice", "-c", "2", "-n", "0", "rsync", "-av", "--timeout=300", "--contimeout=300", "--progress", fname, url]) if exit == 0: print("Removing %r" % (fname,)) os.remove(fname) else: print("Nothing to upload") print("Waiting %d seconds" % (WAIT,)) time.sleep(WAIT) if __name__ == '__main__': main()
d108f090f198cba47083225c0de46e77b22ab5cc
serfclient/__init__.py
serfclient/__init__.py
from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient
from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
Move module level import to top of file (PEP8)
Move module level import to top of file (PEP8) Error: E402 module level import not at top of file
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient Move module level import to top of file (PEP8) Error: E402 module level import not at top of file
from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
<commit_before>from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient <commit_msg>Move module level import to top of file (PEP8) Error: E402 module level import not at top of file<commit_after>
from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient Move module level import to top of file (PEP8) Error: E402 module level import not at top of filefrom pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
<commit_before>from pkg_resources import get_distribution __version__ = get_distribution('serfclient').version from serfclient.client import SerfClient <commit_msg>Move module level import to top of file (PEP8) Error: E402 module level import not at top of file<commit_after>from pkg_resources import get_distribution from serfclient.client import SerfClient __version__ = get_distribution('serfclient').version
b26aaf9bdc80760236d4369f67ea803becc733b7
test_squarespace.py
test_squarespace.py
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.1 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!'
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.2 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!'
Increment the version in the test too
Increment the version in the test too
Python
mit
skullydazed/squarespace-python,skullydazed/squarespace-python
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.1 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!' Increment the version in the test too
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.2 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!'
<commit_before># coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.1 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!' <commit_msg>Increment the version in the test too<commit_after>
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.2 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!'
# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.1 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!' Increment the version in the test too# coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.2 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!'
<commit_before># coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.1 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!' <commit_msg>Increment the version in the test too<commit_after># coding=UTF-8 from squarespace import Squarespace def test_squarespace(): store = Squarespace('test') assert store.api_key == 'test' assert store.useragent == 'Squarespace python API v0.0.2 by Zach White.' def test_squarespace_useragent(): store = Squarespace('test') store.useragent = 'Hello, World!' assert store.useragent == 'Hello, World!' assert store._useragent == 'Hello, World!' assert store.http.headers['User-Agent'] == 'Hello, World!'
375fd952e4495a07cb2031c7d380bdb4a535defc
tests/test_dimension.py
tests/test_dimension.py
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) pprint(fwd_op) print(fwd_op)
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) #pprint(fwd_op) #print(fwd_op)
Change from is_Stepping to is_Derived wherever appropriate
Change from is_Stepping to is_Derived wherever appropriate
Python
mit
opesci/devito,opesci/devito
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) pprint(fwd_op) print(fwd_op) Change from is_Stepping to is_Derived wherever appropriate
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) #pprint(fwd_op) #print(fwd_op)
<commit_before>from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) pprint(fwd_op) print(fwd_op) <commit_msg>Change from is_Stepping to is_Derived wherever appropriate<commit_after>
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) #pprint(fwd_op) #print(fwd_op)
from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) pprint(fwd_op) print(fwd_op) Change from is_Stepping to is_Derived wherever appropriatefrom devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) #pprint(fwd_op) #print(fwd_op)
<commit_before>from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) pprint(fwd_op) print(fwd_op) <commit_msg>Change from is_Stepping to is_Derived wherever appropriate<commit_after>from devito import SubsampledDimension, Grid, TimeFunction, Eq, Operator from devito.tools import pprint def test_subsampled_dimension(): nt = 10 grid = Grid(shape=(11, 11)) x, y = grid.dimensions time = grid.time_dim t = grid.stepping_dim time_subsampled = SubsampledDimension('t_sub', parent=time, factor=4) u = TimeFunction(name='u', grid=grid) u2 = TimeFunction(name='u2', grid=grid, save=nt) assert(t in u.indices) u_s = TimeFunction(name='u_s', grid=grid, time_dim=time_subsampled) assert(time_subsampled in u_s.indices) fwd_eqn = Eq(u.indexed[t+1, x, y], u.indexed[t, x, y] + 1.) fwd_eqn_2 = Eq(u2.indexed[time+1, x, y], u2.indexed[time, x, y] + 1.) save_eqn = Eq(u_s, u) #fwd_op = Operator([fwd_eqn]) fwd_op = Operator([fwd_eqn, fwd_eqn_2, save_eqn]) #pprint(fwd_op) #print(fwd_op)
01a8fcb70ea75d854aaf16547b837d861750c160
tilequeue/queue/file.py
tilequeue/queue/file.py
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
Use readline() instead of next() to detect changes.
Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append something to the queue file and have tilequeue detect the new input without having to restart.
Python
mit
tilezen/tilequeue,mapzen/tilequeue
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close() Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append something to the queue file and have tilequeue detect the new input without having to restart.
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
<commit_before>from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close() <commit_msg>Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append something to the queue file and have tilequeue detect the new input without having to restart.<commit_after>
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close() Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append something to the queue file and have tilequeue detect the new input without having to restart.from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
<commit_before>from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close() <commit_msg>Use readline() instead of next() to detect changes. tilequeue/queue/file.py -`readline()` will pick up new lines appended to the file, whereas `next()` will not since the iterator will just hit `StopIteration` and stop generating new lines. Use `readline()` instead, then, since it might be desirable to append something to the queue file and have tilequeue detect the new input without having to restart.<commit_after>from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
5456ae0af9ad83b8e0339c671ce8954bb48d62cf
database.py
database.py
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base class ImposterBase(object): """ Mixin class to provide additional generic functions for the sqlalchemy models """ def to_dict(obj): """Return dict containing all object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in class_mapper(obj.__class__).mapped_table.c) def get_public_dict(obj): """Return dict containing only public object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in obj.__class__.__public_columns__)
Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models
Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models
Python
bsd-2-clause
jkossen/imposter,jkossen/imposter
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base class ImposterBase(object): """ Mixin class to provide additional generic functions for the sqlalchemy models """ def to_dict(obj): """Return dict containing all object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in class_mapper(obj.__class__).mapped_table.c) def get_public_dict(obj): """Return dict containing only public object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in obj.__class__.__public_columns__)
<commit_before>from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base <commit_msg>Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models<commit_after>
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base class ImposterBase(object): """ Mixin class to provide additional generic functions for the sqlalchemy models """ def to_dict(obj): """Return dict containing all object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in class_mapper(obj.__class__).mapped_table.c) def get_public_dict(obj): """Return dict containing only public object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in obj.__class__.__public_columns__)
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based modelsfrom sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base class ImposterBase(object): """ Mixin class to provide additional generic functions for the sqlalchemy models """ def to_dict(obj): """Return dict containing all object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in class_mapper(obj.__class__).mapped_table.c) def get_public_dict(obj): """Return dict containing only public object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in obj.__class__.__public_columns__)
<commit_before>from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base <commit_msg>Add ImposterBase mixin class so we can add methods and properties to the sqlalchemy based models<commit_after>from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker, class_mapper from sqlalchemy.ext.declarative import declarative_base import config as cfg class DB(object): engine = None db_session = None Base = declarative_base() def __init__(self, dbstring): self.engine = create_engine(dbstring, convert_unicode=True) self.db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=self.engine)) self.Base.query = self.db_session.query_property() def get_session(self): return self.db_session def get_base(self): return self.Base class ImposterBase(object): """ Mixin class to provide additional generic functions for the sqlalchemy models """ def to_dict(obj): """Return dict containing all object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in class_mapper(obj.__class__).mapped_table.c) def get_public_dict(obj): """Return dict containing only public object data""" return dict((col.name, unicode(getattr(obj, col.name))) for col in obj.__class__.__public_columns__)
be1e31c78f17961851d41dea11cd912d237cf5fb
lib/rapidsms/message.py
lib/rapidsms/message.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None self.sent = None self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() self.responses.remove(response) def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
Remove unused attributes; also, empty responses after it's flushed.
Remove unused attributes; also, empty responses after it's flushed.
Python
bsd-3-clause
unicefuganda/edtrac,caktus/rapidsms,eHealthAfrica/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,ken-muturi/rapidsms,ehealthafrica-ci/rapidsms,rapidsms/rapidsms-core-dev,eHealthAfrica/rapidsms,lsgunth/rapidsms,dimagi/rapidsms-core-dev,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,eHealthAfrica/rapidsms,catalpainternational/rapidsms,rapidsms/rapidsms-core-dev,unicefuganda/edtrac,lsgunth/rapidsms,dimagi/rapidsms-core-dev,peterayeni/rapidsms,lsgunth/rapidsms,ken-muturi/rapidsms,ken-muturi/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,unicefuganda/edtrac,caktus/rapidsms,caktus/rapidsms,ehealthafrica-ci/rapidsms,lsgunth/rapidsms
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None self.sent = None self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False Remove unused attributes; also, empty responses after it's flushed.
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() self.responses.remove(response) def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
<commit_before>#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None self.sent = None self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False <commit_msg>Remove unused attributes; also, empty responses after it's flushed.<commit_after>
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() self.responses.remove(response) def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None self.sent = None self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False Remove unused attributes; also, empty responses after it's flushed.#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() self.responses.remove(response) def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
<commit_before>#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text # initialize some empty attributes self.received = None self.sent = None self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False <commit_msg>Remove unused attributes; also, empty responses after it's flushed.<commit_after>#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import copy class Message(object): def __init__(self, backend, caller=None, text=None): self._backend = backend self.caller = caller self.text = text self.responses = [] def __unicode__(self): return self.text @property def backend(self): # backend is read-only, since it's an # immutable property of this object return self._backend def send(self): """Send this message via self.backend, returning True if the message was sent successfully.""" return self.backend.router.outgoing(self) def flush_responses (self): for response in self.responses: response.send() self.responses.remove(response) def respond(self, text): """Send the given text back to the original caller of this message on the same route that it came in on""" if self.caller: response = copy.copy(self) response.text = text self.responses.append(response) return True else: return False
536575db87968014f75d2ad68456c3684d6c92de
auditlog/__manifest__.py
auditlog/__manifest__.py
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', }
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, }
Remove pre_init_hook reference from openerp, no pre_init hook exists any more
auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
Python
agpl-3.0
brain-tec/server-tools,brain-tec/server-tools,bmya/server-tools,brain-tec/server-tools,bmya/server-tools,bmya/server-tools
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, }
<commit_before># -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } <commit_msg>auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more<commit_after>
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, }
# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more# -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, }
<commit_before># -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, 'pre_init_hook': 'pre_init_hook', } <commit_msg>auditlog: Remove pre_init_hook reference from openerp, no pre_init hook exists any more<commit_after># -*- coding: utf-8 -*- # © 2015 ABF OSIELL <http://osiell.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': "Audit Log", 'version': "9.0.1.0.0", 'author': "ABF OSIELL,Odoo Community Association (OCA)", 'license': "AGPL-3", 'website': "http://www.osiell.com", 'category': "Tools", 'depends': [ 'base', ], 'data': [ 'security/ir.model.access.csv', 'data/ir_cron.xml', 'views/auditlog_view.xml', 'views/http_session_view.xml', 'views/http_request_view.xml', ], 'images': [], 'application': True, 'installable': True, }
7f2e91064eabc020cbe660639713278fc187a034
tests/test_result.py
tests/test_result.py
import pytest from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2]
from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2]
Remove unused import of pytest
Remove unused import of pytest
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
import pytest from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2] Remove unused import of pytest
from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2]
<commit_before>import pytest from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2] <commit_msg>Remove unused import of pytest<commit_after>
from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2]
import pytest from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2] Remove unused import of pytestfrom serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2]
<commit_before>import pytest from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2] <commit_msg>Remove unused import of pytest<commit_after>from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'bar')) assert str(r) == \ "SerfResult<head={'a': 1},body=('foo', 'bar')>" def test_can_convert_to_list(self): r = result.SerfResult(head=1, body=2) assert sorted(list(r)) == [1, 2] def test_can_convert_to_tuple(self): r = result.SerfResult(head=1, body=2) assert sorted(tuple(r)) == [1, 2]
a9cd0a385253cef42d03d6a45e81ef4dd582e9de
base/settings/testing.py
base/settings/testing.py
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
Use SQLite in an attempt to speed up the tests.
Use SQLite in an attempt to speed up the tests.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/' Use SQLite in an attempt to speed up the tests.
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
<commit_before># -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/' <commit_msg>Use SQLite in an attempt to speed up the tests.<commit_after>
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/' Use SQLite in an attempt to speed up the tests.# -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
<commit_before># -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'test', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/' <commit_msg>Use SQLite in an attempt to speed up the tests.<commit_after># -*- coding: utf-8 -*- from .base import Base as Settings class Testing(Settings): # Database Configuration. # -------------------------------------------------------------------------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } # django-celery. # -------------------------------------------------------------------------- Settings.INSTALLED_APPS += ['kombu.transport.django', 'djcelery'] BROKER_URL = 'django://' # django-haystack. # -------------------------------------------------------------------------- HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine', }, } # Media Storage Configuration. # -------------------------------------------------------------------------- # Amazon Web Services AWS_STORAGE_BUCKET_NAME = 'test-bucket' # django-s3-folder-storage DEFAULT_S3_PATH = 'media' STATIC_S3_PATH = 'static' CDN_DOMAIN = 'cdn.example.net' MEDIA_URL = 'https://%s/%s/' % (CDN_DOMAIN, DEFAULT_S3_PATH) STATIC_URL = 'https://%s/%s/' % (CDN_DOMAIN, STATIC_S3_PATH) # Authentication Configuration. # -------------------------------------------------------------------------- HELLO_BASE_CLIENT_ID = 'client-id' HELLO_BASE_CLIENT_SECRET = 'client-secret' OAUTH_AUTHORIZATION_URL = 'https://testserver/oauth/authorize/' OAUTH_TOKEN_URL = 'https://testserver/oauth/token/'
211ee03b811cb196dd9f36026fcfc6e75dda2ec6
byceps/config_defaults.py
byceps/config_defaults.py
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) SESSION_COOKIE_SAMESITE = 'Lax' # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
Set session cookie flag `SameSite` to `Lax` (instead of `None`)
Set session cookie flag `SameSite` to `Lax` (instead of `None`)
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin' Set session cookie flag `SameSite` to `Lax` (instead of `None`)
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) SESSION_COOKIE_SAMESITE = 'Lax' # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
<commit_before>""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin' <commit_msg>Set session cookie flag `SameSite` to `Lax` (instead of `None`)<commit_after>
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) SESSION_COOKIE_SAMESITE = 'Lax' # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin' Set session cookie flag `SameSite` to `Lax` (instead of `None`)""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) SESSION_COOKIE_SAMESITE = 'Lax' # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'
<commit_before>""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin' <commit_msg>Set session cookie flag `SameSite` to `Lax` (instead of `None`)<commit_after>""" byceps.config_defaults ~~~~~~~~~~~~~~~~~~~~~~ Default configuration values :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import timedelta from pathlib import Path # database connection SQLALCHEMY_ECHO = False # Avoid connection errors after database becomes temporarily # unreachable, then becomes reachable again. SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True} # Disable Flask-SQLAlchemy's tracking of object modifications. SQLALCHEMY_TRACK_MODIFICATIONS = False # job queue JOBS_ASYNC = True # metrics METRICS_ENABLED = False # RQ dashboard (for job queue) RQ_DASHBOARD_ENABLED = False RQ_DASHBOARD_POLL_INTERVAL = 2500 RQ_DASHBOARD_WEB_BACKGROUND = 'white' # login sessions PERMANENT_SESSION_LIFETIME = timedelta(14) SESSION_COOKIE_SAMESITE = 'Lax' # localization LOCALE = 'de_DE.UTF-8' LOCALES_FORMS = ['de'] TIMEZONE = 'Europe/Berlin' BABEL_DEFAULT_LOCALE = LOCALE BABEL_DEFAULT_TIMEZONE = TIMEZONE # static content files path PATH_DATA = Path('./data') # home page ROOT_REDIRECT_TARGET = None # shop SHOP_ORDER_EXPORT_TIMEZONE = 'Europe/Berlin'