commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
|---|---|---|---|---|---|---|---|---|---|---|
6af31da53a43bcd2e45ea4242892a4831b2fb2f8
|
asyncio_irc/listeners.py
|
asyncio_irc/listeners.py
|
class Listener:
"""Always invokes the handler."""
def __init__(self, handler):
self.handler = handler
def handle(self, connection, message):
self.handler(connection, message=message)
class CommandListener(Listener):
"""Only invokes the handler on one particular command."""
def __init__(self, command, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command.value
def handle(self, connection, message):
if message.command == self.command:
super().handle(connection, message)
class WhitelistListener(Listener):
"""Invokes the handler for a whitelist of commands."""
def __init__(self, whitelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.whitelist = [command.value for command in whitelist]
def handle(self, connection, message):
if message.command in self.whitelist:
super().handle(connection, message)
class BlacklistListener(Listener):
"""Invokes the handler for all but a blacklist of commands."""
def __init__(self, blacklist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blacklist = [command.value for command in blacklist]
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
# class RegexListener(Listener):
# def __init__(self, regex, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self.regex = regex
|
class Listener:
"""Always invokes the handler."""
def __init__(self, handler):
self.handler = handler
def handle(self, connection, message):
self.handler(connection, message=message)
class CommandListener(Listener):
"""Only invokes the handler on one particular command."""
def __init__(self, command, *args, **kwargs):
super().__init__(*args, **kwargs)
self.command = command.value
def handle(self, connection, message):
if message.command == self.command:
super().handle(connection, message)
class WhitelistListener(Listener):
"""Invokes the handler for a whitelist of commands."""
def __init__(self, whitelist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.whitelist = [command.value for command in whitelist]
def handle(self, connection, message):
if message.command in self.whitelist:
super().handle(connection, message)
class BlacklistListener(Listener):
"""Invokes the handler for all but a blacklist of commands."""
def __init__(self, blacklist, *args, **kwargs):
super().__init__(*args, **kwargs)
self.blacklist = [command.value for command in blacklist]
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
|
Remove commented code for the mo
|
Remove commented code for the mo
|
Python
|
bsd-2-clause
|
meshy/framewirc
|
---
+++
@@ -38,9 +38,3 @@
def handle(self, connection, message):
if message.command not in self.blacklist:
super().handle(connection, message)
-
-
-# class RegexListener(Listener):
-# def __init__(self, regex, *args, **kwargs):
-# super().__init__(*args, **kwargs)
-# self.regex = regex
|
b6927cadb72e0a73700416d0218a569c15ec8818
|
generative/tests/compare_test/concat_first/run.py
|
generative/tests/compare_test/concat_first/run.py
|
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import subprocess
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('layer', type=str, help='fc6|conv42|pool1')
parser.add_argument('--cuda-device', type=int, default=0, help='0|1|2|3 [default: 0]')
args = parser.parse_args()
for i in xrange(5):
out_dir = './trained_models/%s/%d' % (args.layer, i + 1)
train_test_split_dir = './train_test_split/%d' % (i + 1)
command = 'CUDA_VISIBLE_DEVICES={device} python train_average.py {layer} --train-test-split-dir {split_dir} --out-dir {out_dir} --cuda'.format(
device=args.cuda_device, layer=args.layer, split_dir=train_test_split_dir, out_dir=out_dir)
subprocess.call(command, shell=True)
|
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import subprocess
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('layer', type=str, help='fc6|conv42|pool1')
parser.add_argument('--cuda-device', type=int, default=0, help='0|1|2|3 [default: 0]')
args = parser.parse_args()
for i in xrange(5):
out_dir = '/mnt/visual_communication_dataset/trained_models_5_30_18/%s/%d' % (args.layer, i + 1)
train_test_split_dir = './train_test_split/%d' % (i + 1)
command = 'CUDA_VISIBLE_DEVICES={device} python train_average.py {layer} --train-test-split-dir {split_dir} --out-dir {out_dir} --cuda'.format(
device=args.cuda_device, layer=args.layer, split_dir=train_test_split_dir, out_dir=out_dir)
subprocess.call(command, shell=True)
|
Update path to save to mnt dir
|
Update path to save to mnt dir
|
Python
|
mit
|
judithfan/pix2svg
|
---
+++
@@ -12,7 +12,7 @@
args = parser.parse_args()
for i in xrange(5):
- out_dir = './trained_models/%s/%d' % (args.layer, i + 1)
+ out_dir = '/mnt/visual_communication_dataset/trained_models_5_30_18/%s/%d' % (args.layer, i + 1)
train_test_split_dir = './train_test_split/%d' % (i + 1)
command = 'CUDA_VISIBLE_DEVICES={device} python train_average.py {layer} --train-test-split-dir {split_dir} --out-dir {out_dir} --cuda'.format(
device=args.cuda_device, layer=args.layer, split_dir=train_test_split_dir, out_dir=out_dir)
|
fd9d1b604e94b27b502413fe84848a6998e37318
|
opentreemap/registration_backend/urls.py
|
opentreemap/registration_backend/urls.py
|
from django.conf.urls import include
from django.conf.urls import url
from django.contrib.auth.views import login
from django.views.generic.base import TemplateView
from views import (RegistrationView, ActivationView, LoginForm,
PasswordResetView)
urlpatterns = [
url(r'^login/?$', login, {'authentication_form': LoginForm}, name='login'),
url(r'^activation-complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
url(r'password/reset/$', PasswordResetView.as_view(),
name='auth_password_reset'),
url(r'', include('registration.auth_urls')),
]
|
from django.conf.urls import include
from django.conf.urls import url
from django.contrib.auth.views import login
from django.views.generic.base import TemplateView
from views import (RegistrationView, ActivationView, LoginForm,
PasswordResetView)
urlpatterns = [
url(r'^login/$', login, {'authentication_form': LoginForm}, name='login'),
url(r'^activation-complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
# Activation keys get matched by \w+ instead of the more specific
# [a-fA-F0-9]{40} because a bad activation key should still get
# to the view; that way it can return a sensible "invalid key"
# message instead of a confusing 404.
url(r'^activate/(?P<activation_key>\w+)/$',
ActivationView.as_view(),
name='registration_activate'),
url(r'^register/$',
RegistrationView.as_view(),
name='registration_register'),
url(r'^register/complete/$',
TemplateView.as_view(template_name='registration/registration_complete.html'), # NOQA
name='registration_complete'),
url(r'^register/closed/$',
TemplateView.as_view(template_name='registration/registration_closed.html'), # NOQA
name='registration_disallowed'),
url(r'password/reset/$', PasswordResetView.as_view(),
name='auth_password_reset'),
url(r'', include('registration.auth_urls')),
]
|
Make trailing slash on login view non-optional
|
Make trailing slash on login view non-optional
This was causing the UI tests to fail
|
Python
|
agpl-3.0
|
maurizi/otm-core,maurizi/otm-core,maurizi/otm-core,maurizi/otm-core
|
---
+++
@@ -9,7 +9,7 @@
urlpatterns = [
- url(r'^login/?$', login, {'authentication_form': LoginForm}, name='login'),
+ url(r'^login/$', login, {'authentication_form': LoginForm}, name='login'),
url(r'^activation-complete/$',
TemplateView.as_view(template_name='registration/activation_complete.html'), # NOQA
name='registration_activation_complete'),
|
fe2dbf3d0008c344f1ef1ba3895c2cbb6b07209a
|
instance/config.py
|
instance/config.py
|
import os
class MainConfig(object):
DEBUG = False
WTF_CSRF_ENABLED = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
# Will generate a random secret key with a sequence of random chaarcters
SECRET_KEY = os.urandom(24)
class DevelopmentEnviron(MainConfig):
DEBUG = True
TESTING = True
# URI to our development database
SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/bucketlist_db'
class TestingConfig(MainConfig):
TESTING = True
DEBUG = True
# URI to our testing database
SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/test_db'
class ProductionConfig(MainConfig):
DEBUG = False
TESTING = False
# Dictionary with keys mapping to the different configuration environments
app_config = {
'MainConfig': MainConfig,
'DevelopmentEnviron': DevelopmentEnviron,
'TestingConfig': TestingConfig,
'ProductionConfig': ProductionConfig
}
|
import os
class MainConfig(object):
DEBUG = False
WTF_CSRF_ENABLED = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
class DevelopmentEnviron(MainConfig):
DEBUG = True
TESTING = True
# URI to our development database
SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/bucketlist_db'
class TestingConfig(MainConfig):
TESTING = True
DEBUG = True
# URI to our testing database
SQLALCHEMY_DATABASE_URI = 'postgresql://@localhost/test_db'
class ProductionConfig(MainConfig):
DEBUG = False
TESTING = False
# Dictionary with keys mapping to the different configuration environments
app_config = {
'MainConfig': MainConfig,
'DevelopmentEnviron': DevelopmentEnviron,
'TestingConfig': TestingConfig,
'ProductionConfig': ProductionConfig
}
|
Add secret key to env viarables
|
Add secret key to env viarables
|
Python
|
mit
|
paulupendo/CP-2-Bucketlist-Application
|
---
+++
@@ -5,8 +5,7 @@
DEBUG = False
WTF_CSRF_ENABLED = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
- # Will generate a random secret key with a sequence of random chaarcters
- SECRET_KEY = os.urandom(24)
+ SECRET_KEY = os.getenv('SECRET_KEY')
class DevelopmentEnviron(MainConfig):
|
83b8f44a3d978a120b8a1b8346ecdd54fdd068fd
|
correctiv_justizgelder/urls.py
|
correctiv_justizgelder/urls.py
|
from functools import wraps
from django.conf.urls import patterns, url
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.cache import cache_page
from .views import OrganisationSearchView, OrganisationDetail
CACHE_TIME = 15 * 60
def c(view):
@wraps(view)
def cache_page_anonymous(request, *args, **kwargs):
if request.user.is_authenticated():
return view(request, *args, **kwargs)
return cache_page(CACHE_TIME)(view)(request, *args, **kwargs)
return cache_page_anonymous
urlpatterns = patterns('',
url(r'^$', c(OrganisationSearchView.as_view()), name='search'),
url(_(r'^recipient/(?P<slug>[\w-]+)/$'),
c(OrganisationDetail.as_view()),
name='organisation_detail'),
)
|
from functools import wraps
from django.conf.urls import patterns, url
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.cache import cache_page
from .views import OrganisationSearchView, OrganisationDetail
CACHE_TIME = 15 * 60
def c(view):
@wraps(view)
def cache_page_anonymous(request, *args, **kwargs):
if request.user.is_authenticated():
return view(request, *args, **kwargs)
return cache_page(CACHE_TIME)(view)(request, *args, **kwargs)
return cache_page_anonymous
urlpatterns = patterns('',
url(r'^$', c(OrganisationSearchView.as_view()), name='search'),
url(_(r'^recipient/(?P<slug>[\w\~\-]+)/$'),
c(OrganisationDetail.as_view()),
name='organisation_detail'),
)
|
Add tilde to url lookup for recipient slugs
|
Add tilde to url lookup for recipient slugs
|
Python
|
mit
|
correctiv/correctiv-justizgelder,correctiv/correctiv-justizgelder
|
---
+++
@@ -20,7 +20,7 @@
urlpatterns = patterns('',
url(r'^$', c(OrganisationSearchView.as_view()), name='search'),
- url(_(r'^recipient/(?P<slug>[\w-]+)/$'),
+ url(_(r'^recipient/(?P<slug>[\w\~\-]+)/$'),
c(OrganisationDetail.as_view()),
name='organisation_detail'),
)
|
d3489d51621fc001d0700f5a8562e53d82b52cac
|
tests/test_cyclus.py
|
tests/test_cyclus.py
|
#! /usr/bin/env python
import os
from testcases import sim_files
from cyclus_tools import run_cyclus, db_comparator
"""Tests"""
def test_cyclus():
"""Test for all inputs in sim_files. Checks if reference and current cyclus
output is the same.
WARNING: the tests require cyclus executable to be included in PATH
"""
cwd = os.getcwd()
for sim_input,bench_db in sim_files:
temp_output = [(sim_input, "./output_temp.h5")]
yield run_cyclus, "cyclus", cwd, temp_output
yield db_comparator, bench_db, "./output_temp.h5"
os.remove("./output_temp.h5")
|
#! /usr/bin/env python
import os
from testcases import sim_files
from cyclus_tools import run_cyclus, db_comparator
"""Tests"""
def test_cyclus():
"""Test for all inputs in sim_files. Checks if reference and current cyclus
output is the same.
WARNING: the tests require cyclus executable to be included in PATH
"""
cwd = os.getcwd()
for sim_input,bench_db in sim_files:
temp_output = [(sim_input, "./output_temp.h5")]
yield run_cyclus, "cyclus", cwd, temp_output
yield db_comparator, bench_db, "./output_temp.h5"
if os.path.isfile("./output_temp.h5):
os.remove("./output_temp.h5")
|
Remove output_temp.h5 only if it exists
|
Remove output_temp.h5 only if it exists
|
Python
|
bsd-3-clause
|
Baaaaam/cyCLASS,gonuke/cycamore,Baaaaam/cyBaM,cyclus/cycaless,rwcarlsen/cycamore,jlittell/cycamore,jlittell/cycamore,rwcarlsen/cycamore,gonuke/cycamore,cyclus/cycaless,Baaaaam/cycamore,Baaaaam/cyCLASS,Baaaaam/cyBaM,rwcarlsen/cycamore,gonuke/cycamore,jlittell/cycamore,Baaaaam/cycamore,Baaaaam/cycamore,Baaaaam/cyBaM,Baaaaam/cyBaM,gonuke/cycamore,rwcarlsen/cycamore,jlittell/cycamore
|
---
+++
@@ -13,7 +13,7 @@
WARNING: the tests require cyclus executable to be included in PATH
"""
cwd = os.getcwd()
-
+
for sim_input,bench_db in sim_files:
temp_output = [(sim_input, "./output_temp.h5")]
@@ -21,4 +21,5 @@
yield db_comparator, bench_db, "./output_temp.h5"
- os.remove("./output_temp.h5")
+ if os.path.isfile("./output_temp.h5):
+ os.remove("./output_temp.h5")
|
21e2db0e2c3873e6390eee1865c67ee4c73ba498
|
tests/test_cyprep.py
|
tests/test_cyprep.py
|
import numpy as np
import pytest
import yatsm._cyprep as cyprep
def test_get_valid_mask():
n_bands, n_images, n_mask = 8, 500, 50
data = np.random.randint(0, 10000,
size=(n_bands, n_images)).astype(np.int32)
# Add in bad data
_idx = np.arange(0, n_images)
for b in range(n_bands):
idx = np.random.choice(_idx, size=n_mask, replace=False)
data[b, idx] = 16000
mins = np.repeat(0, n_bands).astype(np.int16)
maxes = np.repeat(10000, n_bands).astype(np.int16)
truth = np.all([((b > _min) & (b < _max)) for b, _min, _max in
zip(np.rollaxis(data, 0), mins, maxes)], axis=0)
np.testing.assert_equal(truth, cyprep.get_valid_mask(data, mins, maxes))
|
import numpy as np
import pytest
import yatsm._cyprep as cyprep
def test_get_valid_mask():
n_bands, n_images, n_mask = 8, 500, 50
data = np.random.randint(0, 10000,
size=(n_bands, n_images)).astype(np.int32)
# Add in bad data
_idx = np.arange(0, n_images)
for b in range(n_bands):
idx = np.random.choice(_idx, size=n_mask, replace=False)
data[b, idx] = 16000
mins = np.repeat(0, n_bands).astype(np.int16)
maxes = np.repeat(10000, n_bands).astype(np.int16)
truth = np.all([((b >= _min) & (b <= _max)) for b, _min, _max in
zip(data, mins, maxes)], axis=0)
test = cyprep.get_valid_mask(data, mins, maxes).astype(np.bool)
test_min = data[:, test].min(axis=1)
test_max = data[:, test].max(axis=1)
assert np.array_equal(truth, test)
assert np.array_equal(data[:, truth].min(axis=1), test_min)
assert np.array_equal(data[:, truth].max(axis=1), test_max)
assert np.all(test_min >= mins)
assert np.all(test_max <= maxes)
|
Fix bool logic in mask test & add test criteria
|
Fix bool logic in mask test & add test criteria
|
Python
|
mit
|
c11/yatsm,ceholden/yatsm,valpasq/yatsm,valpasq/yatsm,c11/yatsm,ceholden/yatsm
|
---
+++
@@ -16,7 +16,15 @@
mins = np.repeat(0, n_bands).astype(np.int16)
maxes = np.repeat(10000, n_bands).astype(np.int16)
- truth = np.all([((b > _min) & (b < _max)) for b, _min, _max in
- zip(np.rollaxis(data, 0), mins, maxes)], axis=0)
+ truth = np.all([((b >= _min) & (b <= _max)) for b, _min, _max in
+ zip(data, mins, maxes)], axis=0)
+ test = cyprep.get_valid_mask(data, mins, maxes).astype(np.bool)
- np.testing.assert_equal(truth, cyprep.get_valid_mask(data, mins, maxes))
+ test_min = data[:, test].min(axis=1)
+ test_max = data[:, test].max(axis=1)
+
+ assert np.array_equal(truth, test)
+ assert np.array_equal(data[:, truth].min(axis=1), test_min)
+ assert np.array_equal(data[:, truth].max(axis=1), test_max)
+ assert np.all(test_min >= mins)
+ assert np.all(test_max <= maxes)
|
40edd2d679bcaebcbdb55b08fdd38b4c1af68672
|
tests/test_models.py
|
tests/test_models.py
|
#! /usr/bin/env python
import os
import pytest
from pymt import models
@pytest.mark.parametrize("cls", models.__all__)
def test_model_setup(cls):
model = models.__dict__[cls]()
args = model.setup()
assert os.path.isfile(os.path.join(args[1], args[0]))
@pytest.mark.parametrize("cls", models.__all__)
def test_model_initialize(cls):
model = models.__dict__[cls]()
args = model.setup()
model.initialize(*args)
assert model.initdir == args[1]
assert model._initialized
@pytest.mark.parametrize("cls", models.__all__)
def test_model_irf(cls):
model = models.__dict__[cls]()
model.initialize(*model.setup())
model.update()
assert model.get_current_time() > model.get_start_time()
model.finalize()
|
#! /usr/bin/env python
import os
import pytest
from pymt import models
@pytest.mark.parametrize("cls", models.__all__)
def test_model_setup(cls):
model = models.__dict__[cls]()
args = model.setup()
assert os.path.isfile(os.path.join(args[1], args[0]))
@pytest.mark.parametrize("cls", models.__all__)
def test_model_initialize(cls):
model = models.__dict__[cls]()
args = model.setup()
model.initialize(*args)
assert model.initdir == args[1]
assert model._initialized
@pytest.mark.parametrize("cls", models.__all__)
def test_model_update(cls):
model = models.__dict__[cls]()
model.initialize(*model.setup())
model.update()
assert model.get_current_time() > model.get_start_time()
@pytest.mark.parametrize("cls", models.__all__)
def test_model_finalize(cls):
model = models.__dict__[cls]()
model.initialize(*model.setup())
model.finalize()
|
Add test for finalize method.
|
Add test for finalize method.
|
Python
|
mit
|
csdms/coupling,csdms/pymt,csdms/coupling
|
---
+++
@@ -24,9 +24,15 @@
@pytest.mark.parametrize("cls", models.__all__)
-def test_model_irf(cls):
+def test_model_update(cls):
model = models.__dict__[cls]()
model.initialize(*model.setup())
model.update()
assert model.get_current_time() > model.get_start_time()
+
+
+@pytest.mark.parametrize("cls", models.__all__)
+def test_model_finalize(cls):
+ model = models.__dict__[cls]()
+ model.initialize(*model.setup())
model.finalize()
|
d0d7c1f29ca17d3273033821a8ed1326b0ec7b4c
|
wmata.py
|
wmata.py
|
import datetime
import urllib
import json
class WmataError(Exception):
pass
class Wmata(object):
api_url = 'http://api.wmata.com/%(svc)s.svc/json/%(endpoint)s'
# By default, we'll use the WMATA demonstration key
def __init__(self, api_key='kfgpmgvfgacx98de9q3xazww'):
if api_key is not None:
self.api_key = api_key
|
import datetime
import urllib
import json
class WmataError(Exception):
pass
class Wmata(object):
api_url = 'http://api.wmata.com/%(svc)s.svc/json/%(endpoint)s'
# By default, we'll use the WMATA demonstration key
def __init__(self, api_key='kfgpmgvfgacx98de9q3xazww'):
self.api_key = api_key
|
Remove old default api_key logic in __init__.
|
Remove old default api_key logic in __init__.
|
Python
|
mit
|
ExperimentMonty/py3-wmata
|
---
+++
@@ -11,5 +11,4 @@
# By default, we'll use the WMATA demonstration key
def __init__(self, api_key='kfgpmgvfgacx98de9q3xazww'):
- if api_key is not None:
- self.api_key = api_key
+ self.api_key = api_key
|
b9f302f38e07b32590fc4008f413a5baa756dbee
|
zou/app/resources/source/csv/assets.py
|
zou/app/resources/source/csv/assets.py
|
from zou.app.resources.source.csv.base import BaseCsvImportResource
from zou.app.project import project_info, asset_info
from zou.app.models.entity import Entity
from sqlalchemy.exc import IntegrityError
class AssetsCsvImportResource(BaseCsvImportResource):
def prepare_import(self):
self.projects = {}
self.entity_types = {}
def import_row(self, row):
name = row["Name"]
project_name = row["Project"]
entity_type_name = row["Category"]
description = row["Description"]
self.add_to_cache_if_absent(
self.projects,
project_info.get_or_create,
project_name
)
project_id = self.get_id_from_cache(self.projects, project_name)
self.add_to_cache_if_absent(
self.entity_types,
asset_info.get_or_create_type,
entity_type_name
)
entity_type_id = self.get_id_from_cache(
self.entity_types,
entity_type_name
)
try:
entity = Entity.create(
name=name,
description=description,
project_id=project_id,
entity_type_id=entity_type_id
)
except IntegrityError:
entity = Entity.get_by(
name=name,
project_id=project_id,
entity_type_id=entity_type_id
)
return entity
|
from zou.app.resources.source.csv.base import BaseCsvImportResource
from zou.app.project import project_info, asset_info
from zou.app.models.entity import Entity
from sqlalchemy.exc import IntegrityError
class AssetsCsvImportResource(BaseCsvImportResource):
def prepare_import(self):
self.projects = {}
self.entity_types = {}
def import_row(self, row):
name = row["Name"]
project_name = row["Project"]
entity_type_name = row["Category"]
description = row["Description"]
self.add_to_cache_if_absent(
self.projects,
project_info.get_or_create,
project_name
)
project_id = self.get_id_from_cache(self.projects, project_name)
self.add_to_cache_if_absent(
self.entity_types,
asset_info.get_or_create_type,
entity_type_name
)
entity_type_id = self.get_id_from_cache(
self.entity_types,
entity_type_name
)
try:
entity = Entity.get_by(
name=name,
project_id=project_id,
entity_type_id=entity_type_id
)
if entity is None:
entity = Entity.create(
name=name,
description=description,
project_id=project_id,
entity_type_id=entity_type_id
)
except IntegrityError:
pass
return entity
|
Fix duplicates in asset import
|
Fix duplicates in asset import
It relied on the unique constraint from the database, but it doesn't apply if
parent_id is null. So it checks the existence of the asset before inserting it.
|
Python
|
agpl-3.0
|
cgwire/zou
|
---
+++
@@ -36,17 +36,20 @@
)
try:
- entity = Entity.create(
- name=name,
- description=description,
- project_id=project_id,
- entity_type_id=entity_type_id
- )
- except IntegrityError:
entity = Entity.get_by(
name=name,
project_id=project_id,
entity_type_id=entity_type_id
)
+ if entity is None:
+ entity = Entity.create(
+ name=name,
+ description=description,
+ project_id=project_id,
+ entity_type_id=entity_type_id
+ )
+ except IntegrityError:
+ pass
+
return entity
|
9ebc81565171866462dae5eb068bb7c1d98948a7
|
ovp_users/serializers/__init__.py
|
ovp_users/serializers/__init__.py
|
from ovp_users.serializers.user import UserCreateSerializer
from ovp_users.serializers.user import UserUpdateSerializer
from ovp_users.serializers.user import CurrentUserSerializer
from ovp_users.serializers.user import UserPublicRetrieveSerializer
from ovp_users.serializers.user import UserProjectRetrieveSerializer
from ovp_users.serializers.user import UserApplyRetrieveSerializer
from ovp_users.serializers.password_recovery import RecoveryTokenSerializer
from ovp_users.serializers.password_recovery import RecoverPasswordSerializer
from ovp_users.serializers.profile import ProfileCreateUpdateSerializer
from ovp_users.serializers.profile import ProfileRetrieveSerializer
|
from ovp_users.serializers.user import UserCreateSerializer
from ovp_users.serializers.user import UserUpdateSerializer
from ovp_users.serializers.user import CurrentUserSerializer
from ovp_users.serializers.user import ShortUserPublicRetrieveSerializer
from ovp_users.serializers.user import LongUserPublicRetrieveSerializer
from ovp_users.serializers.user import UserProjectRetrieveSerializer
from ovp_users.serializers.user import UserApplyRetrieveSerializer
from ovp_users.serializers.password_recovery import RecoveryTokenSerializer
from ovp_users.serializers.password_recovery import RecoverPasswordSerializer
from ovp_users.serializers.profile import ProfileCreateUpdateSerializer
from ovp_users.serializers.profile import ProfileRetrieveSerializer
|
Add ShortUserRetrieve and LongUserRetrieve serializers
|
Add ShortUserRetrieve and LongUserRetrieve serializers
|
Python
|
agpl-3.0
|
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
|
---
+++
@@ -1,7 +1,8 @@
from ovp_users.serializers.user import UserCreateSerializer
from ovp_users.serializers.user import UserUpdateSerializer
from ovp_users.serializers.user import CurrentUserSerializer
-from ovp_users.serializers.user import UserPublicRetrieveSerializer
+from ovp_users.serializers.user import ShortUserPublicRetrieveSerializer
+from ovp_users.serializers.user import LongUserPublicRetrieveSerializer
from ovp_users.serializers.user import UserProjectRetrieveSerializer
from ovp_users.serializers.user import UserApplyRetrieveSerializer
|
b85a713f883caaf29f39daff1e0c3d3d0896969f
|
primestg/message.py
|
primestg/message.py
|
from lxml.objectify import fromstring
class BaseMessage(object):
"""
Base XML message.
"""
def __init__(self, xml):
"""
Create an object of BaseMessage.
:param xml: a file object or a string with the XML
:return: an instance of BaseMessage
"""
self.objectified = xml
@property
def objectified(self):
"""
The XML objectified
:return: the XML objectified
"""
return self._objectifyed
@objectified.setter
def objectified(self, value):
"""
Objectify an XML
:param value: a file object or string with the XML
"""
if isinstance(value, file):
value = value.read()
self._xml = value
self._objectifyed = fromstring(self._xml)
class MessageS(BaseMessage):
"""
Message class for reports.
"""
pass
|
from lxml.objectify import fromstring
class BaseMessage(object):
"""
Base XML message.
"""
def __init__(self, xml):
"""
Create an object of BaseMessage.
:param xml: a file object or a string with the XML
:return: an instance of BaseMessage
"""
self.objectified = xml
@property
def objectified(self):
"""
The XML objectified
:return: the XML objectified
"""
return self._objectified
@objectified.setter
def objectified(self, value):
"""
Objectify an XML
:param value: a file object or string with the XML
"""
if isinstance(value, file):
value = value.read()
self._xml = value
self._objectified = fromstring(self._xml)
class MessageS(BaseMessage):
"""
Message class for reports.
"""
pass
|
Fix typo in objectified name
|
Fix typo in objectified name
|
Python
|
agpl-3.0
|
gisce/primestg
|
---
+++
@@ -21,7 +21,7 @@
:return: the XML objectified
"""
- return self._objectifyed
+ return self._objectified
@objectified.setter
def objectified(self, value):
@@ -34,7 +34,7 @@
if isinstance(value, file):
value = value.read()
self._xml = value
- self._objectifyed = fromstring(self._xml)
+ self._objectified = fromstring(self._xml)
class MessageS(BaseMessage):
|
2a7eecbf55f5cc00bed76a70990946309baa2baa
|
boardinghouse/tests/test_sql.py
|
boardinghouse/tests/test_sql.py
|
"""
Tests for the RAW sql functions.
"""
from django.conf import settings
from django.test import TestCase
from django.db.models import connection
from boardinghouse.models import Schema
class TestRejectSchemaColumnChange(TestCase):
def test_exception_is_raised(self):
Schema.objects.mass_create('a')
cursor = connection.cursor()
UPDATE = "UPDATE boardinghouse_schema SET schema='foo' WHERE schema='a'"
self.assertRaises(Exception, cursor.execute, UPDATE)
|
"""
Tests for the RAW sql functions.
"""
from django.conf import settings
from django.test import TestCase
from django.db import connection
from boardinghouse.models import Schema
class TestRejectSchemaColumnChange(TestCase):
def test_exception_is_raised(self):
Schema.objects.mass_create('a')
cursor = connection.cursor()
UPDATE = "UPDATE boardinghouse_schema SET schema='foo' WHERE schema='a'"
self.assertRaises(Exception, cursor.execute, UPDATE)
|
Make test work with 1.7
|
Make test work with 1.7
|
Python
|
bsd-3-clause
|
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
|
---
+++
@@ -4,7 +4,7 @@
from django.conf import settings
from django.test import TestCase
-from django.db.models import connection
+from django.db import connection
from boardinghouse.models import Schema
@@ -13,4 +13,4 @@
Schema.objects.mass_create('a')
cursor = connection.cursor()
UPDATE = "UPDATE boardinghouse_schema SET schema='foo' WHERE schema='a'"
- self.assertRaises(Exception, cursor.execute, UPDATE)
+ self.assertRaises(Exception, cursor.execute, UPDATE)
|
32efe6c239a62c2f011179c4431adf6e028442f0
|
alg_selection_sort.py
|
alg_selection_sort.py
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(a_list):
"""Selection Sort algortihm.
Procedure:
- Find out the max item's original slot first,
- then swap it and the item at the max slot.
- Iterate the procedure for the next max, etc.
Time complexity: O(n^2).
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
a_list[select_slot], a_list[max_slot] = (
a_list[max_slot], a_list[select_slot])
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def selection_sort(a_list):
"""Selection Sort algortihm.
Time complexity: O(n^2).
"""
for max_slot in reversed(range(len(a_list))):
select_slot = 0
for slot in range(1, max_slot + 1):
if a_list[slot] > a_list[select_slot]:
select_slot = slot
a_list[select_slot], a_list[max_slot] = (
a_list[max_slot], a_list[select_slot])
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By selection sort: ')
selection_sort(a_list)
print(a_list)
if __name__ == '__main__':
main()
|
Add to doc string: time complexity
|
Add to doc string: time complexity
|
Python
|
bsd-2-clause
|
bowen0701/algorithms_data_structures
|
---
+++
@@ -5,11 +5,6 @@
def selection_sort(a_list):
"""Selection Sort algortihm.
-
- Procedure:
- - Find out the max item's original slot first,
- - then swap it and the item at the max slot.
- - Iterate the procedure for the next max, etc.
Time complexity: O(n^2).
"""
|
f828523180e8996e17ecb36e4a39c67656a372a3
|
launch_instance.py
|
launch_instance.py
|
# License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
'''
'''
if not isinstance(security_groups, list):
security_groups = [security_groups]
ec2 = boto.ec2.connect_to_region(region)
reserve = ec2.run_instances(image_id, key_name=key_name,
instance_type=instance_type,
security_groups=security_groups,
user_data=user_data)
inst = reserve.instances[0]
while inst.state == u'pending':
time.sleep(10)
inst.update()
# Wait for the status checks first
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
if initial_check:
check_stat = "Status:initializing"
while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
time.sleep(10)
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
return inst
# ec2.get_instance_attribute('i-336b69f6', 'instanceType')
|
# License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name=None, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
'''
'''
if not isinstance(security_groups, list):
security_groups = [security_groups]
ec2 = boto.ec2.connect_to_region(region)
reserve = ec2.run_instances(image_id, key_name=key_name,
instance_type=instance_type,
security_groups=security_groups,
user_data=user_data)
inst = reserve.instances[0]
while inst.state == u'pending':
time.sleep(10)
inst.update()
if initial_check:
# Wait for the status checks first
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
check_stat = "Status:initializing"
while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
time.sleep(10)
status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
return inst
# ec2.get_instance_attribute('i-336b69f6', 'instanceType')
|
Move status into initial check; fails when instance is stopped already
|
Move status into initial check; fails when instance is stopped already
|
Python
|
mit
|
Astroua/aws_controller,Astroua/aws_controller
|
---
+++
@@ -27,10 +27,10 @@
time.sleep(10)
inst.update()
- # Wait for the status checks first
- status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
+ if initial_check:
+ # Wait for the status checks first
+ status = ec2.get_all_instance_status(instance_ids=[inst.id])[0]
- if initial_check:
check_stat = "Status:initializing"
while str(status.system_status) == check_stat and str(status.instance_status) == check_stat:
|
5bf2f25cb309f38bc7a48d76c2018768117a456a
|
alg_tower_of_hanoi.py
|
alg_tower_of_hanoi.py
|
"""The tower of Hanoi."""
from __future__ import print_function
def move_towers(height, from_pole, to_pole, with_pole):
if height == 1:
print('Moving disk from {0} to {1}'.format(from_pole, to_pole))
else:
move_towers(height - 1, from_pole, with_pole, to_pole)
move_towers(1, from_pole, to_pole, with_pole)
move_towers(height - 1, with_pole, to_pole, from_pole)
def main():
from_pole = 'f'
to_pole = 't'
with_pole = 'w'
height = 1
print('height: {}'.format(height))
move_towers(height, from_pole, to_pole, with_pole)
height = 2
print('height: {}'.format(height))
move_towers(height, from_pole, to_pole, with_pole)
height = 5
print('height: {}'.format(height))
move_towers(height, from_pole, to_pole, with_pole)
if __name__ == '__main__':
main()
|
"""The tower of Hanoi."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def tower_of_hanoi(height, from_pole, to_pole, with_pole, counter):
if height == 1:
counter[0] += 1
print('{0} -> {1}'.format(from_pole, to_pole))
else:
tower_of_hanoi(height - 1, from_pole, with_pole, to_pole, counter)
tower_of_hanoi(1, from_pole, to_pole, with_pole, counter)
tower_of_hanoi(height - 1, with_pole, to_pole, from_pole, counter)
def main():
from_pole = 'A'
to_pole = 'B'
with_pole = 'C'
height = 1
counter = [0]
print('height: {}'.format(height))
tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
print('counter: {}'.format(counter[0]))
height = 2
counter = [0]
print('height: {}'.format(height))
tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
print('counter: {}'.format(counter[0]))
height = 5
counter = [0]
print('height: {}'.format(height))
tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
print('counter: {}'.format(counter[0]))
if __name__ == '__main__':
main()
|
Revise tower of hanoi alg from Yuanlin
|
Revise tower of hanoi alg from Yuanlin
|
Python
|
bsd-2-clause
|
bowen0701/algorithms_data_structures
|
---
+++
@@ -1,32 +1,42 @@
"""The tower of Hanoi."""
+from __future__ import absolute_import
from __future__ import print_function
+from __future__ import division
-def move_towers(height, from_pole, to_pole, with_pole):
+def tower_of_hanoi(height, from_pole, to_pole, with_pole, counter):
if height == 1:
- print('Moving disk from {0} to {1}'.format(from_pole, to_pole))
+ counter[0] += 1
+ print('{0} -> {1}'.format(from_pole, to_pole))
else:
- move_towers(height - 1, from_pole, with_pole, to_pole)
- move_towers(1, from_pole, to_pole, with_pole)
- move_towers(height - 1, with_pole, to_pole, from_pole)
+ tower_of_hanoi(height - 1, from_pole, with_pole, to_pole, counter)
+ tower_of_hanoi(1, from_pole, to_pole, with_pole, counter)
+ tower_of_hanoi(height - 1, with_pole, to_pole, from_pole, counter)
def main():
- from_pole = 'f'
- to_pole = 't'
- with_pole = 'w'
+ from_pole = 'A'
+ to_pole = 'B'
+ with_pole = 'C'
height = 1
+ counter = [0]
print('height: {}'.format(height))
- move_towers(height, from_pole, to_pole, with_pole)
+ tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
+ print('counter: {}'.format(counter[0]))
height = 2
+ counter = [0]
print('height: {}'.format(height))
- move_towers(height, from_pole, to_pole, with_pole)
+ tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
+ print('counter: {}'.format(counter[0]))
- height = 5
+ height = 5
+ counter = [0]
print('height: {}'.format(height))
- move_towers(height, from_pole, to_pole, with_pole)
+ tower_of_hanoi(height, from_pole, to_pole, with_pole, counter)
+ print('counter: {}'.format(counter[0]))
+
if __name__ == '__main__':
main()
|
5987cfc1485b6dc4cccef2b1e538078b90a9acd1
|
pythonx/completers/javascript/__init__.py
|
pythonx/completers/javascript/__init__.py
|
# -*- coding: utf-8 -*-
import json
import os.path
from completor import Completor
from completor.compat import to_unicode
dirname = os.path.dirname(__file__)
class Tern(Completor):
filetype = 'javascript'
daemon = True
trigger = r'\w+$|[\w\)\]\}\'\"]+\.\w*$'
def format_cmd(self):
binary = self.get_option('node_binary') or 'node'
tern_config = self.find_config_file('.tern-project')
cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')]
if tern_config:
cmd.append(os.path.dirname(tern_config))
return cmd
def parse(self, data):
try:
data = to_unicode(data[0], 'utf-8')
return [i for i in json.loads(data)
if not self.input_data.endswith(i['word'])]
except Exception:
return []
|
# -*- coding: utf-8 -*-
import json
import os.path
import re
from completor import Completor
from completor.compat import to_unicode
dirname = os.path.dirname(__file__)
class Tern(Completor):
filetype = 'javascript'
daemon = True
ident = re.compile(r"""(\w+)|(('|").+)""", re.U)
trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$"""
def format_cmd(self):
binary = self.get_option('node_binary') or 'node'
tern_config = self.find_config_file('.tern-project')
cmd = [binary, os.path.join(dirname, 'tern_wrapper.js')]
if tern_config:
cmd.append(os.path.dirname(tern_config))
return cmd
def parse(self, data):
try:
data = to_unicode(data[0], 'utf-8')
return [i for i in json.loads(data)
if not self.input_data.endswith(i['word'])]
except Exception:
return []
|
Add support for tern complete_strings plugin
|
Add support for tern complete_strings plugin
|
Python
|
mit
|
maralla/completor.vim,maralla/completor.vim
|
---
+++
@@ -2,6 +2,7 @@
import json
import os.path
+import re
from completor import Completor
from completor.compat import to_unicode
@@ -12,7 +13,8 @@
class Tern(Completor):
filetype = 'javascript'
daemon = True
- trigger = r'\w+$|[\w\)\]\}\'\"]+\.\w*$'
+ ident = re.compile(r"""(\w+)|(('|").+)""", re.U)
+ trigger = r"""\w+$|[\w\)\]\}\'\"]+\.\w*$|('|").*$"""
def format_cmd(self):
binary = self.get_option('node_binary') or 'node'
|
88752efa9ac2c0f251733e335763cb880da34741
|
thinglang/parser/definitions/member_definition.py
|
thinglang/parser/definitions/member_definition.py
|
from thinglang.lexer.definitions.tags import LexicalPrivateTag
from thinglang.lexer.definitions.thing_definition import LexicalDeclarationMember
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.symbols.symbol import Symbol
class MemberDefinition(BaseNode):
"""
A member definition
Must be a direct child of a ThingDefinition
"""
def __init__(self, name, type_name, visibility=Symbol.PUBLIC):
super(MemberDefinition, self).__init__([name, type_name])
self.type, self.name, self.visibility = type_name, name, visibility
def __repr__(self):
return 'has {} {}'.format(self.type, self.name)
def symbol(self):
return Symbol.member(self.name, self.type, self.visibility)
MEMBER_NAME_TYPES = Identifier
@staticmethod
@ParserRule.mark
def parse_member_definition(_: LexicalDeclarationMember, type_name: MEMBER_NAME_TYPES, name: Identifier):
return MemberDefinition(name, type_name)
@staticmethod
@ParserRule.mark
def tag_member_definition(_: LexicalPrivateTag, member: 'MemberDefinition'):
member.visibility = Symbol.PRIVATE
return member
|
from thinglang.lexer.definitions.tags import LexicalPrivateTag
from thinglang.lexer.definitions.thing_definition import LexicalDeclarationMember
from thinglang.lexer.values.identifier import Identifier
from thinglang.parser.nodes import BaseNode
from thinglang.parser.rule import ParserRule
from thinglang.symbols.symbol import Symbol
class MemberDefinition(BaseNode):
"""
A member definition
Must be a direct child of a ThingDefinition
"""
def __init__(self, name, type_name, visibility=Symbol.PUBLIC):
super(MemberDefinition, self).__init__([name, type_name])
self.type, self.name, self.visibility = type_name, name, visibility
def __repr__(self):
return 'has {} {}'.format(self.type, self.name)
def symbol(self):
return Symbol.member(self.name, self.type, self.visibility)
MEMBER_NAME_TYPES = Identifier
@staticmethod
@ParserRule.mark
def parse_member_definition(_: (LexicalDeclarationMember, LexicalPrivateTag), type_name: MEMBER_NAME_TYPES, name: Identifier):
return MemberDefinition(name, type_name)
|
Add visibility tagging to MethoDefinition
|
Add visibility tagging to MethoDefinition
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
---
+++
@@ -27,11 +27,5 @@
@staticmethod
@ParserRule.mark
- def parse_member_definition(_: LexicalDeclarationMember, type_name: MEMBER_NAME_TYPES, name: Identifier):
+ def parse_member_definition(_: (LexicalDeclarationMember, LexicalPrivateTag), type_name: MEMBER_NAME_TYPES, name: Identifier):
return MemberDefinition(name, type_name)
-
- @staticmethod
- @ParserRule.mark
- def tag_member_definition(_: LexicalPrivateTag, member: 'MemberDefinition'):
- member.visibility = Symbol.PRIVATE
- return member
|
f4a067acd58aa083680a556bb7d79e9d05403eba
|
cc/deploy/vendor_wsgi.py
|
cc/deploy/vendor_wsgi.py
|
"""
Alternative WSGI entry-point that uses requirements/vendor for
dependencies.
"""
import os, sys
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, base_dir)
from cc.deploy.paths import add_vendor_lib
add_vendor_lib()
# Set default settings and instantiate application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cc.settings.default")
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
|
"""
Alternative WSGI entry-point that uses requirements/vendor for
dependencies.
"""
import os, sys
base_dir = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, base_dir)
from cc.deploy.paths import add_vendor_lib
add_vendor_lib()
# Set default settings and instantiate application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cc.settings.default")
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
|
Fix path addition in vendor-wsgi.py.
|
Fix path addition in vendor-wsgi.py.
|
Python
|
bsd-2-clause
|
mozilla/moztrap,mozilla/moztrap,mozilla/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,mozilla/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap
|
---
+++
@@ -5,7 +5,8 @@
"""
import os, sys
-base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+base_dir = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, base_dir)
from cc.deploy.paths import add_vendor_lib
|
d115f039a474e93585096a22f5870c60a221bae9
|
dthm4kaiako/config/__init__.py
|
dthm4kaiako/config/__init__.py
|
"""Configuration for Django system."""
__version__ = "0.14.1"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
|
"""Configuration for Django system."""
__version__ = "0.14.2"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
|
Increment version number to 0.14.2
|
Increment version number to 0.14.2
|
Python
|
mit
|
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
|
---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.14.1"
+__version__ = "0.14.2"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
|
6d16a7d137b723fe93260eb2729aca1d8f98e37f
|
actions/cloudbolt_plugins/multi_user_approval/two_user_approval.py
|
actions/cloudbolt_plugins/multi_user_approval/two_user_approval.py
|
"""
Two User Approval
Overrides CloudBolt's standard Order Approval workflow. This Orchestration
Action requires two users to approve an order before it becomes Active.
Requires CloudBolt 8.8
"""
def run(order, *args, **kwargs):
# Return the order's status to "PENDING" if fewer than two users have
# approved it.
if len(order.approvers) < 2:
order.status = "PENDING"
order.save()
return "SUCCESS", "", ""
|
"""
Two User Approval
~~~~~~~~~~~~~~~~~
Overrides CloudBolt's standard Order Approval workflow. This Orchestration
Action requires two users to approve an Order before it becomes Active.
Version Req.
~~~~~~~~~~~~
CloudBolt 8.8
"""
def run(order, *args, **kwargs):
# Return the order's status to "PENDING" if fewer than two users have
# approved it.
if len(order.approvers) < 2:
order.set_pending()
return "SUCCESS", "", ""
|
Standardize approval Orch Actions docstrings
|
Standardize approval Orch Actions docstrings
[DEV-12140]
|
Python
|
apache-2.0
|
CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge
|
---
+++
@@ -1,10 +1,13 @@
"""
Two User Approval
+~~~~~~~~~~~~~~~~~
+Overrides CloudBolt's standard Order Approval workflow. This Orchestration
+Action requires two users to approve an Order before it becomes Active.
-Overrides CloudBolt's standard Order Approval workflow. This Orchestration
-Action requires two users to approve an order before it becomes Active.
-Requires CloudBolt 8.8
+Version Req.
+~~~~~~~~~~~~
+CloudBolt 8.8
"""
@@ -13,7 +16,6 @@
# approved it.
if len(order.approvers) < 2:
- order.status = "PENDING"
- order.save()
+ order.set_pending()
return "SUCCESS", "", ""
|
318c98ab5a9710dfdeedc0ee893e87993ac49727
|
robosync/test/test_robosync.py
|
robosync/test/test_robosync.py
|
import unittest
import os
import shutil
class testMirror(unittest.TestCase):
def setUp(self):
os.mkdir('test_source')
os.mkdir('test_dest')
source_dirs = ['dir1', 'dir2', 'dir3']
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
contents = ['foobar1', 'foobar2', 'foobar3']
for d_name, f_name, content, in zip(source_dirs, filenames, contents):
new_dir = os.path.join('test_source', d_name)
os.mkdir(new_dir)
with open(os.path.join('test_source', d_name, f_name), 'w') as f:
f.write(content)
def tearDown(self):
shutil.rmtree('test_source')
shutil.rmtree('test_dest')
def test_mirror(self):
pass
if __name__ == '__main__':
unittest.main()
|
import unittest
import os
import shutil
class testMirror(unittest.TestCase):
def setUp(self):
os.mkdir('test_source')
os.mkdir('test_dest')
source_dirs = ['dir1', 'dir2', 'dir3']
dest_dirs = ['dir1_c', 'dir2_c', 'dir3_c']
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
contents = ['foobar1', 'foobar2', 'foobar3']
with open('source_file.txt', 'w') as f:
f.write('\n'.join(source_dirs))
with open('dest_file.txt', 'w') as f:
f.write('\n'.join(dest_dirs))
for d_name, f_name, content, in zip(source_dirs, filenames, contents):
new_dir = os.path.join('test_source', d_name)
os.mkdir(new_dir)
with open(os.path.join('test_source', d_name, f_name), 'w') as f:
f.write(content)
def tearDown(self):
shutil.rmtree('test_source')
shutil.rmtree('test_dest')
os.remove('source_file.txt')
os.remove('dest_file.txt')
def test_mirror(self):
pass
if __name__ == '__main__':
unittest.main()
|
Add source and destination list to setup and teardown
|
Add source and destination list to setup and teardown
|
Python
|
mit
|
rbn920/robosync
|
---
+++
@@ -8,8 +8,15 @@
os.mkdir('test_source')
os.mkdir('test_dest')
source_dirs = ['dir1', 'dir2', 'dir3']
+ dest_dirs = ['dir1_c', 'dir2_c', 'dir3_c']
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
contents = ['foobar1', 'foobar2', 'foobar3']
+ with open('source_file.txt', 'w') as f:
+ f.write('\n'.join(source_dirs))
+
+ with open('dest_file.txt', 'w') as f:
+ f.write('\n'.join(dest_dirs))
+
for d_name, f_name, content, in zip(source_dirs, filenames, contents):
new_dir = os.path.join('test_source', d_name)
os.mkdir(new_dir)
@@ -20,6 +27,8 @@
def tearDown(self):
shutil.rmtree('test_source')
shutil.rmtree('test_dest')
+ os.remove('source_file.txt')
+ os.remove('dest_file.txt')
def test_mirror(self):
|
7fc0c026508472726d2a47b5ab027b3bcc43f101
|
calibre_books/core/management/commands/synchronize.py
|
calibre_books/core/management/commands/synchronize.py
|
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django_dropbox.storage import DropboxStorage
from dropbox.rest import ErrorResponse
from calibre_books.calibre.models import Book, Data
class Command(NoArgsCommand):
def get_url(self, path):
try:
return self.client.media(path).get('url')
except ErrorResponse:
pass
def handle_noargs(self, **options):
self.client = DropboxStorage().client
for book in Book.objects.all():
print book.title,
url = self.get_url('/%s/%s/cover.jpg' % (settings.DROPBOX_CALIBRE_DIR, book.path))
if url:
book.set_data('cover_url', url)
try:
data = book.data.get(format=Data.MOBI)
except ObjectDoesNotExist:
pass
else:
url = self.get_url('/%s/%s/%s.mobi' % (settings.DROPBOX_CALIBRE_DIR, book.path, data.name))
if url:
book.set_data('download_url', url)
print 'done'
|
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import NoArgsCommand
from django.conf import settings
from django_dropbox.storage import DropboxStorage
from dropbox.rest import ErrorResponse
from calibre_books.calibre.models import Book, Data
class Command(NoArgsCommand):
def get_url(self, path):
try:
return self.client.media(path).get('url')
except ErrorResponse:
pass
def handle_noargs(self, **options):
self.client = DropboxStorage().client
calibre_db = self.client.get_file('/%s/metadata.db' % settings.DROPBOX_CALIBRE_DIR)
local_db = open(settings.DATABASES['calibre']['NAME'], 'wb')
local_db.write(calibre_db.read())
local_db.close()
for book in Book.objects.all():
print book.title,
url = self.get_url('/%s/%s/cover.jpg' % (settings.DROPBOX_CALIBRE_DIR, book.path))
if url:
book.set_data('cover_url', url)
try:
data = book.data.get(format=Data.MOBI)
except ObjectDoesNotExist:
pass
else:
url = self.get_url('/%s/%s/%s.mobi' % (settings.DROPBOX_CALIBRE_DIR, book.path, data.name))
if url:
book.set_data('download_url', url)
print 'done'
|
Add ability to get calibre db
|
Add ability to get calibre db
|
Python
|
bsd-2-clause
|
bogdal/calibre-books,bogdal/calibre-books
|
---
+++
@@ -18,6 +18,11 @@
def handle_noargs(self, **options):
self.client = DropboxStorage().client
+ calibre_db = self.client.get_file('/%s/metadata.db' % settings.DROPBOX_CALIBRE_DIR)
+
+ local_db = open(settings.DATABASES['calibre']['NAME'], 'wb')
+ local_db.write(calibre_db.read())
+ local_db.close()
for book in Book.objects.all():
print book.title,
|
7183edee23f715d225b7dc506746e3b7a96d7d6b
|
gmql/dataset/loaders/__init__.py
|
gmql/dataset/loaders/__init__.py
|
"""
Loader settings:
we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the
same id_sample based on the hash of the file name
"""
inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat'
keyFormatClass = 'org.apache.hadoop.io.LongWritable'
valueFormatClass = 'org.apache.hadoop.io.Text'
defaultCombineSize = 64
# configuration of the Hadoop loader used by spark
conf = {"textinputformat.record.delimiter": "\n",
"mapreduce.input.fileinputformat.input.dir.recursive": "true",
"mapred.max.split.size": str(defaultCombineSize*1024*1024)
}
def generateHashKey(filename):
return hash(filename)
def generateNameKey(filename):
if filename.endswith(".meta"):
return filename[:-5]
else:
return filename
|
import os
"""
Loader settings:
we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the
same id_sample based on the hash of the file name
"""
inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat'
keyFormatClass = 'org.apache.hadoop.io.LongWritable'
valueFormatClass = 'org.apache.hadoop.io.Text'
defaultCombineSize = 64
# configuration of the Hadoop loader used by spark
conf = {"textinputformat.record.delimiter": "\n",
"mapreduce.input.fileinputformat.input.dir.recursive": "true",
"mapred.max.split.size": str(defaultCombineSize*1024*1024)
}
"""
Generation of the index of the pandas dataframe.
This can be done in different ways:
- hashing the complete file name
- using directly the file as index (this is visually appealing :) )
"""
def generateHashKey(filename):
return hash(filename)
def generateNameKey(filename):
filename = os.path.basename(filename)
if filename.endswith(".meta"):
return filename[:-5]
else:
return filename
|
Use only the base file name for key
|
Use only the base file name for key
Former-commit-id: 3acbf9e93d3d501013e2a1b6aa9631bdcc663c66 [formerly eea949727d3693aa032033d84dcca3790d9072dd] [formerly ca065bc9f78b1416903179418d64b3273d437987]
Former-commit-id: 58c1d18e8960ad3236a34b8080b18ccff5684eaa
Former-commit-id: 6501068cea164df37ec055c3fb8baf8c89fc7823
|
Python
|
apache-2.0
|
DEIB-GECO/PyGMQL,DEIB-GECO/PyGMQL
|
---
+++
@@ -1,3 +1,5 @@
+import os
+
"""
Loader settings:
we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the
@@ -16,11 +18,19 @@
}
+"""
+ Generation of the index of the pandas dataframe.
+ This can be done in different ways:
+ - hashing the complete file name
+ - using directly the file as index (this is visually appealing :) )
+"""
+
def generateHashKey(filename):
return hash(filename)
def generateNameKey(filename):
+ filename = os.path.basename(filename)
if filename.endswith(".meta"):
return filename[:-5]
else:
|
a117b191c402ce051b6e8aec2fced315c119b9eb
|
test/test_large_source_tree.py
|
test/test_large_source_tree.py
|
import unittest
from yeast_harness import *
class TestLargeSourceTree(unittest.TestCase):
def test_large_source_tree(self):
make_filename = lambda ext='': ''.join(
random.choice(string.ascii_lowercase) for _ in range(8)) + ext
make_sources = lambda path: [
CSourceFile(path + '/' + make_filename('.c')) for _ in range(10)]
make_spore = lambda: SporeFile(
sources=make_sources(make_filename()),
products='static_lib',
name=make_filename('.spore'))
mk = Makefile(
spores=[make_spore() for _ in range(10)], name='Makefile')
with SourceTree('tree') as src:
src.create(mk)
build = Build(src, mk)
self.assertEqual(0, build.make())
|
import unittest
from yeast_harness import *
class TestLargeSourceTree(unittest.TestCase):
def test_large_source_tree(self):
make_filename = lambda ext='': ''.join(
random.choice(string.ascii_lowercase) for _ in range(8)) + ext
make_sources = lambda path: [
CSourceFile(path + '/' + make_filename('.c')) for _ in range(100)]
make_spore = lambda: SporeFile(
sources=make_sources(make_filename()),
products='static_lib',
name=make_filename('.spore'))
mk = Makefile(
spores=[make_spore() for _ in range(10)], name='Makefile')
with SourceTree('tree', preserve=True) as src:
src.create(mk)
build = Build(src, mk)
self.assertEqual(0, build.make('-j4'))
|
Increase size of large source tree 10x
|
Increase size of large source tree 10x
- up to 1000 source files
- use parallel make
- preserve source tree
|
Python
|
mit
|
sjanhunen/moss,sjanhunen/yeast,sjanhunen/moss,sjanhunen/gnumake-molds
|
---
+++
@@ -10,7 +10,7 @@
random.choice(string.ascii_lowercase) for _ in range(8)) + ext
make_sources = lambda path: [
- CSourceFile(path + '/' + make_filename('.c')) for _ in range(10)]
+ CSourceFile(path + '/' + make_filename('.c')) for _ in range(100)]
make_spore = lambda: SporeFile(
sources=make_sources(make_filename()),
products='static_lib',
@@ -19,7 +19,7 @@
mk = Makefile(
spores=[make_spore() for _ in range(10)], name='Makefile')
- with SourceTree('tree') as src:
+ with SourceTree('tree', preserve=True) as src:
src.create(mk)
build = Build(src, mk)
- self.assertEqual(0, build.make())
+ self.assertEqual(0, build.make('-j4'))
|
3e06403b71e8ee826d38f58198342cc22af398bd
|
yacs/settings/development.py
|
yacs/settings/development.py
|
from yacs.settings.base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
'VERSION': CACHE_VERSION,
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacsdb',
'USER': 'yacs',
'PASSWORD': 'NULL', # using trust auth via localhost
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
|
from yacs.settings.base import *
DEBUG = True
TEMPLATE_DEBUG = DEBUG
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
'VERSION': CACHE_VERSION,
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacsdb',
'USER': 'yacs',
'PASSWORD': 'NULL', # using trust auth via localhost
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
|
Add space before inline comment
|
Add space before inline comment
|
Python
|
mit
|
JGrippo/YACS,jeffh/YACS,jeffh/YACS,jeffh/YACS,JGrippo/YACS,JGrippo/YACS,jeffh/YACS,JGrippo/YACS
|
---
+++
@@ -15,7 +15,7 @@
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'yacsdb',
'USER': 'yacs',
- 'PASSWORD': 'NULL', # using trust auth via localhost
+ 'PASSWORD': 'NULL', # using trust auth via localhost
'HOST': '127.0.0.1',
'PORT': '5432',
}
|
a84ce4c8215cced7a64253453a3530911b8518f8
|
job_runner/apps/job_runner/management/commands/broadcast_queue.py
|
job_runner/apps/job_runner/management/commands/broadcast_queue.py
|
import json
import logging
import time
from datetime import datetime
import zmq
from django.conf import settings
from django.core.management.base import NoArgsCommand
from job_runner.apps.job_runner.models import Run
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Broadcast runs in queue to workers'
def handle_noargs(self, **options):
logger.info('Starting queue broadcaster')
context = zmq.Context(1)
publisher = context.socket(zmq.PUB)
publisher.bind(
'tcp://*:{0}'.format(settings.JOB_RUNNER_BROADCASTER_PORT))
while True:
self._broadcast(publisher)
time.sleep(5)
publisher.close()
context.term()
def _broadcast(self, publisher):
"""
Broadcast runs that are scheduled to run now.
:param publisher:
A ``zmq`` publisher.
"""
enqueueable_runs = Run.objects.awaiting_enqueue().filter(
schedule_dts__lte=datetime.utcnow()).select_related()
for run in enqueueable_runs:
worker = run.job.job_template.worker
message = [
'master.broadcast.{0}'.format(worker.api_key),
json.dumps({'run_id': run.id, 'action': 'enqueue'})
]
logger.debug('Sending: {0}'.format(message))
publisher.send_multipart(message)
|
import json
import logging
import time
from datetime import datetime
import zmq
from django.conf import settings
from django.core.management.base import NoArgsCommand
from job_runner.apps.job_runner.models import Run
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = 'Broadcast runs in queue to workers'
def handle_noargs(self, **options):
logger.info('Starting queue broadcaster')
context = zmq.Context(1)
publisher = context.socket(zmq.PUB)
publisher.bind(
'tcp://*:{0}'.format(settings.JOB_RUNNER_BROADCASTER_PORT))
# give the subscribers some time to (re-)connect.
time.sleep(2)
while True:
self._broadcast(publisher)
time.sleep(5)
publisher.close()
context.term()
def _broadcast(self, publisher):
"""
Broadcast runs that are scheduled to run now.
:param publisher:
A ``zmq`` publisher.
"""
enqueueable_runs = Run.objects.awaiting_enqueue().filter(
schedule_dts__lte=datetime.utcnow()).select_related()
for run in enqueueable_runs:
worker = run.job.job_template.worker
message = [
'master.broadcast.{0}'.format(worker.api_key),
json.dumps({'run_id': run.id, 'action': 'enqueue'})
]
logger.debug('Sending: {0}'.format(message))
publisher.send_multipart(message)
|
Add time.sleep after binding publisher to give subscribers time to (re-)connect.
|
Add time.sleep after binding publisher to give subscribers time to (re-)connect.
|
Python
|
bsd-3-clause
|
spilgames/job-runner,spilgames/job-runner
|
---
+++
@@ -22,6 +22,9 @@
publisher = context.socket(zmq.PUB)
publisher.bind(
'tcp://*:{0}'.format(settings.JOB_RUNNER_BROADCASTER_PORT))
+
+ # give the subscribers some time to (re-)connect.
+ time.sleep(2)
while True:
self._broadcast(publisher)
|
68c7db19c0ac8c159bc12ff9714dea068a7835e4
|
importlib_resources/__init__.py
|
importlib_resources/__init__.py
|
"""Read resources contained within a package."""
import sys
__all__ = [
'Package',
'Resource',
'ResourceReader',
'contents',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
]
if sys.version_info >= (3,):
from importlib_resources._py3 import (
Package,
Resource,
contents,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
from importlib_resources.abc import ResourceReader
else:
from importlib_resources._py2 import (
contents,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
del __all__[:3]
__version__ = read_text('importlib_resources', 'version.txt').strip()
|
"""Read resources contained within a package."""
import sys
__all__ = [
'Package',
'Resource',
'ResourceReader',
'contents',
'files',
'is_resource',
'open_binary',
'open_text',
'path',
'read_binary',
'read_text',
]
if sys.version_info >= (3,):
from importlib_resources._py3 import (
Package,
Resource,
contents,
files,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
from importlib_resources.abc import ResourceReader
else:
from importlib_resources._py2 import (
contents,
files,
is_resource,
open_binary,
open_text,
path,
read_binary,
read_text,
)
del __all__[:3]
__version__ = read_text('importlib_resources', 'version.txt').strip()
|
Add files to the exported names.
|
Add files to the exported names.
|
Python
|
apache-2.0
|
python/importlib_resources
|
---
+++
@@ -8,6 +8,7 @@
'Resource',
'ResourceReader',
'contents',
+ 'files',
'is_resource',
'open_binary',
'open_text',
@@ -22,6 +23,7 @@
Package,
Resource,
contents,
+ files,
is_resource,
open_binary,
open_text,
@@ -33,6 +35,7 @@
else:
from importlib_resources._py2 import (
contents,
+ files,
is_resource,
open_binary,
open_text,
|
3ef02d93f9c7e60341ea2d8e407a62d2cadd95f6
|
mangopaysdk/types/payinexecutiondetailsdirect.py
|
mangopaysdk/types/payinexecutiondetailsdirect.py
|
from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
# Mode3DSType { DEFAULT, FORCE }
self.SecureMode = None
self.StatementDescriptor = None
|
from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails
class PayInExecutionDetailsDirect(PayInExecutionDetails):
def __init__(self):
# direct card
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
self.SecureModeNeeded = None
# Mode3DSType { DEFAULT, FORCE }
self.SecureMode = None
self.StatementDescriptor = None
|
Add SecureModeNeeded property to PayInExecutionDetailsDirect
|
Add SecureModeNeeded property to PayInExecutionDetailsDirect
|
Python
|
mit
|
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
|
---
+++
@@ -8,6 +8,7 @@
self.CardId = None
self.SecureModeReturnURL = None
self.SecureModeRedirectURL = None
+ self.SecureModeNeeded = None
# Mode3DSType { DEFAULT, FORCE }
self.SecureMode = None
self.StatementDescriptor = None
|
491ce4e51d666fc068e4bed14ab410b90e5b1ea8
|
extraction/utils.py
|
extraction/utils.py
|
import subprocess32 as subprocess
import threading
import signal
def external_process(process_args, input_data='', timeout=None):
'''
Pipes input_data via stdin to the process specified by process_args and returns the results
Arguments:
process_args -- passed directly to subprocess.Popen(), see there for more details
input_data -- the data to pipe in via STDIN (optional)
timeout -- number of seconds to time out the process after (optional)
IF the process timesout, a subprocess32.TimeoutExpired exception will be raised
Returns:
(exit_status, stdout, stderr) -- a tuple of the exit status code and strings containing stdout and stderr data
Examples:
>>> external_process(['grep', 'Data'], input_data="Some String\nWith Data")
(0, 'With Data\n', '')
'''
process = subprocess.Popen(process_args,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
(stdout, stderr) = process.communicate(input_data, timeout)
except subprocess.TimeoutExpired as e:
# cleanup process
# see https://docs.python.org/3.3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate
process.kill()
process.communicate()
raise e
exit_status = process.returncode
return (exit_status, stdout, stderr)
|
import subprocess32 as subprocess
import threading
import signal
import tempfile
import os
def external_process(process_args, input_data='', timeout=None):
'''
Pipes input_data via stdin to the process specified by process_args and returns the results
Arguments:
process_args -- passed directly to subprocess.Popen(), see there for more details
input_data -- the data to pipe in via STDIN (optional)
timeout -- number of seconds to time out the process after (optional)
IF the process timesout, a subprocess32.TimeoutExpired exception will be raised
Returns:
(exit_status, stdout, stderr) -- a tuple of the exit status code and strings containing stdout and stderr data
Examples:
>>> external_process(['grep', 'Data'], input_data="Some String\nWith Data")
(0, 'With Data\n', '')
'''
process = subprocess.Popen(process_args,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
try:
(stdout, stderr) = process.communicate(input_data, timeout)
except subprocess.TimeoutExpired as e:
# cleanup process
# see https://docs.python.org/3.3/library/subprocess.html?highlight=subprocess#subprocess.Popen.communicate
process.kill()
process.communicate()
raise e
exit_status = process.returncode
return (exit_status, stdout, stderr)
def temp_file(data, suffix=''):
handle, file_path = tempfile.mkstemp(suffix=suffix)
f = os.fdopen(handle, 'w')
f.write(data)
f.close()
return file_path
|
Add method to create tempfile with content easily
|
Add method to create tempfile with content easily
|
Python
|
apache-2.0
|
SeerLabs/extractor-framework,Tiger66639/extractor-framework
|
---
+++
@@ -1,6 +1,8 @@
import subprocess32 as subprocess
import threading
import signal
+import tempfile
+import os
def external_process(process_args, input_data='', timeout=None):
'''
@@ -35,3 +37,13 @@
exit_status = process.returncode
return (exit_status, stdout, stderr)
+
+def temp_file(data, suffix=''):
+ handle, file_path = tempfile.mkstemp(suffix=suffix)
+ f = os.fdopen(handle, 'w')
+ f.write(data)
+ f.close()
+ return file_path
+
+
+
|
59db2a96034955fe678242e63d826610a009a103
|
indra/tests/test_dart_client.py
|
indra/tests/test_dart_client.py
|
import json
from indra.literature.dart_client import _jsonify_query_data
def test_timestamp():
# Should ignore "after"
assert _jsonify_query_data(timestamp={'on': '2020-01-01',
'after': '2020-01-02'}) == \
json.dumps({"timestamp": {"on": "2020-01-01"}})
assert _jsonify_query_data(timestamp={'after': '2020-01-01',
'before': '2020-01-05'}) == \
json.dumps(
{'timestamp': {'after': '2020-01-01', 'before': '2020-01-05'}})
def test_lists():
# Check lists, ignore the lists that have non-str objects
assert _jsonify_query_data(readers=['hume', 123456],
versions=['123', '456']) ==\
json.dumps({'versions': ['123', '456']})
|
import json
import requests
from indra.config import get_config
from indra.literature.dart_client import _jsonify_query_data, dart_base_url
def test_timestamp():
# Should ignore "after"
assert _jsonify_query_data(timestamp={'on': '2020-01-01',
'after': '2020-01-02'}) == \
json.dumps({"timestamp": {"on": "2020-01-01"}})
assert _jsonify_query_data(timestamp={'after': '2020-01-01',
'before': '2020-01-05'}) == \
json.dumps(
{'timestamp': {'after': '2020-01-01', 'before': '2020-01-05'}})
def test_lists():
# Check lists, ignore the lists that have non-str objects
assert _jsonify_query_data(readers=['hume', 123456],
versions=['123', '456']) ==\
json.dumps({'versions': ['123', '456']})
def test_api():
health_ep = dart_base_url + '/health'
dart_uname = get_config('DART_WM_USERNAME', failure_ok=False)
dart_pwd = get_config('DART_WM_PASSWORD', failure_ok=False)
res = requests.get(health_ep, auth=(dart_uname, dart_pwd))
assert res.status_code == 200
|
Add test for reaching API health endpoint
|
Add test for reaching API health endpoint
|
Python
|
bsd-2-clause
|
sorgerlab/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/belpy
|
---
+++
@@ -1,5 +1,7 @@
import json
-from indra.literature.dart_client import _jsonify_query_data
+import requests
+from indra.config import get_config
+from indra.literature.dart_client import _jsonify_query_data, dart_base_url
def test_timestamp():
@@ -18,3 +20,11 @@
assert _jsonify_query_data(readers=['hume', 123456],
versions=['123', '456']) ==\
json.dumps({'versions': ['123', '456']})
+
+
+def test_api():
+ health_ep = dart_base_url + '/health'
+ dart_uname = get_config('DART_WM_USERNAME', failure_ok=False)
+ dart_pwd = get_config('DART_WM_PASSWORD', failure_ok=False)
+ res = requests.get(health_ep, auth=(dart_uname, dart_pwd))
+ assert res.status_code == 200
|
0e6f62ec8230f85cfb891917be5d7ed144b44979
|
src/pretty_print.py
|
src/pretty_print.py
|
#!/usr/bin/python
import argparse
import re
format = list('''
-- --
-----------
-----------
----------
--------
-------
-- --
-----------
'''[1:-1])
def setFormatString(index, value):
position = -1
for i in range(len(format)):
if not format[i].isspace():
position += 1
if position == index:
format[i] = value
return
assert False, 'Format string is shorter than maximum index.'
parser = argparse.ArgumentParser(description='Convert array notation into a visual output.')
parser.add_argument('solution', help='The solution to format. e.g. [0,1,1],[1,0,0]')
# Remove whitespace from string and split based on brackets
args = parser.parse_args()
solution = re.sub(r'\s+', '', args.solution, flags=re.UNICODE)
assert solution[0] == '[', 'Expected input to start with an open bracket.'
assert solution[-1] == ']', 'Expected input to end with a close bracket.'
solution = solution[1:-1]
# Indicate the location of each piece in the format string by a unique letter
char = 'a'
for piece in solution.split('],['):
for index in piece.split(','):
setFormatString(int(index), char)
char = chr(ord(char) + 1)
print(''.join(format))
|
#!/usr/bin/python
import argparse
import ast
format = list('''
-- --
-----------
-----------
----------
--------
-------
-- --
-----------
'''[1:-1])
# Print the given labels using the whitespace of format.
def printFormatted(labels):
i = 0
for c in format:
if c.isspace():
print(c, end='')
else:
print(labels[i], end='')
i += 1
print()
# Insert value into array at index, expanding array as necessary.
def insertAtIndex(array, index, value):
while len(array) < index + 1:
array.append(None)
array[index] = value
# Input: [[3,2],[1,5],[4,0]]
# Output: ['c', 'b', 'a', 'a', 'c', 'b']
def createLabelArray(indexes):
result = []
for i in range(len(indexes)):
label = chr(ord('a') + i)
for index in indexes[i]:
insertAtIndex(result, index, label)
return result
def main():
parser = argparse.ArgumentParser(description='Convert array notation into a visual output.')
parser.add_argument('solution', help='The solution to format. e.g. [0,1,1],[1,0,0]')
args = parser.parse_args()
solution = ast.literal_eval(args.solution)
labels = createLabelArray(solution)
printFormatted(labels)
if __name__ == "__main__":
main()
|
Clean up python script and make it run in linear time.
|
Clean up python script and make it run in linear time.
|
Python
|
mit
|
altayhunter/Pentomino-Puzzle-Solver,altayhunter/Pentomino-Puzzle-Solver
|
---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/python
import argparse
-import re
+import ast
format = list('''
-- --
@@ -13,29 +13,41 @@
-----------
'''[1:-1])
-def setFormatString(index, value):
- position = -1
- for i in range(len(format)):
- if not format[i].isspace():
- position += 1
- if position == index:
- format[i] = value
- return
- assert False, 'Format string is shorter than maximum index.'
+# Print the given labels using the whitespace of format.
+def printFormatted(labels):
+ i = 0
+ for c in format:
+ if c.isspace():
+ print(c, end='')
+ else:
+ print(labels[i], end='')
+ i += 1
+ print()
-parser = argparse.ArgumentParser(description='Convert array notation into a visual output.')
-parser.add_argument('solution', help='The solution to format. e.g. [0,1,1],[1,0,0]')
+# Insert value into array at index, expanding array as necessary.
+def insertAtIndex(array, index, value):
+ while len(array) < index + 1:
+ array.append(None)
+ array[index] = value
-# Remove whitespace from string and split based on brackets
-args = parser.parse_args()
-solution = re.sub(r'\s+', '', args.solution, flags=re.UNICODE)
-assert solution[0] == '[', 'Expected input to start with an open bracket.'
-assert solution[-1] == ']', 'Expected input to end with a close bracket.'
-solution = solution[1:-1]
-# Indicate the location of each piece in the format string by a unique letter
-char = 'a'
-for piece in solution.split('],['):
- for index in piece.split(','):
- setFormatString(int(index), char)
- char = chr(ord(char) + 1)
-print(''.join(format))
+# Input: [[3,2],[1,5],[4,0]]
+# Output: ['c', 'b', 'a', 'a', 'c', 'b']
+def createLabelArray(indexes):
+ result = []
+ for i in range(len(indexes)):
+ label = chr(ord('a') + i)
+ for index in indexes[i]:
+ insertAtIndex(result, index, label)
+ return result
+
+def main():
+ parser = argparse.ArgumentParser(description='Convert array notation into a visual output.')
+ parser.add_argument('solution', help='The solution to format. e.g. [0,1,1],[1,0,0]')
+
+ args = parser.parse_args()
+ solution = ast.literal_eval(args.solution)
+ labels = createLabelArray(solution)
+ printFormatted(labels)
+
+if __name__ == "__main__":
+ main()
|
941392d41317943f4c0603d7d28a31858a2648bc
|
neutron/plugins/ml2/drivers/datacom/db/models.py
|
neutron/plugins/ml2/drivers/datacom/db/models.py
|
from sqlalchemy import Column, String, ForeignKey
from sqlalchemy.orm import relationship, backref
from neutron.db.model_base import BASEV2
from neutron.db.models_v2 import HasId
class DatacomTenant(BASEV2, HasId):
"""Datacom Tenant table"""
tenant = Column(String(50))
class DatacomNetwork(BASEV2, HasId):
"""Each VLAN represent a Network
Multiple networks may be associated with a tenant
"""
vlan = Column(String(10))
tenant_id = Column(String(36), ForeignKey('datacomtenant.id'))
tenant = relationship('DatacomTenant', backref=backref('datacomtenants'))
class DatacomPort(BASEV2, HasId):
"""Each port is connected to a network"""
port = Column(String(36))
network_id = Column(String(36), ForeignKey('datacomnetwork.id'))
network = relationship('DatacomNetwork', backref=backref('ports'))
|
from sqlalchemy import Column, String, ForeignKey, Integer
from sqlalchemy.orm import relationship, backref
from neutron.db.model_base import BASEV2
from neutron.db.models_v2 import HasId
class DatacomNetwork(BASEV2, HasId):
"""Each VLAN represent a Network
a network may have multiple ports
"""
vid = Column(Integer)
name = Column(String(30))
class DatacomPort(BASEV2, HasId):
"""Each port is connected to a network
"""
port = Column(Integer)
network_id = Column(String(36), ForeignKey('datacomnetworks.id'))
network = relationship('DatacomNetwork', backref=backref('ports'))
|
Fix DB to fit new requirements
|
Fix DB to fit new requirements
|
Python
|
apache-2.0
|
asgard-lab/neutron,asgard-lab/neutron
|
---
+++
@@ -1,27 +1,20 @@
-from sqlalchemy import Column, String, ForeignKey
+from sqlalchemy import Column, String, ForeignKey, Integer
from sqlalchemy.orm import relationship, backref
from neutron.db.model_base import BASEV2
from neutron.db.models_v2 import HasId
-
-class DatacomTenant(BASEV2, HasId):
- """Datacom Tenant table"""
- tenant = Column(String(50))
-
-
class DatacomNetwork(BASEV2, HasId):
"""Each VLAN represent a Network
- Multiple networks may be associated with a tenant
+ a network may have multiple ports
"""
- vlan = Column(String(10))
- tenant_id = Column(String(36), ForeignKey('datacomtenant.id'))
- tenant = relationship('DatacomTenant', backref=backref('datacomtenants'))
-
+ vid = Column(Integer)
+ name = Column(String(30))
class DatacomPort(BASEV2, HasId):
- """Each port is connected to a network"""
- port = Column(String(36))
+ """Each port is connected to a network
+ """
+ port = Column(Integer)
- network_id = Column(String(36), ForeignKey('datacomnetwork.id'))
+ network_id = Column(String(36), ForeignKey('datacomnetworks.id'))
network = relationship('DatacomNetwork', backref=backref('ports'))
|
e6611885dcb1200dec13603b68c5ad03fcae97e4
|
frasco/redis/ext.py
|
frasco/redis/ext.py
|
from frasco.ext import *
from redis import StrictRedis
from werkzeug.local import LocalProxy
from .templating import CacheFragmentExtension
class FrascoRedis(Extension):
name = "frasco_redis"
defaults = {"url": "redis://localhost:6379/0",
"fragment_cache_timeout": 3600,
"decode_responses": True}
def _init_app(self, app, state):
state.connection = StrictRedis.from_url(state.options["url"], state.options["decode_responses"])
app.jinja_env.add_extension(CacheFragmentExtension)
def get_current_redis():
return get_extension_state('frasco_redis').connection
redis = LocalProxy(get_current_redis)
|
from frasco.ext import *
from redis import Redis
from werkzeug.local import LocalProxy
from .templating import CacheFragmentExtension
class FrascoRedis(Extension):
name = "frasco_redis"
defaults = {"url": "redis://localhost:6379/0",
"fragment_cache_timeout": 3600,
"decode_responses": True,
"encoding": "utf-8"}
def _init_app(self, app, state):
state.connection = Redis.from_url(state.options["url"],
decode_responses=state.options["decode_responses"],
encoding=state.options["encoding"])
app.jinja_env.add_extension(CacheFragmentExtension)
def get_current_redis():
return get_extension_state('frasco_redis').connection
redis = LocalProxy(get_current_redis)
|
Set the encoding parameter in Redis constructor
|
[redis] Set the encoding parameter in Redis constructor
|
Python
|
mit
|
frascoweb/frasco,frascoweb/frasco
|
---
+++
@@ -1,5 +1,5 @@
from frasco.ext import *
-from redis import StrictRedis
+from redis import Redis
from werkzeug.local import LocalProxy
from .templating import CacheFragmentExtension
@@ -8,10 +8,13 @@
name = "frasco_redis"
defaults = {"url": "redis://localhost:6379/0",
"fragment_cache_timeout": 3600,
- "decode_responses": True}
+ "decode_responses": True,
+ "encoding": "utf-8"}
def _init_app(self, app, state):
- state.connection = StrictRedis.from_url(state.options["url"], state.options["decode_responses"])
+ state.connection = Redis.from_url(state.options["url"],
+ decode_responses=state.options["decode_responses"],
+ encoding=state.options["encoding"])
app.jinja_env.add_extension(CacheFragmentExtension)
|
903274d3bf87e642430e5b603c924601baa3955a
|
emission/net/usercache/formatters/android/motion_activity.py
|
emission/net/usercache/formatters/android/motion_activity.py
|
import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
|
import logging
import emission.core.wrapper.motionactivity as ecwa
import emission.net.usercache.formatters.common as fc
import attrdict as ad
def format(entry):
formatted_entry = ad.AttrDict()
formatted_entry["_id"] = entry["_id"]
formatted_entry.user_id = entry.user_id
metadata = entry.metadata
if "time_zone" not in metadata:
metadata.time_zone = "America/Los_Angeles"
fc.expand_metadata_times(metadata)
formatted_entry.metadata = metadata
data = ad.AttrDict()
if 'agb' in entry.data:
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
elif 'ajO' in entry.data:
data.type = ecwa.MotionTypes(entry.data.ajO).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
if 'agc' in entry.data:
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
elif 'ajP' in entry.data:
data.confidence = entry.data.ajP
else:
data.confidence = entry.data.zzaKN
data.ts = formatted_entry.metadata.write_ts
data.local_dt = formatted_entry.metadata.write_local_dt
data.fmt_time = formatted_entry.metadata.write_fmt_time
formatted_entry.data = data
return formatted_entry
|
Change the motionactivity formatter to match the new version of the google play library
|
Change the motionactivity formatter to match the new version of the google play library
We bumped up the play version number in
https://github.com/e-mission/e-mission-data-collection/commit/a93bc993ddcc1e78ab7fc15e6c9a588ce28a5e45
which will change the fields that show up in the android messages.
We really need to resolve
https://github.com/e-mission/e-mission-data-collection/issues/80
|
Python
|
bsd-3-clause
|
shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server
|
---
+++
@@ -20,6 +20,8 @@
data.type = ecwa.MotionTypes(entry.data.agb).value
elif 'zzaEg' in entry.data:
data.type = ecwa.MotionTypes(entry.data.zzaEg).value
+ elif 'ajO' in entry.data:
+ data.type = ecwa.MotionTypes(entry.data.ajO).value
else:
data.type = ecwa.MotionTypes(entry.data.zzaKM).value
@@ -28,6 +30,8 @@
data.confidence = entry.data.agc
elif 'zzaEh' in entry.data:
data.confidence = entry.data.zzaEh
+ elif 'ajP' in entry.data:
+ data.confidence = entry.data.ajP
else:
data.confidence = entry.data.zzaKN
|
92420d319865f2f0dcf0e53a4b4a3fecc30b6aad
|
components/lie_md/lie_md/gromacs_gromit.py
|
components/lie_md/lie_md/gromacs_gromit.py
|
# -*- coding: utf-8 -*-
"""
file: gromacs_gromit.py
Prepaire gromit command line input
"""
GROMIT_ARG_DICT = {
'forcefield': '-ff',
'charge': '-charge',
'gromacs_lie': '-lie',
'periodic_distance': '-d',
'temperature': '-t',
'prfc': '-prfc',
'ttau': '-ttau',
'salinity': '-conc',
'solvent': '-solvent',
'ptau': '-ptau',
'sim_time': '-time',
'gromacs_vsite': '-vsite',
'gmxrc': '-gmxrc'}
def gromit_cmd(options):
gmxRun = './gmx45md.sh '
for arg, val in options.items():
if arg in GROMIT_ARG_DICT:
if val:
gmxRun += '{0} '.format(GROMIT_ARG_DICT[arg])
else:
gmxRun += '{0} {1} '.format(GROMIT_ARG_DICT[arg], val)
return gmxRun
|
# -*- coding: utf-8 -*-
"""
file: gromacs_gromit.py
Prepaire gromit command line input
"""
GROMIT_ARG_DICT = {
'forcefield': '-ff',
'charge': '-charge',
'gromacs_lie': '-lie',
'periodic_distance': '-d',
'temperature': '-t',
'prfc': '-prfc',
'ttau': '-ttau',
'salinity': '-conc',
'solvent': '-solvent',
'ptau': '-ptau',
'sim_time': '-time',
'gromacs_vsite': '-vsite',
'gmxrc': '-gmxrc',
'gromacs_rtc': '-rtc',
'gromacs_ndlp': '-ndlp'}
def gromit_cmd(options):
gmxRun = './gmx45md.sh '
for arg, val in options.items():
if arg in GROMIT_ARG_DICT:
if val == True:
gmxRun += '{0} '.format(GROMIT_ARG_DICT[arg])
elif val:
gmxRun += '{0} {1} '.format(GROMIT_ARG_DICT[arg], val)
else:
pass
return gmxRun
|
Fix command line argument construction
|
Fix command line argument construction
Boolean values not parsed correctly
|
Python
|
apache-2.0
|
MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio
|
---
+++
@@ -19,7 +19,9 @@
'ptau': '-ptau',
'sim_time': '-time',
'gromacs_vsite': '-vsite',
- 'gmxrc': '-gmxrc'}
+ 'gmxrc': '-gmxrc',
+ 'gromacs_rtc': '-rtc',
+ 'gromacs_ndlp': '-ndlp'}
def gromit_cmd(options):
@@ -27,9 +29,11 @@
gmxRun = './gmx45md.sh '
for arg, val in options.items():
if arg in GROMIT_ARG_DICT:
- if val:
+ if val == True:
gmxRun += '{0} '.format(GROMIT_ARG_DICT[arg])
+ elif val:
+ gmxRun += '{0} {1} '.format(GROMIT_ARG_DICT[arg], val)
else:
- gmxRun += '{0} {1} '.format(GROMIT_ARG_DICT[arg], val)
+ pass
return gmxRun
|
3245d884845748ef641ae1b39a14a040cf9a97a9
|
debexpo/tests/functional/test_register.py
|
debexpo/tests/functional/test_register.py
|
from debexpo.tests import TestController, url
from debexpo.model import meta
from debexpo.model.users import User
class TestRegisterController(TestController):
def test_maintainer_signup(self):
count = meta.session.query(User).filter(User.email=='mr_me@example.com').count()
self.assertEquals(count, 0)
self.app.post(url(controller='register', action='maintainer'),
{'name': 'Mr. Me',
'password': 'password',
'password_confirm': 'password',
'commit': 'yes',
'email': 'mr_me@example.com'})
count = meta.session.query(User).filter(User.email=='mr_me@example.com').count()
self.assertEquals(count, 1)
user = meta.session.query(User).filter(User.email=='mr_me@example.com').one()
# delete it
meta.session.delete(user)
|
from debexpo.tests import TestController, url
from debexpo.model import meta
from debexpo.model.users import User
class TestRegisterController(TestController):
def test_maintainer_signup(self, actually_delete_it=True):
count = meta.session.query(User).filter(User.email=='mr_me@example.com').count()
self.assertEquals(count, 0)
self.app.post(url(controller='register', action='maintainer'),
{'name': 'Mr. Me',
'password': 'password',
'password_confirm': 'password',
'commit': 'yes',
'email': 'mr_me@example.com'})
count = meta.session.query(User).filter(User.email=='mr_me@example.com').count()
self.assertEquals(count, 1)
user = meta.session.query(User).filter(User.email=='mr_me@example.com').one()
# delete it
if actually_delete_it:
meta.session.delete(user)
else:
return user
def test_maintainer_signup_with_duplicate_name(self):
self.test_maintainer_signup(actually_delete_it=False)
self.app.post(url(controller='register', action='maintainer'),
{'name': 'Mr. Me',
'password': 'password',
'password_confirm': 'password',
'commit': 'yes',
'email': 'mr_me_again@example.com'})
count = meta.session.query(User).filter(User.email=='mr_me_again@example.com').count()
self.assertEquals(count, 1)
|
Add a test that reproduces the crash if you sign up a second time with the same name
|
Add a test that reproduces the crash if you sign up a second time with the same name
|
Python
|
mit
|
jonnylamb/debexpo,swvist/Debexpo,jonnylamb/debexpo,swvist/Debexpo,jonnylamb/debexpo,swvist/Debexpo,jadonk/debexpo,jadonk/debexpo,jadonk/debexpo
|
---
+++
@@ -4,7 +4,7 @@
class TestRegisterController(TestController):
- def test_maintainer_signup(self):
+ def test_maintainer_signup(self, actually_delete_it=True):
count = meta.session.query(User).filter(User.email=='mr_me@example.com').count()
self.assertEquals(count, 0)
@@ -20,5 +20,21 @@
user = meta.session.query(User).filter(User.email=='mr_me@example.com').one()
# delete it
- meta.session.delete(user)
+ if actually_delete_it:
+ meta.session.delete(user)
+ else:
+ return user
+ def test_maintainer_signup_with_duplicate_name(self):
+ self.test_maintainer_signup(actually_delete_it=False)
+
+ self.app.post(url(controller='register', action='maintainer'),
+ {'name': 'Mr. Me',
+ 'password': 'password',
+ 'password_confirm': 'password',
+ 'commit': 'yes',
+ 'email': 'mr_me_again@example.com'})
+
+ count = meta.session.query(User).filter(User.email=='mr_me_again@example.com').count()
+ self.assertEquals(count, 1)
+
|
772cff48318cd745fd2fcadd4c6bdc52629b176d
|
dp/dirichlet.py
|
dp/dirichlet.py
|
# -*- coding: utf-8 -*-
from random import betavariate, uniform
def weighted_choice(weights):
choices = range(len(weights))
total = sum(weights)
r = uniform(0, total)
upto = 0
for c, w in zip(choices, weights):
if upto + w > r:
return c
upto += w
raise Exception("Error in weighted_choice.")
class DirichletProcess():
def __init__(self, base_measure, alpha):
self.base_measure = base_measure
self.alpha = alpha
self.cache = []
self.weights = []
self.total_stick_used = 0.
def __call__(self):
remaining = 1.0 - self.total_stick_used
i = weighted_choice(self.weights + [remaining])
if i < len(self.weights):
return self.cache[i]
else:
stick_piece = betavariate(1, self.alpha) * remaining
self.total_stick_used += stick_piece
self.weights.append(stick_piece)
new_value = self.base_measure()
self.cache.append(new_value)
return new_value
|
# -*- coding: utf-8 -*-
from random import betavariate, uniform
def weighted_choice(weights):
choices = range(len(weights))
total = sum(weights)
r = uniform(0, total)
upto = 0
for c, w in zip(choices, weights):
if upto + w > r:
return c
upto += w
raise Exception("Error in weighted_choice.")
class DirichletProcess():
def __init__(self, base_measure, alpha):
if alpha <= 0:
raise ValueError("alpha must be a positive number")
self.base_measure = base_measure
self.alpha = alpha
self.cache = []
self.weights = []
self.total_stick_used = 0.
def __call__(self):
remaining = 1.0 - self.total_stick_used
i = weighted_choice(self.weights + [remaining])
if i < len(self.weights):
return self.cache[i]
else:
stick_piece = betavariate(1, self.alpha) * remaining
self.total_stick_used += stick_piece
self.weights.append(stick_piece)
new_value = self.base_measure()
self.cache.append(new_value)
return new_value
|
Raise error on bad alpha value
|
Raise error on bad alpha value
|
Python
|
mit
|
fivejjs/dirichletprocess,tdhopper/dirichletprocess,fivejjs/dirichletprocess,tdhopper/dirichletprocess
|
---
+++
@@ -17,6 +17,8 @@
class DirichletProcess():
def __init__(self, base_measure, alpha):
+ if alpha <= 0:
+ raise ValueError("alpha must be a positive number")
self.base_measure = base_measure
self.alpha = alpha
|
f80b080f62b450531007f58849019fd18c75c25f
|
stacker/blueprints/rds/postgres.py
|
stacker/blueprints/rds/postgres.py
|
from stacker.blueprints.rds import base
class PostgresMixin(object):
def engine(self):
return "postgres"
def get_engine_versions(self):
return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.4.1']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
class MasterInstance(PostgresMixin, base.MasterInstance):
pass
class ReadReplica(PostgresMixin, base.ReadReplica):
pass
|
from stacker.blueprints.rds import base
class PostgresMixin(object):
def engine(self):
return "postgres"
def get_engine_versions(self):
return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.3.9',
'9.3.10', '9.4.1', '9.4.4', '9.4.5']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
class MasterInstance(PostgresMixin, base.MasterInstance):
pass
class ReadReplica(PostgresMixin, base.ReadReplica):
pass
|
Add new versions of Postgres
|
Add new versions of Postgres
|
Python
|
bsd-2-clause
|
mhahn/stacker,remind101/stacker,mhahn/stacker,remind101/stacker
|
---
+++
@@ -6,7 +6,8 @@
return "postgres"
def get_engine_versions(self):
- return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.4.1']
+ return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.3.9',
+ '9.3.10', '9.4.1', '9.4.4', '9.4.5']
def get_db_families(self):
return ["postgres9.3", "postgres9.4"]
|
6860d8a1fabdf7a8b18ad7cd6c687128443f85b5
|
HARK/tests/test_validators.py
|
HARK/tests/test_validators.py
|
import unittest
from HARK.validators import non_empty
class ValidatorsTests(unittest.TestCase):
'''
Tests for validator decorators which validate function arguments
'''
def test_non_empty(self):
@non_empty('list_a')
def foo(list_a, list_b):
pass
try:
foo([1], [])
except Exception:
self.fail()
with self.assertRaisesRegex(
TypeError,
'Expected non-empty argument for parameter list_a',
):
foo([], [1])
@non_empty('list_a', 'list_b')
def foo(list_a, list_b):
pass
with self.assertRaisesRegex(
TypeError,
'Expected non-empty argument for parameter list_b',
):
foo([1], [])
with self.assertRaisesRegex(
TypeError,
'Expected non-empty argument for parameter list_a',
):
foo([], [1])
|
import unittest
from HARK.validators import non_empty
class ValidatorsTests(unittest.TestCase):
'''
Tests for validator decorators which validate function arguments
'''
def test_non_empty(self):
@non_empty('list_a')
def foo(list_a, list_b):
pass
try:
foo([1], [])
except Exception:
self.fail()
if sys.version[0] == 2:
with self.assertRaisesRegexp(
TypeError,
'Expected non-empty argument for parameter list_a',
):
foo([], [1])
else:
with self.assertRaisesRegex(
TypeError,
'Expected non-empty argument for parameter list_a',
):
foo([], [1])
@non_empty('list_a', 'list_b')
def foo(list_a, list_b):
pass
with self.assertRaisesRegex(
TypeError,
'Expected non-empty argument for parameter list_b',
):
foo([1], [])
with self.assertRaisesRegex(
TypeError,
'Expected non-empty argument for parameter list_a',
):
foo([], [1])
|
Use different assert for Python 2 v 3
|
Use different assert for Python 2 v 3
|
Python
|
apache-2.0
|
econ-ark/HARK,econ-ark/HARK
|
---
+++
@@ -16,11 +16,19 @@
foo([1], [])
except Exception:
self.fail()
- with self.assertRaisesRegex(
- TypeError,
- 'Expected non-empty argument for parameter list_a',
- ):
- foo([], [1])
+
+ if sys.version[0] == 2:
+ with self.assertRaisesRegexp(
+ TypeError,
+ 'Expected non-empty argument for parameter list_a',
+ ):
+ foo([], [1])
+ else:
+ with self.assertRaisesRegex(
+ TypeError,
+ 'Expected non-empty argument for parameter list_a',
+ ):
+ foo([], [1])
@non_empty('list_a', 'list_b')
def foo(list_a, list_b):
|
35fe55e41a6b1d22cb0ca93651771152cba831ad
|
wafer/users/migrations/0001_initial.py
|
wafer/users/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(
verbose_name='ID', serialize=False, auto_created=True,
primary_key=True)),
('contact_number', models.CharField(
max_length=16, null=True, blank=True)),
('bio', models.TextField(null=True, blank=True)),
('homepage', models.CharField(
max_length=256, null=True, blank=True)),
('twitter_handle', models.CharField(
max_length=15, null=True, blank=True)),
('github_username', models.CharField(
max_length=32, null=True, blank=True)),
('user', models.OneToOneField(
to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),
],
options={
},
bases=(models.Model,),
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.core.validators
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(
verbose_name='ID', serialize=False, auto_created=True,
primary_key=True)),
('contact_number', models.CharField(
max_length=16, null=True, blank=True)),
('bio', models.TextField(null=True, blank=True)),
('homepage', models.CharField(
max_length=256, null=True, blank=True)),
('twitter_handle', models.CharField(
max_length=15, null=True, blank=True,
validators=[
django.core.validators.RegexValidator(
'^[A-Za-z0-9_]{1,15}$',
'Incorrectly formatted twitter handle')
])),
('github_username', models.CharField(
max_length=32, null=True, blank=True)),
('user', models.OneToOneField(
to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)),
],
options={
},
bases=(models.Model,),
),
]
|
Add validator to initial user migration
|
Add validator to initial user migration
|
Python
|
isc
|
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
|
---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+import django.core.validators
from django.db import models, migrations
from django.conf import settings
@@ -24,7 +25,12 @@
('homepage', models.CharField(
max_length=256, null=True, blank=True)),
('twitter_handle', models.CharField(
- max_length=15, null=True, blank=True)),
+ max_length=15, null=True, blank=True,
+ validators=[
+ django.core.validators.RegexValidator(
+ '^[A-Za-z0-9_]{1,15}$',
+ 'Incorrectly formatted twitter handle')
+ ])),
('github_username', models.CharField(
max_length=32, null=True, blank=True)),
('user', models.OneToOneField(
|
e139cb8fc8887f98724eb8670de930230280976f
|
mclearn/tests/test_experiment.py
|
mclearn/tests/test_experiment.py
|
import os
import shutil
from .datasets import Dataset
from mclearn.experiment import ActiveExperiment
class TestExperiment:
@classmethod
def setup_class(cls):
cls.data = Dataset('wine')
cls.policies = ['passive', 'margin', 'weighted-margin', 'confidence',
'weighted-confidence', 'entropy', 'weighted-entropy',
'qbb-margin', 'qbb-kl', 'thompson', 'ocucb', 'klucb',
'exp++', 'borda', 'geometric', 'schulze']
def test_experiment(self):
for policy in self.policies:
expt = ActiveExperiment(self.data.features, self.data.target,
'wine', policy, n_iter=1)
expt.run_policies()
@classmethod
def teardown_class(cls):
if os.path.exists('results'):
shutil.rmtree('results')
|
import os
import shutil
from .datasets import Dataset
from mclearn.experiment import ActiveExperiment
class TestExperiment:
@classmethod
def setup_class(cls):
cls.data = Dataset('wine')
cls.policies = ['passive', 'margin', 'w-margin', 'confidence',
'w-confidence', 'entropy', 'w-entropy',
'qbb-margin', 'qbb-kl', 'thompson', 'ocucb', 'klucb',
'exp++', 'borda', 'geometric', 'schulze']
def test_experiment(self):
for policy in self.policies:
expt = ActiveExperiment(self.data.features, self.data.target,
'wine', policy, n_iter=1)
expt.run_policies()
@classmethod
def teardown_class(cls):
if os.path.exists('results'):
shutil.rmtree('results')
|
Update policy names in test
|
Update policy names in test
|
Python
|
bsd-3-clause
|
chengsoonong/mclass-sky,chengsoonong/mclass-sky,alasdairtran/mclearn,alasdairtran/mclearn,chengsoonong/mclass-sky,chengsoonong/mclass-sky,alasdairtran/mclearn,alasdairtran/mclearn
|
---
+++
@@ -7,8 +7,8 @@
@classmethod
def setup_class(cls):
cls.data = Dataset('wine')
- cls.policies = ['passive', 'margin', 'weighted-margin', 'confidence',
- 'weighted-confidence', 'entropy', 'weighted-entropy',
+ cls.policies = ['passive', 'margin', 'w-margin', 'confidence',
+ 'w-confidence', 'entropy', 'w-entropy',
'qbb-margin', 'qbb-kl', 'thompson', 'ocucb', 'klucb',
'exp++', 'borda', 'geometric', 'schulze']
|
59057c28746220cd0c9d9c78d4fe18b6480e8dda
|
vertica_python/vertica/messages/backend_messages/empty_query_response.py
|
vertica_python/vertica/messages/backend_messages/empty_query_response.py
|
from vertica_python.vertica.messages.message import BackendMessage
class EmptyQueryResponse(BackendMessage):
pass
EmptyQueryResponse._message_id(b'I')
|
from vertica_python.vertica.messages.message import BackendMessage
class EmptyQueryResponse(BackendMessage):
def __init__(self, data=None):
self.data = data
EmptyQueryResponse._message_id(b'I')
|
Add init for empty query response
|
Add init for empty query response
|
Python
|
apache-2.0
|
uber/vertica-python
|
---
+++
@@ -4,7 +4,8 @@
class EmptyQueryResponse(BackendMessage):
- pass
+ def __init__(self, data=None):
+ self.data = data
EmptyQueryResponse._message_id(b'I')
|
0ca662090e4b10b5fbc10b3d00fb87b861943272
|
calaccess_website/management/commands/updatedownloadswebsite.py
|
calaccess_website/management/commands/updatedownloadswebsite.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
import logging
from django.core.management import call_command
from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand
logger = logging.getLogger(__name__)
class Command(updatecommand):
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages'
def add_arguments(self, parser):
"""
Adds custom arguments specific to this command.
"""
super(Command, self).add_arguments(parser)
parser.add_argument(
"--publish",
action="store_true",
dest="publish",
default=False,
help="Publish baked content"
)
def handle(self, *args, **options):
"""
Make it happen.
"""
super(Command, self).handle(*args, **options)
self.header('Creating latest file links')
call_command('createlatestlinks')
self.header('Baking downloads-website content')
call_command('build')
if options['publish']:
self.header('Publishing baked content to S3 bucket.')
call_command('publish')
self.success("Done!")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
import logging
from django.core.management import call_command
from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand
logger = logging.getLogger(__name__)
class Command(updatecommand):
"""
Update to the latest CAL-ACCESS snapshot and bake static website pages.
"""
help = 'Update to the latest CAL-ACCESS snapshot and bake static website pages'
def add_arguments(self, parser):
"""
Adds custom arguments specific to this command.
"""
super(Command, self).add_arguments(parser)
parser.add_argument(
"--publish",
action="store_true",
dest="publish",
default=False,
help="Publish baked content"
)
def handle(self, *args, **options):
"""
Make it happen.
"""
super(Command, self).handle(*args, **options)
call_command(
'processcalaccessdata',
verbosity=self.verbosity,
)
self.header('Creating latest file links')
call_command('createlatestlinks')
self.header('Baking downloads-website content')
call_command('build')
if options['publish']:
self.header('Publishing baked content to S3 bucket.')
call_command('publish')
self.success("Done!")
|
Add processcalaccessdata to update routine
|
Add processcalaccessdata to update routine
|
Python
|
mit
|
california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website
|
---
+++
@@ -34,6 +34,10 @@
"""
super(Command, self).handle(*args, **options)
+ call_command(
+ 'processcalaccessdata',
+ verbosity=self.verbosity,
+ )
self.header('Creating latest file links')
call_command('createlatestlinks')
self.header('Baking downloads-website content')
|
4ff7f008552cb2696c5e6b933a8e9df9e2cf9db9
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='validation',
url='https://github.com/JOIVY/validation',
version='0.1.0',
author='Ben Mather',
author_email='bwhmather@bwhmather.com',
maintainer='',
license='BSD',
description=(
"A library for runtime type checking and validation of python values"
),
long_description=__doc__,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
install_requires=[
'six >= 1.10, < 2',
],
tests_require=[
'pytz',
],
packages=find_packages(),
package_data={
'': ['*.pyi'],
},
entry_points={
'console_scripts': [
],
},
test_suite='validation.tests.suite',
)
|
from setuptools import setup, find_packages
setup(
name='validation',
url='https://github.com/JOIVY/validation',
version='0.1.0',
author='Ben Mather',
author_email='bwhmather@bwhmather.com',
maintainer='',
license='BSD',
description=(
"A library for runtime type checking and validation of python values"
),
long_description=__doc__,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
install_requires=[
'six >= 1.10, < 2',
],
tests_require=[
'pytz',
],
packages=find_packages(),
package_data={
'': ['*.pyi'],
},
entry_points={
'console_scripts': [
],
},
test_suite='validation.tests.suite',
)
|
Add python 3.6 to the list of supported versions
|
Add python 3.6 to the list of supported versions
|
Python
|
apache-2.0
|
JOIVY/validation
|
---
+++
@@ -21,6 +21,7 @@
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
],
install_requires=[
'six >= 1.10, < 2',
|
45b9d6329eb3ea4d602bd7785b9085d2769dfb70
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='bankbarcode',
version='0.1.1',
packages=find_packages(),
url='https://github.com/gisce/bankbarcode',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
# We need python-barcode v0.8, to have Code128 (EAN128), not released yet
# https://bitbucket.org/whitie/python-barcode/issues/16/pypi-08-release-request
dependency_links=[
"https://bitbucket.org/whitie/python-barcode/get/6c22b96a2ca2.zip"
],
install_requires=[
'pybarcode>=0.8b1'
],
description='barcodes for financial documents'
)
|
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='bankbarcode',
version='0.1.1',
packages=find_packages(),
url='https://github.com/gisce/bankbarcode',
license='GNU Affero General Public License v3',
author='GISCE-TI, S.L.',
author_email='devel@gisce.net',
# We need python-barcode v0.8, to have Code128 (EAN128), not released yet
# https://bitbucket.org/whitie/python-barcode/issues/16/pypi-08-release-request
dependency_links=[
"https://bitbucket.org/whitie/python-barcode/get/6c22b96.zip#egg=pybarcode-0.8b1"
],
install_requires=[
'pybarcode>=0.8b1'
],
description='barcodes for financial documents'
)
|
Use egg attribute of the links
|
Use egg attribute of the links
To correct install it you must do:
$ python setup.py install
or
$ pip install --process-dependency-links bankbarcode
|
Python
|
agpl-3.0
|
gisce/bankbarcode
|
---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
+
setup(
name='bankbarcode',
@@ -13,7 +14,7 @@
# We need python-barcode v0.8, to have Code128 (EAN128), not released yet
# https://bitbucket.org/whitie/python-barcode/issues/16/pypi-08-release-request
dependency_links=[
- "https://bitbucket.org/whitie/python-barcode/get/6c22b96a2ca2.zip"
+ "https://bitbucket.org/whitie/python-barcode/get/6c22b96.zip#egg=pybarcode-0.8b1"
],
install_requires=[
'pybarcode>=0.8b1'
|
b138a3428f91cd9917b7c0943e6b63c7787084d3
|
setup.py
|
setup.py
|
import os
import sys
from setuptools import setup
from oauth2 import VERSION
if sys.version_info < (3, 0, 0):
memcache_require = "python-memcached"
else:
memcache_require = "python3-memcached"
setup(name="python-oauth2",
version=VERSION,
description="OAuth 2.0 provider for python",
long_description=open("README.rst").read(),
author="Markus Meyer",
author_email="hydrantanderwand@gmail.com",
url="https://github.com/wndhydrnt/python-oauth2",
packages=[d[0].replace("/", ".") for d in os.walk("oauth2") if not d[0].endswith("__pycache__")],
extras_require={
"memcache": [memcache_require],
"mongodb": ["pymongo"],
"redis": ["redis"]
},
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
]
)
|
import os
import sys
from setuptools import setup
from oauth2 import VERSION
if sys.version_info < (3, 0, 0):
memcache_require = "python-memcached"
else:
memcache_require = "python3-memcached"
setup(name="python-oauth2",
version=VERSION,
description="OAuth 2.0 provider for python",
long_description=open("README.rst").read(),
author="Markus Meyer",
author_email="hydrantanderwand@gmail.com",
url="https://github.com/wndhydrnt/python-oauth2",
packages=[d[0].replace("/", ".") for d in os.walk("oauth2") if not d[0].endswith("__pycache__")],
extras_require={
"memcache": [memcache_require],
"mongodb": ["pymongo"],
"redis": ["redis"]
},
classifiers=[
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
]
)
|
Add support for Python 3.5
|
Add support for Python 3.5
|
Python
|
mit
|
wndhydrnt/python-oauth2,wndhydrnt/python-oauth2,wndhydrnt/python-oauth2
|
---
+++
@@ -32,5 +32,6 @@
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
+ "Programming Language :: Python :: 3.5",
]
)
|
fa672b56da73283013e8bc93809cb112ac399c40
|
datacats/error.py
|
datacats/error.py
|
from clint.textui import colored
class DatacatsError(Exception):
def __init__(self, message, format_args=(), parent_exception=None):
self.message = message
if parent_exception:
self.message += '\n\n' + '~' * 30 + \
"\nTechnical Details:\n" + \
parent_exception.__str__() + \
'~' * 30 + '\n'
self.format_args = format_args
super(DatacatsError, self).__init__(message, format_args)
def __str__(self):
return self.message.format(*self.format_args)
def pretty_print(self):
"""
Print the error message to stdout with colors and borders
"""
print colored.blue("-" * 40)
print colored.red("DataCats: problem was encountered:")
for line in self.message.format(*self.format_args).split('\n'):
print " ", line
print colored.blue("-" * 40)
|
from clint.textui import colored
class DatacatsError(Exception):
def __init__(self, message, format_args=(), parent_exception=None):
self.message = message
if parent_exception:
self.message += '\n\n' + '~' * 30 + \
"\nTechnical Details:\n" + \
parent_exception.__str__() + \
'~' * 30 + '\n'
self.format_args = format_args
super(DatacatsError, self).__init__(message, format_args)
def __str__(self):
return self.message.format(*self.format_args)
def pretty_print(self):
"""
Print the error message to stdout with colors and borders
"""
print colored.blue("-" * 40)
print colored.red("datacats: problem was encountered:")
for line in self.message.format(*self.format_args).split('\n'):
print " ", line
print colored.blue("-" * 40)
|
Fix capitalization of datacats to match command name.
|
Fix capitalization of datacats to match command name.
|
Python
|
agpl-3.0
|
JackMc/datacats,deniszgonjanin/datacats,reneenoble/datacats,poguez/datacats,JackMc/datacats,wardi/datacats,datawagovau/datacats,dborzov/datacats,poguez/datacats,datawagovau/datacats,florianm/datacats,reneenoble/datacats,datacats/datacats,deniszgonjanin/datacats,wardi/datacats,datacats/datacats,florianm/datacats,dborzov/datacats,JJediny/datacats,JJediny/datacats
|
---
+++
@@ -21,7 +21,7 @@
Print the error message to stdout with colors and borders
"""
print colored.blue("-" * 40)
- print colored.red("DataCats: problem was encountered:")
+ print colored.red("datacats: problem was encountered:")
for line in self.message.format(*self.format_args).split('\n'):
print " ", line
print colored.blue("-" * 40)
|
3a1eaebe08243839c5e593245a2c4a6eaa716048
|
enthought/traits/ui/editors/date_editor.py
|
enthought/traits/ui/editors/date_editor.py
|
#------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
# Author: Judah De Paula
# Date: 10/7/2008
#
#------------------------------------------------------------------------------
"""
A Traits UI editor that wraps a WX calendar panel.
"""
import datetime
from enthought.traits.traits import Property
from enthought.traits.ui.basic_editor_factory import BasicEditorFactory
from enthought.traits.ui.toolkit import toolkit_object
#-- DateEditor definition -----------------------------------------------------
class DateEditor ( BasicEditorFactory ):
"""
Editor factory for date/time editors. Generates _DateEditor()s.
"""
# The editor class to be created:
klass = Property
#---------------------------------------------------------------------------
# Property getters
#---------------------------------------------------------------------------
def _get_klass(self):
""" Returns the editor class to be created.
"""
return toolkit_object('date_editor:_DateEditor')
#-- end DateEditor definition -------------------------------------------------
#-- eof -----------------------------------------------------------------------
|
#------------------------------------------------------------------------------
#
# Copyright (c) 2008, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
# Author: Judah De Paula
# Date: 10/7/2008
#
#------------------------------------------------------------------------------
"""
A Traits UI editor that wraps a WX calendar panel.
"""
import datetime
from enthought.traits.traits import Property
from enthought.traits.ui.editor_factory import EditorFactory
from enthought.traits.ui.toolkit import toolkit_object
#-- DateEditor definition -----------------------------------------------------
class DateEditor ( EditorFactory ):
"""
Editor factory for date/time editors.
"""
#---------------------------------------------------------------------------
# Trait definitions:
#---------------------------------------------------------------------------
# TODO: Placeholder for date-editor-specific traits.
pass
#-- end DateEditor definition -------------------------------------------------
#-- eof -----------------------------------------------------------------------
|
Upgrade to an EditorFactory, so Custom, Text, and Readonly can be written.
|
Upgrade to an EditorFactory, so Custom, Text, and Readonly can be written.
|
Python
|
bsd-3-clause
|
burnpanck/traits,burnpanck/traits
|
---
+++
@@ -20,26 +20,21 @@
import datetime
from enthought.traits.traits import Property
-from enthought.traits.ui.basic_editor_factory import BasicEditorFactory
+from enthought.traits.ui.editor_factory import EditorFactory
from enthought.traits.ui.toolkit import toolkit_object
#-- DateEditor definition -----------------------------------------------------
-class DateEditor ( BasicEditorFactory ):
+class DateEditor ( EditorFactory ):
"""
- Editor factory for date/time editors. Generates _DateEditor()s.
+ Editor factory for date/time editors.
"""
- # The editor class to be created:
- klass = Property
-
#---------------------------------------------------------------------------
- # Property getters
+ # Trait definitions:
#---------------------------------------------------------------------------
- def _get_klass(self):
- """ Returns the editor class to be created.
- """
- return toolkit_object('date_editor:_DateEditor')
+ # TODO: Placeholder for date-editor-specific traits.
+ pass
#-- end DateEditor definition -------------------------------------------------
|
666b011ef95ef6e82e59cc134b52fb29443ff9d8
|
iroha_cli/crypto.py
|
iroha_cli/crypto.py
|
import base64
import sha3
import os
from collections import namedtuple
class KeyPair:
def __init__(self, pub, pri):
self.private_key = pri
self.public_key = pub
from iroha_cli.crypto_ed25519 import generate_keypair_ed25519, sign_ed25519, verify_ed25519, ed25519_sha3_512, \
ed25519_sha3_256
def generate_keypair():
return generate_keypair_ed25519()
def sign(key_pair, message):
return sign_ed25519(key_pair, message)
def verify(pub_key, sig, message):
return verify_ed25519(pub_key, sig, message)
def sha3_256(message):
return ed25519_sha3_256(message)
def sha3_512(message):
return ed25519_sha3_512(message)
|
import base64
import sha3
import os
from collections import namedtuple
class KeyPair:
def __init__(self, pub, pri):
self.private_key = pri
self.public_key = pub
def raw_public_key(self):
return base64.b64decode(self.public_key)
from iroha_cli.crypto_ed25519 import generate_keypair_ed25519, sign_ed25519, verify_ed25519, ed25519_sha3_512, \
ed25519_sha3_256
def generate_keypair():
return generate_keypair_ed25519()
def sign(key_pair, message):
return sign_ed25519(key_pair, message)
def verify(pub_key, sig, message):
return verify_ed25519(pub_key, sig, message)
def sha3_256(message):
return ed25519_sha3_256(message)
def sha3_512(message):
return ed25519_sha3_512(message)
|
Add get raw key from KeyPair
|
Add get raw key from KeyPair
|
Python
|
apache-2.0
|
MizukiSonoko/iroha-cli,MizukiSonoko/iroha-cli
|
---
+++
@@ -11,6 +11,8 @@
self.private_key = pri
self.public_key = pub
+ def raw_public_key(self):
+ return base64.b64decode(self.public_key)
from iroha_cli.crypto_ed25519 import generate_keypair_ed25519, sign_ed25519, verify_ed25519, ed25519_sha3_512, \
ed25519_sha3_256
|
43783e4ff07c9a2ff9f9a11b92515d49e66abcb2
|
lms/djangoapps/open_ended_grading/controller_query_service.py
|
lms/djangoapps/open_ended_grading/controller_query_service.py
|
import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError
from django.conf import settings
from django.http import HttpResponse, Http404
log = logging.getLogger(__name__)
class ControllerQueryService(GradingService):
"""
Interface to staff grading backend.
"""
def __init__(self, config):
super(ControllerQuery, self).__init__(config)
self.check_eta_url = self.url + '/get_submission_eta/'
self.is_unique_url = self.url + '/is_name_unique/'
def check_if_name_is_unique(self, location, problem_id, course_id):
params = {
'course_id': course_id,
'location' : location,
'problem_id' : problem_id
}
response = self.get(self.is_unique_url, params)
return response
def check_for_eta(self, location):
params = {
'location' : location,
}
response = self.get(self.check_eta_url, params)
return response
|
import json
import logging
import requests
from requests.exceptions import RequestException, ConnectionError, HTTPError
import sys
from grading_service import GradingService
from grading_service import GradingServiceError
from django.conf import settings
from django.http import HttpResponse, Http404
log = logging.getLogger(__name__)
class ControllerQueryService(GradingService):
"""
Interface to staff grading backend.
"""
def __init__(self, config):
super(ControllerQuery, self).__init__(config)
self.check_eta_url = self.url + '/get_submission_eta/'
self.is_unique_url = self.url + '/is_name_unique/'
self.combined_notifications_url = self.url + '/combined_notifications/'
def check_if_name_is_unique(self, location, problem_id, course_id):
params = {
'course_id': course_id,
'location' : location,
'problem_id' : problem_id
}
response = self.get(self.is_unique_url, params)
return response
def check_for_eta(self, location):
params = {
'location' : location,
}
response = self.get(self.check_eta_url, params)
return response
def check_combined_notifications(self, course_id, student_id):
params= {
'student_id' : student_id,
'course_id' : course_id,
}
response = self.get(self.combined_notifications_url,params)
return response
|
Add in an item to check for combined notifications
|
Add in an item to check for combined notifications
|
Python
|
agpl-3.0
|
apigee/edx-platform,motion2015/edx-platform,fly19890211/edx-platform,angelapper/edx-platform,yokose-ks/edx-platform,itsjeyd/edx-platform,chudaol/edx-platform,dkarakats/edx-platform,dsajkl/123,DNFcode/edx-platform,ferabra/edx-platform,iivic/BoiseStateX,marcore/edx-platform,UXE/local-edx,cyanna/edx-platform,praveen-pal/edx-platform,teltek/edx-platform,chrisndodge/edx-platform,antonve/s4-project-mooc,Stanford-Online/edx-platform,MakeHer/edx-platform,shashank971/edx-platform,etzhou/edx-platform,sameetb-cuelogic/edx-platform-test,romain-li/edx-platform,lduarte1991/edx-platform,xingyepei/edx-platform,cecep-edu/edx-platform,nanolearningllc/edx-platform-cypress-2,wwj718/edx-platform,Semi-global/edx-platform,doganov/edx-platform,gymnasium/edx-platform,Edraak/edraak-platform,jbzdak/edx-platform,jazkarta/edx-platform,bigdatauniversity/edx-platform,alu042/edx-platform,shubhdev/edxOnBaadal,zhenzhai/edx-platform,mushtaqak/edx-platform,Softmotions/edx-platform,halvertoluke/edx-platform,doganov/edx-platform,gsehub/edx-platform,Edraak/circleci-edx-platform,proversity-org/edx-platform,deepsrijit1105/edx-platform,dkarakats/edx-platform,rismalrv/edx-platform,shabab12/edx-platform,appliedx/edx-platform,xingyepei/edx-platform,bigdatauniversity/edx-platform,zerobatu/edx-platform,dcosentino/edx-platform,devs1991/test_edx_docmode,shurihell/testasia,AkA84/edx-platform,solashirai/edx-platform,MakeHer/edx-platform,rhndg/openedx,chand3040/cloud_that,sudheerchintala/LearnEraPlatForm,Lektorium-LLC/edx-platform,doismellburning/edx-platform,EduPepperPD/pepper2013,eduNEXT/edx-platform,jelugbo/tundex,J861449197/edx-platform,vikas1885/test1,nttks/edx-platform,rue89-tech/edx-platform,vasyarv/edx-platform,proversity-org/edx-platform,Livit/Livit.Learn.EdX,utecuy/edx-platform,edx/edx-platform,TsinghuaX/edx-platform,JioEducation/edx-platform,xinjiguaike/edx-platform,caesar2164/edx-platform,franosincic/edx-platform,eestay/edx-platform,dsajkl/reqiop,pdehaye/theming-edx-platform,appsembler/edx-platform,tanmaykm/edx-platform,openfun/edx-platform,JCBarahona/edX,rhndg/openedx,shubhdev/edx-platform,edry/edx-platform,rismalrv/edx-platform,cognitiveclass/edx-platform,gymnasium/edx-platform,playm2mboy/edx-platform,benpatterson/edx-platform,shabab12/edx-platform,zerobatu/edx-platform,abdoosh00/edx-rtl-final,nanolearning/edx-platform,nagyistoce/edx-platform,zofuthan/edx-platform,vasyarv/edx-platform,pomegranited/edx-platform,rue89-tech/edx-platform,torchingloom/edx-platform,nanolearningllc/edx-platform-cypress,pdehaye/theming-edx-platform,apigee/edx-platform,rationalAgent/edx-platform-custom,Edraak/circleci-edx-platform,Endika/edx-platform,LearnEra/LearnEraPlaftform,longmen21/edx-platform,dkarakats/edx-platform,bdero/edx-platform,doismellburning/edx-platform,ahmedaljazzar/edx-platform,B-MOOC/edx-platform,jazztpt/edx-platform,EduPepperPDTesting/pepper2013-testing,chudaol/edx-platform,BehavioralInsightsTeam/edx-platform,kalebhartje/schoolboost,PepperPD/edx-pepper-platform,mahendra-r/edx-platform,nanolearningllc/edx-platform-cypress,DNFcode/edx-platform,eduNEXT/edunext-platform,jolyonb/edx-platform,mbareta/edx-platform-ft,deepsrijit1105/edx-platform,Softmotions/edx-platform,SravanthiSinha/edx-platform,J861449197/edx-platform,naresh21/synergetics-edx-platform,morenopc/edx-platform,torchingloom/edx-platform,SravanthiSinha/edx-platform,IONISx/edx-platform,nagyistoce/edx-platform,ahmadiga/min_edx,cpennington/edx-platform,jazkarta/edx-platform-for-isc,openfun/edx-platform,chand3040/cloud_that,yokose-ks/edx-platform,rismalrv/edx-platform,hastexo/edx-platform,hastexo/edx-platform,RPI-OPENEDX/edx-platform,PepperPD/edx-pepper-platform,franosincic/edx-platform,morpheby/levelup-by,amir-qayyum-khan/edx-platform,mjirayu/sit_academy,a-parhom/edx-platform,B-MOOC/edx-platform,apigee/edx-platform,benpatterson/edx-platform,ahmadio/edx-platform,pepeportela/edx-platform,hkawasaki/kawasaki-aio8-0,IONISx/edx-platform,tiagochiavericosta/edx-platform,CredoReference/edx-platform,vismartltd/edx-platform,marcore/edx-platform,eduNEXT/edx-platform,ovnicraft/edx-platform,auferack08/edx-platform,torchingloom/edx-platform,dcosentino/edx-platform,motion2015/a3,ahmadiga/min_edx,rismalrv/edx-platform,wwj718/edx-platform,IONISx/edx-platform,beni55/edx-platform,hamzehd/edx-platform,gymnasium/edx-platform,xuxiao19910803/edx,don-github/edx-platform,jbassen/edx-platform,atsolakid/edx-platform,ferabra/edx-platform,Softmotions/edx-platform,Semi-global/edx-platform,rationalAgent/edx-platform-custom,nikolas/edx-platform,stvstnfrd/edx-platform,arifsetiawan/edx-platform,hkawasaki/kawasaki-aio8-2,polimediaupv/edx-platform,IITBinterns13/edx-platform-dev,WatanabeYasumasa/edx-platform,mbareta/edx-platform-ft,msegado/edx-platform,msegado/edx-platform,appliedx/edx-platform,SivilTaram/edx-platform,nttks/jenkins-test,Lektorium-LLC/edx-platform,miptliot/edx-platform,UXE/local-edx,jjmiranda/edx-platform,kmoocdev/edx-platform,nanolearning/edx-platform,ZLLab-Mooc/edx-platform,ubc/edx-platform,pelikanchik/edx-platform,ovnicraft/edx-platform,miptliot/edx-platform,ahmedaljazzar/edx-platform,BehavioralInsightsTeam/edx-platform,Shrhawk/edx-platform,ahmadiga/min_edx,syjeon/new_edx,mahendra-r/edx-platform,andyzsf/edx,ampax/edx-platform-backup,beni55/edx-platform,ahmadio/edx-platform,BehavioralInsightsTeam/edx-platform,jruiperezv/ANALYSE,syjeon/new_edx,polimediaupv/edx-platform,philanthropy-u/edx-platform,y12uc231/edx-platform,motion2015/a3,ubc/edx-platform,mcgachey/edx-platform,vasyarv/edx-platform,xuxiao19910803/edx-platform,hkawasaki/kawasaki-aio8-1,romain-li/edx-platform,fintech-circle/edx-platform,chand3040/cloud_that,analyseuc3m/ANALYSE-v1,xinjiguaike/edx-platform,ampax/edx-platform-backup,stvstnfrd/edx-platform,itsjeyd/edx-platform,analyseuc3m/ANALYSE-v1,jelugbo/tundex,iivic/BoiseStateX,eduNEXT/edx-platform,cecep-edu/edx-platform,Livit/Livit.Learn.EdX,dcosentino/edx-platform,tiagochiavericosta/edx-platform,raccoongang/edx-platform,stvstnfrd/edx-platform,utecuy/edx-platform,ahmedaljazzar/edx-platform,jonathan-beard/edx-platform,4eek/edx-platform,cognitiveclass/edx-platform,zubair-arbi/edx-platform,Shrhawk/edx-platform,ak2703/edx-platform,morenopc/edx-platform,LICEF/edx-platform,shubhdev/openedx,hkawasaki/kawasaki-aio8-0,mushtaqak/edx-platform,Edraak/edx-platform,jonathan-beard/edx-platform,chauhanhardik/populo_2,abdoosh00/edraak,UOMx/edx-platform,mtlchun/edx,xuxiao19910803/edx-platform,jswope00/GAI,auferack08/edx-platform,appsembler/edx-platform,RPI-OPENEDX/edx-platform,kamalx/edx-platform,zhenzhai/edx-platform,martynovp/edx-platform,ampax/edx-platform-backup,fly19890211/edx-platform,devs1991/test_edx_docmode,jazztpt/edx-platform,devs1991/test_edx_docmode,openfun/edx-platform,chrisndodge/edx-platform,prarthitm/edxplatform,SravanthiSinha/edx-platform,don-github/edx-platform,analyseuc3m/ANALYSE-v1,jazztpt/edx-platform,rationalAgent/edx-platform-custom,Edraak/edx-platform,LearnEra/LearnEraPlaftform,bigdatauniversity/edx-platform,tiagochiavericosta/edx-platform,andyzsf/edx,prarthitm/edxplatform,beni55/edx-platform,xuxiao19910803/edx-platform,jruiperezv/ANALYSE,jolyonb/edx-platform,miptliot/edx-platform,edx/edx-platform,shubhdev/openedx,yokose-ks/edx-platform,zubair-arbi/edx-platform,unicri/edx-platform,olexiim/edx-platform,knehez/edx-platform,jamesblunt/edx-platform,kalebhartje/schoolboost,10clouds/edx-platform,tiagochiavericosta/edx-platform,edry/edx-platform,shubhdev/edxOnBaadal,nagyistoce/edx-platform,morenopc/edx-platform,valtech-mooc/edx-platform,antoviaque/edx-platform,LICEF/edx-platform,EduPepperPDTesting/pepper2013-testing,itsjeyd/edx-platform,kxliugang/edx-platform,jbzdak/edx-platform,wwj718/edx-platform,zubair-arbi/edx-platform,jazkarta/edx-platform-for-isc,ak2703/edx-platform,eduNEXT/edx-platform,vismartltd/edx-platform,MSOpenTech/edx-platform,vismartltd/edx-platform,jolyonb/edx-platform,openfun/edx-platform,edry/edx-platform,longmen21/edx-platform,ak2703/edx-platform,zofuthan/edx-platform,Edraak/circleci-edx-platform,philanthropy-u/edx-platform,motion2015/edx-platform,hkawasaki/kawasaki-aio8-1,TeachAtTUM/edx-platform,procangroup/edx-platform,peterm-itr/edx-platform,dsajkl/123,edx/edx-platform,nagyistoce/edx-platform,jamiefolsom/edx-platform,doganov/edx-platform,pabloborrego93/edx-platform,knehez/edx-platform,pomegranited/edx-platform,pomegranited/edx-platform,polimediaupv/edx-platform,cselis86/edx-platform,jbassen/edx-platform,jolyonb/edx-platform,Semi-global/edx-platform,mushtaqak/edx-platform,cognitiveclass/edx-platform,motion2015/a3,EDUlib/edx-platform,abdoosh00/edraak,AkA84/edx-platform,alexthered/kienhoc-platform,Shrhawk/edx-platform,franosincic/edx-platform,gsehub/edx-platform,chauhanhardik/populo,defance/edx-platform,bdero/edx-platform,louyihua/edx-platform,LICEF/edx-platform,cyanna/edx-platform,ZLLab-Mooc/edx-platform,cpennington/edx-platform,peterm-itr/edx-platform,beacloudgenius/edx-platform,cpennington/edx-platform,kursitet/edx-platform,shubhdev/openedx,sameetb-cuelogic/edx-platform-test,MSOpenTech/edx-platform,xingyepei/edx-platform,devs1991/test_edx_docmode,EduPepperPD/pepper2013,vismartltd/edx-platform,jelugbo/tundex,Ayub-Khan/edx-platform,devs1991/test_edx_docmode,Edraak/edx-platform,bitifirefly/edx-platform,shashank971/edx-platform,chauhanhardik/populo_2,jswope00/GAI,rhndg/openedx,Lektorium-LLC/edx-platform,etzhou/edx-platform,morpheby/levelup-by,jbzdak/edx-platform,zerobatu/edx-platform,Kalyzee/edx-platform,mahendra-r/edx-platform,nttks/edx-platform,chand3040/cloud_that,ahmadiga/min_edx,hastexo/edx-platform,MakeHer/edx-platform,procangroup/edx-platform,halvertoluke/edx-platform,benpatterson/edx-platform,pepeportela/edx-platform,kxliugang/edx-platform,DNFcode/edx-platform,Unow/edx-platform,rhndg/openedx,deepsrijit1105/edx-platform,mitocw/edx-platform,xingyepei/edx-platform,Ayub-Khan/edx-platform,cselis86/edx-platform,IndonesiaX/edx-platform,y12uc231/edx-platform,cselis86/edx-platform,deepsrijit1105/edx-platform,OmarIthawi/edx-platform,EDUlib/edx-platform,Ayub-Khan/edx-platform,edx/edx-platform,ampax/edx-platform,utecuy/edx-platform,EduPepperPDTesting/pepper2013-testing,morpheby/levelup-by,WatanabeYasumasa/edx-platform,iivic/BoiseStateX,Edraak/edx-platform,edx-solutions/edx-platform,Kalyzee/edx-platform,a-parhom/edx-platform,EduPepperPD/pepper2013,doismellburning/edx-platform,edx-solutions/edx-platform,zubair-arbi/edx-platform,UXE/local-edx,shurihell/testasia,jruiperezv/ANALYSE,chauhanhardik/populo,TsinghuaX/edx-platform,carsongee/edx-platform,Endika/edx-platform,motion2015/a3,jzoldak/edx-platform,angelapper/edx-platform,nanolearning/edx-platform,10clouds/edx-platform,longmen21/edx-platform,AkA84/edx-platform,bigdatauniversity/edx-platform,shashank971/edx-platform,ahmadio/edx-platform,iivic/BoiseStateX,hmcmooc/muddx-platform,pdehaye/theming-edx-platform,RPI-OPENEDX/edx-platform,alu042/edx-platform,caesar2164/edx-platform,CredoReference/edx-platform,mitocw/edx-platform,ubc/edx-platform,cognitiveclass/edx-platform,MSOpenTech/edx-platform,jamesblunt/edx-platform,jamiefolsom/edx-platform,Endika/edx-platform,UOMx/edx-platform,knehez/edx-platform,B-MOOC/edx-platform,wwj718/edx-platform,zadgroup/edx-platform,SivilTaram/edx-platform,chudaol/edx-platform,ak2703/edx-platform,ovnicraft/edx-platform,jruiperezv/ANALYSE,andyzsf/edx,chauhanhardik/populo,xuxiao19910803/edx,ampax/edx-platform,SravanthiSinha/edx-platform,jelugbo/tundex,nanolearningllc/edx-platform-cypress,shurihell/testasia,unicri/edx-platform,Stanford-Online/edx-platform,eestay/edx-platform,devs1991/test_edx_docmode,IndonesiaX/edx-platform,ampax/edx-platform-backup,Kalyzee/edx-platform,adoosii/edx-platform,arifsetiawan/edx-platform,mitocw/edx-platform,EduPepperPD/pepper2013,waheedahmed/edx-platform,sudheerchintala/LearnEraPlatForm,mbareta/edx-platform-ft,sameetb-cuelogic/edx-platform-test,AkA84/edx-platform,Softmotions/edx-platform,ferabra/edx-platform,bdero/edx-platform,kxliugang/edx-platform,waheedahmed/edx-platform,IITBinterns13/edx-platform-dev,polimediaupv/edx-platform,zadgroup/edx-platform,pdehaye/theming-edx-platform,ovnicraft/edx-platform,hkawasaki/kawasaki-aio8-1,arifsetiawan/edx-platform,ubc/edx-platform,jelugbo/tundex,JioEducation/edx-platform,beni55/edx-platform,kxliugang/edx-platform,kxliugang/edx-platform,kamalx/edx-platform,romain-li/edx-platform,naresh21/synergetics-edx-platform,hkawasaki/kawasaki-aio8-2,bitifirefly/edx-platform,jazkarta/edx-platform,syjeon/new_edx,4eek/edx-platform,nanolearningllc/edx-platform-cypress-2,nanolearningllc/edx-platform-cypress-2,marcore/edx-platform,jonathan-beard/edx-platform,defance/edx-platform,leansoft/edx-platform,abdoosh00/edx-rtl-final,knehez/edx-platform,olexiim/edx-platform,arbrandes/edx-platform,devs1991/test_edx_docmode,chauhanhardik/populo_2,kursitet/edx-platform,caesar2164/edx-platform,kamalx/edx-platform,angelapper/edx-platform,jamiefolsom/edx-platform,SivilTaram/edx-platform,EduPepperPD/pepper2013,CourseTalk/edx-platform,simbs/edx-platform,edry/edx-platform,naresh21/synergetics-edx-platform,solashirai/edx-platform,rue89-tech/edx-platform,antonve/s4-project-mooc,pku9104038/edx-platform,Unow/edx-platform,analyseuc3m/ANALYSE-v1,wwj718/ANALYSE,MSOpenTech/edx-platform,torchingloom/edx-platform,alexthered/kienhoc-platform,hmcmooc/muddx-platform,teltek/edx-platform,nikolas/edx-platform,ampax/edx-platform-backup,msegado/edx-platform,playm2mboy/edx-platform,ampax/edx-platform,raccoongang/edx-platform,franosincic/edx-platform,alu042/edx-platform,halvertoluke/edx-platform,xuxiao19910803/edx-platform,arifsetiawan/edx-platform,shurihell/testasia,DNFcode/edx-platform,mushtaqak/edx-platform,zhenzhai/edx-platform,dsajkl/reqiop,mjg2203/edx-platform-seas,shubhdev/openedx,WatanabeYasumasa/edx-platform,IITBinterns13/edx-platform-dev,cyanna/edx-platform,jamesblunt/edx-platform,leansoft/edx-platform,synergeticsedx/deployment-wipro,appliedx/edx-platform,etzhou/edx-platform,Kalyzee/edx-platform,inares/edx-platform,carsongee/edx-platform,arbrandes/edx-platform,unicri/edx-platform,OmarIthawi/edx-platform,shabab12/edx-platform,eestay/edx-platform,hamzehd/edx-platform,cyanna/edx-platform,hkawasaki/kawasaki-aio8-0,B-MOOC/edx-platform,kmoocdev2/edx-platform,fly19890211/edx-platform,waheedahmed/edx-platform,tanmaykm/edx-platform,jswope00/griffinx,rationalAgent/edx-platform-custom,msegado/edx-platform,dcosentino/edx-platform,4eek/edx-platform,jswope00/griffinx,praveen-pal/edx-platform,Edraak/edx-platform,nanolearningllc/edx-platform-cypress,kursitet/edx-platform,jzoldak/edx-platform,miptliot/edx-platform,mtlchun/edx,rue89-tech/edx-platform,amir-qayyum-khan/edx-platform,motion2015/edx-platform,martynovp/edx-platform,TsinghuaX/edx-platform,appsembler/edx-platform,kmoocdev/edx-platform,doganov/edx-platform,philanthropy-u/edx-platform,caesar2164/edx-platform,dkarakats/edx-platform,eestay/edx-platform,shubhdev/edxOnBaadal,xinjiguaike/edx-platform,jazkarta/edx-platform,Stanford-Online/edx-platform,etzhou/edx-platform,mjirayu/sit_academy,J861449197/edx-platform,synergeticsedx/deployment-wipro,polimediaupv/edx-platform,xinjiguaike/edx-platform,defance/edx-platform,martynovp/edx-platform,arbrandes/edx-platform,cecep-edu/edx-platform,nanolearning/edx-platform,shurihell/testasia,solashirai/edx-platform,zofuthan/edx-platform,abdoosh00/edraak,shabab12/edx-platform,chand3040/cloud_that,nttks/edx-platform,defance/edx-platform,don-github/edx-platform,cecep-edu/edx-platform,dcosentino/edx-platform,mcgachey/edx-platform,amir-qayyum-khan/edx-platform,prarthitm/edxplatform,chrisndodge/edx-platform,alexthered/kienhoc-platform,unicri/edx-platform,auferack08/edx-platform,dkarakats/edx-platform,mtlchun/edx,beni55/edx-platform,syjeon/new_edx,jswope00/griffinx,chauhanhardik/populo,xingyepei/edx-platform,pabloborrego93/edx-platform,kmoocdev2/edx-platform,kmoocdev2/edx-platform,valtech-mooc/edx-platform,sudheerchintala/LearnEraPlatForm,ferabra/edx-platform,jruiperezv/ANALYSE,atsolakid/edx-platform,ahmadio/edx-platform,unicri/edx-platform,valtech-mooc/edx-platform,jonathan-beard/edx-platform,Ayub-Khan/edx-platform,nttks/edx-platform,devs1991/test_edx_docmode,dsajkl/reqiop,atsolakid/edx-platform,lduarte1991/edx-platform,fintech-circle/edx-platform,apigee/edx-platform,vikas1885/test1,proversity-org/edx-platform,ahmadiga/min_edx,rismalrv/edx-platform,eestay/edx-platform,nanolearning/edx-platform,ubc/edx-platform,carsongee/edx-platform,iivic/BoiseStateX,chauhanhardik/populo,vikas1885/test1,shubhdev/edxOnBaadal,10clouds/edx-platform,shubhdev/edx-platform,OmarIthawi/edx-platform,DefyVentures/edx-platform,abdoosh00/edraak,jzoldak/edx-platform,DefyVentures/edx-platform,doismellburning/edx-platform,kamalx/edx-platform,ESOedX/edx-platform,kalebhartje/schoolboost,wwj718/ANALYSE,LICEF/edx-platform,mcgachey/edx-platform,vikas1885/test1,y12uc231/edx-platform,Stanford-Online/edx-platform,shubhdev/edx-platform,hamzehd/edx-platform,kursitet/edx-platform,UOMx/edx-platform,xinjiguaike/edx-platform,xuxiao19910803/edx,shubhdev/edx-platform,wwj718/ANALYSE,hkawasaki/kawasaki-aio8-0,utecuy/edx-platform,antonve/s4-project-mooc,zadgroup/edx-platform,msegado/edx-platform,pku9104038/edx-platform,praveen-pal/edx-platform,vasyarv/edx-platform,jamiefolsom/edx-platform,zubair-arbi/edx-platform,peterm-itr/edx-platform,naresh21/synergetics-edx-platform,IndonesiaX/edx-platform,ak2703/edx-platform,eemirtekin/edx-platform,jswope00/griffinx,louyihua/edx-platform,RPI-OPENEDX/edx-platform,IndonesiaX/edx-platform,kmoocdev/edx-platform,rationalAgent/edx-platform-custom,jjmiranda/edx-platform,leansoft/edx-platform,ahmadio/edx-platform,bitifirefly/edx-platform,pelikanchik/edx-platform,dsajkl/123,shubhdev/edx-platform,shashank971/edx-platform,alu042/edx-platform,CourseTalk/edx-platform,adoosii/edx-platform,gsehub/edx-platform,jamesblunt/edx-platform,jbassen/edx-platform,Edraak/edraak-platform,leansoft/edx-platform,ZLLab-Mooc/edx-platform,bigdatauniversity/edx-platform,vismartltd/edx-platform,mtlchun/edx,jazkarta/edx-platform-for-isc,eemirtekin/edx-platform,chauhanhardik/populo_2,CredoReference/edx-platform,atsolakid/edx-platform,andyzsf/edx,fly19890211/edx-platform,cselis86/edx-platform,olexiim/edx-platform,lduarte1991/edx-platform,jamiefolsom/edx-platform,gsehub/edx-platform,simbs/edx-platform,jjmiranda/edx-platform,chudaol/edx-platform,cecep-edu/edx-platform,ovnicraft/edx-platform,utecuy/edx-platform,pepeportela/edx-platform,vikas1885/test1,10clouds/edx-platform,adoosii/edx-platform,xuxiao19910803/edx,yokose-ks/edx-platform,nanolearningllc/edx-platform-cypress-2,nttks/edx-platform,auferack08/edx-platform,proversity-org/edx-platform,valtech-mooc/edx-platform,peterm-itr/edx-platform,dsajkl/reqiop,DNFcode/edx-platform,pelikanchik/edx-platform,mitocw/edx-platform,JioEducation/edx-platform,zofuthan/edx-platform,teltek/edx-platform,simbs/edx-platform,Edraak/edraak-platform,JCBarahona/edX,mahendra-r/edx-platform,EduPepperPDTesting/pepper2013-testing,jzoldak/edx-platform,MSOpenTech/edx-platform,adoosii/edx-platform,nttks/jenkins-test,inares/edx-platform,Unow/edx-platform,stvstnfrd/edx-platform,kamalx/edx-platform,MakeHer/edx-platform,eduNEXT/edunext-platform,jazkarta/edx-platform,benpatterson/edx-platform,zerobatu/edx-platform,ferabra/edx-platform,chudaol/edx-platform,morpheby/levelup-by,motion2015/edx-platform,mbareta/edx-platform-ft,mjirayu/sit_academy,ZLLab-Mooc/edx-platform,AkA84/edx-platform,TsinghuaX/edx-platform,romain-li/edx-platform,morenopc/edx-platform,amir-qayyum-khan/edx-platform,mjirayu/sit_academy,nttks/jenkins-test,a-parhom/edx-platform,olexiim/edx-platform,marcore/edx-platform,nagyistoce/edx-platform,Shrhawk/edx-platform,jswope00/GAI,appsembler/edx-platform,hmcmooc/muddx-platform,mcgachey/edx-platform,MakeHer/edx-platform,cognitiveclass/edx-platform,DefyVentures/edx-platform,Edraak/circleci-edx-platform,martynovp/edx-platform,WatanabeYasumasa/edx-platform,antoviaque/edx-platform,antonve/s4-project-mooc,pepeportela/edx-platform,philanthropy-u/edx-platform,motion2015/a3,rue89-tech/edx-platform,mjg2203/edx-platform-seas,mjg2203/edx-platform-seas,beacloudgenius/edx-platform,pabloborrego93/edx-platform,mahendra-r/edx-platform,TeachAtTUM/edx-platform,jbzdak/edx-platform,inares/edx-platform,y12uc231/edx-platform,TeachAtTUM/edx-platform,IONISx/edx-platform,shashank971/edx-platform,y12uc231/edx-platform,playm2mboy/edx-platform,JioEducation/edx-platform,jazkarta/edx-platform-for-isc,jazztpt/edx-platform,nttks/jenkins-test,playm2mboy/edx-platform,mjg2203/edx-platform-seas,chauhanhardik/populo_2,LearnEra/LearnEraPlaftform,CredoReference/edx-platform,sameetb-cuelogic/edx-platform-test,appliedx/edx-platform,raccoongang/edx-platform,J861449197/edx-platform,nanolearningllc/edx-platform-cypress-2,DefyVentures/edx-platform,fly19890211/edx-platform,eduNEXT/edunext-platform,fintech-circle/edx-platform,cpennington/edx-platform,nikolas/edx-platform,kalebhartje/schoolboost,inares/edx-platform,beacloudgenius/edx-platform,ESOedX/edx-platform,abdoosh00/edx-rtl-final,JCBarahona/edX,prarthitm/edxplatform,4eek/edx-platform,kmoocdev2/edx-platform,pomegranited/edx-platform,abdoosh00/edx-rtl-final,wwj718/ANALYSE,franosincic/edx-platform,hamzehd/edx-platform,nanolearningllc/edx-platform-cypress,shubhdev/edxOnBaadal,halvertoluke/edx-platform,arifsetiawan/edx-platform,sameetb-cuelogic/edx-platform-test,nikolas/edx-platform,kalebhartje/schoolboost,hkawasaki/kawasaki-aio8-2,martynovp/edx-platform,PepperPD/edx-pepper-platform,Semi-global/edx-platform,zhenzhai/edx-platform,teltek/edx-platform,EduPepperPDTesting/pepper2013-testing,inares/edx-platform,romain-li/edx-platform,Edraak/edraak-platform,antoviaque/edx-platform,CourseTalk/edx-platform,waheedahmed/edx-platform,simbs/edx-platform,Ayub-Khan/edx-platform,hastexo/edx-platform,RPI-OPENEDX/edx-platform,pomegranited/edx-platform,IndonesiaX/edx-platform,EDUlib/edx-platform,dsajkl/123,procangroup/edx-platform,praveen-pal/edx-platform,4eek/edx-platform,kursitet/edx-platform,mjirayu/sit_academy,PepperPD/edx-pepper-platform,eemirtekin/edx-platform,ampax/edx-platform,halvertoluke/edx-platform,fintech-circle/edx-platform,jbassen/edx-platform,SravanthiSinha/edx-platform,solashirai/edx-platform,pku9104038/edx-platform,kmoocdev/edx-platform,SivilTaram/edx-platform,hmcmooc/muddx-platform,vasyarv/edx-platform,knehez/edx-platform,simbs/edx-platform,gymnasium/edx-platform,EDUlib/edx-platform,wwj718/ANALYSE,angelapper/edx-platform,chrisndodge/edx-platform,mtlchun/edx,IITBinterns13/edx-platform-dev,ESOedX/edx-platform,BehavioralInsightsTeam/edx-platform,a-parhom/edx-platform,motion2015/edx-platform,synergeticsedx/deployment-wipro,solashirai/edx-platform,JCBarahona/edX,Lektorium-LLC/edx-platform,dsajkl/123,edx-solutions/edx-platform,antonve/s4-project-mooc,EduPepperPDTesting/pepper2013-testing,wwj718/edx-platform,olexiim/edx-platform,OmarIthawi/edx-platform,edry/edx-platform,J861449197/edx-platform,SivilTaram/edx-platform,JCBarahona/edX,nikolas/edx-platform,pelikanchik/edx-platform,Semi-global/edx-platform,valtech-mooc/edx-platform,shubhdev/openedx,zadgroup/edx-platform,Livit/Livit.Learn.EdX,Edraak/circleci-edx-platform,DefyVentures/edx-platform,IONISx/edx-platform,jswope00/griffinx,longmen21/edx-platform,bitifirefly/edx-platform,UOMx/edx-platform,louyihua/edx-platform,jbassen/edx-platform,beacloudgenius/edx-platform,UXE/local-edx,B-MOOC/edx-platform,raccoongang/edx-platform,appliedx/edx-platform,zadgroup/edx-platform,alexthered/kienhoc-platform,zofuthan/edx-platform,playm2mboy/edx-platform,xuxiao19910803/edx-platform,jonathan-beard/edx-platform,rhndg/openedx,ahmedaljazzar/edx-platform,bdero/edx-platform,etzhou/edx-platform,pabloborrego93/edx-platform,tiagochiavericosta/edx-platform,pku9104038/edx-platform,Endika/edx-platform,carsongee/edx-platform,tanmaykm/edx-platform,xuxiao19910803/edx,zhenzhai/edx-platform,procangroup/edx-platform,longmen21/edx-platform,morenopc/edx-platform,tanmaykm/edx-platform,mushtaqak/edx-platform,benpatterson/edx-platform,waheedahmed/edx-platform,cyanna/edx-platform,leansoft/edx-platform,PepperPD/edx-pepper-platform,sudheerchintala/LearnEraPlatForm,jazkarta/edx-platform,zerobatu/edx-platform,eemirtekin/edx-platform,alexthered/kienhoc-platform,jamesblunt/edx-platform,hkawasaki/kawasaki-aio8-2,adoosii/edx-platform,kmoocdev2/edx-platform,cselis86/edx-platform,Shrhawk/edx-platform,beacloudgenius/edx-platform,jbzdak/edx-platform,mcgachey/edx-platform,doganov/edx-platform,edx-solutions/edx-platform,LICEF/edx-platform,eemirtekin/edx-platform,doismellburning/edx-platform,bitifirefly/edx-platform,Livit/Livit.Learn.EdX,don-github/edx-platform,Kalyzee/edx-platform,louyihua/edx-platform,hamzehd/edx-platform,arbrandes/edx-platform,CourseTalk/edx-platform,synergeticsedx/deployment-wipro,antoviaque/edx-platform,Softmotions/edx-platform,jazkarta/edx-platform-for-isc,jswope00/GAI,ZLLab-Mooc/edx-platform,torchingloom/edx-platform,openfun/edx-platform,LearnEra/LearnEraPlaftform,hkawasaki/kawasaki-aio8-1,nttks/jenkins-test,jazztpt/edx-platform,TeachAtTUM/edx-platform,jjmiranda/edx-platform,ESOedX/edx-platform,don-github/edx-platform,atsolakid/edx-platform,eduNEXT/edunext-platform,kmoocdev/edx-platform,lduarte1991/edx-platform,Unow/edx-platform,yokose-ks/edx-platform,itsjeyd/edx-platform
|
---
+++
@@ -19,6 +19,7 @@
super(ControllerQuery, self).__init__(config)
self.check_eta_url = self.url + '/get_submission_eta/'
self.is_unique_url = self.url + '/is_name_unique/'
+ self.combined_notifications_url = self.url + '/combined_notifications/'
def check_if_name_is_unique(self, location, problem_id, course_id):
params = {
@@ -35,3 +36,12 @@
}
response = self.get(self.check_eta_url, params)
return response
+
+ def check_combined_notifications(self, course_id, student_id):
+ params= {
+ 'student_id' : student_id,
+ 'course_id' : course_id,
+ }
+ response = self.get(self.combined_notifications_url,params)
+ return response
+
|
24ab943904339b5479912b8b70a7a2a0433c60da
|
src/interpreter/interpreter.py
|
src/interpreter/interpreter.py
|
'''
Created on 03.02.2016.
@author: Lazar
'''
from textx.metamodel import metamodel_from_file
from concepts.layout import Layout
from concepts.object import Object
from concepts.property import Property
from concepts.selector_object import SelectorObject, selector_object_processor
from concepts.selector_view import SelectorView
from concepts.view import View
from concepts.page import page_processor
if __name__ == "__main__":
builtins = {x : View(None,x, []) for x in View.basic_type_names}
layouts = {
'border' : Layout('border', ['top','bottom','center','left','right'], None),
'grid' : Layout('grid', [], None)
}
builtins.update(layouts)
obj_processors = {
'SelectorObject' : selector_object_processor,
'Page' : page_processor
}
my_mm = metamodel_from_file('../grammar/grammar.tx',
classes = [
View,
Object,
Property,
SelectorObject,
SelectorView
],
builtins = builtins,
debug = False)
my_mm.register_obj_processors(obj_processors)
# Create model
my_model = my_mm.model_from_file('../../test/test.gn')
my_model
|
'''
Created on 03.02.2016.
@author: Lazar
'''
import os
from textx.metamodel import metamodel_from_file
from concepts.layout import Layout
from concepts.object import Object
from concepts.property import Property
from concepts.selector_object import SelectorObject, selector_object_processor
from concepts.selector_view import SelectorView
from concepts.view import View
from concepts.page import page_processor
if __name__ == "__main__":
builtins = {x : View(None,x, []) for x in View.basic_type_names}
layouts = {
'border' : Layout('border', ['top','bottom','center',
'left','right'], None),
'grid' : Layout('grid', [], None)
}
builtins.update(layouts)
obj_processors = {
'SelectorObject' : selector_object_processor,
'Page' : page_processor
}
this_dir = os.path.dirname(__file__)
my_mm = metamodel_from_file(os.path.join(this_dir,
'..', 'grammar', 'grammar.tx'),
classes = [
View,
Object,
Property,
SelectorObject,
SelectorView
],
builtins = builtins,
debug = False)
my_mm.register_obj_processors(obj_processors)
# Create model
my_model = my_mm.model_from_file(os.path.join(this_dir,
'..', '..',
'test', 'test.gn'))
print(my_model.entity)
|
Use os.path.join to join paths. Use relative paths.
|
Use os.path.join to join paths. Use relative paths.
|
Python
|
mit
|
theshammy/GenAn,theshammy/GenAn,theshammy/GenAn
|
---
+++
@@ -3,6 +3,7 @@
@author: Lazar
'''
+import os
from textx.metamodel import metamodel_from_file
from concepts.layout import Layout
@@ -15,33 +16,39 @@
if __name__ == "__main__":
-
+
builtins = {x : View(None,x, []) for x in View.basic_type_names}
layouts = {
- 'border' : Layout('border', ['top','bottom','center','left','right'], None),
+ 'border' : Layout('border', ['top','bottom','center',
+ 'left','right'], None),
'grid' : Layout('grid', [], None)
}
-
- builtins.update(layouts)
-
+
+ builtins.update(layouts)
+
obj_processors = {
'SelectorObject' : selector_object_processor,
'Page' : page_processor
}
-
- my_mm = metamodel_from_file('../grammar/grammar.tx',
+
+ this_dir = os.path.dirname(__file__)
+ my_mm = metamodel_from_file(os.path.join(this_dir,
+ '..', 'grammar', 'grammar.tx'),
classes = [
- View,
- Object,
- Property,
- SelectorObject,
+ View,
+ Object,
+ Property,
+ SelectorObject,
SelectorView
],
builtins = builtins,
debug = False)
-
+
my_mm.register_obj_processors(obj_processors)
# Create model
- my_model = my_mm.model_from_file('../../test/test.gn')
- my_model
-
+ my_model = my_mm.model_from_file(os.path.join(this_dir,
+ '..', '..',
+ 'test', 'test.gn'))
+
+ print(my_model.entity)
+
|
b11399713d004a95da035ffceed9a1db8b837d11
|
diffs/__init__.py
|
diffs/__init__.py
|
from __future__ import absolute_import, unicode_literals
__version__ = '0.1.6'
default_app_config = 'diffs.apps.DiffLogConfig'
klasses_to_connect = []
def register(cls):
"""
Decorator function that registers a class to record diffs.
@diffs.register
class ExampleModel(models.Model):
...
"""
from django.apps import apps as django_apps
from dirtyfields import DirtyFieldsMixin
from .models import DiffModelManager, DiffModelDescriptor
from .signals import connect
# Hack to add dirtyfieldsmixin automatically
if DirtyFieldsMixin not in cls.__bases__:
cls.__bases__ = (DirtyFieldsMixin,) + cls.__bases__
cls.add_to_class('diffs', DiffModelDescriptor(DiffModelManager()))
if not django_apps.ready:
klasses_to_connect.append(cls)
else:
connect(cls)
return cls
def get_connection():
"""Helper method to get redis connection configured by settings"""
import redis
import fakeredis
from .settings import diffs_settings
if not diffs_settings['test_mode']:
return redis.Redis(**diffs_settings['redis'])
else:
return fakeredis.FakeRedis()
|
from __future__ import absolute_import, unicode_literals
__version__ = '0.1.7'
default_app_config = 'diffs.apps.DiffLogConfig'
klasses_to_connect = []
def register(cls):
"""
Decorator function that registers a class to record diffs.
@diffs.register
class ExampleModel(models.Model):
...
"""
from django.apps import apps as django_apps
from dirtyfields import DirtyFieldsMixin
from .models import DiffModelManager, DiffModelDescriptor
from .signals import connect
# check if class implemented get_dirty_fields else hack in dirtyfields
if not hasattr(cls, 'get_dirty_fields') and DirtyFieldsMixin not in cls.__bases__:
cls.__bases__ = (DirtyFieldsMixin,) + cls.__bases__
cls.add_to_class('diffs', DiffModelDescriptor(DiffModelManager()))
if not django_apps.ready:
klasses_to_connect.append(cls)
else:
connect(cls)
return cls
def get_connection():
"""Helper method to get redis connection configured by settings"""
import redis
import fakeredis
from .settings import diffs_settings
if not diffs_settings['test_mode']:
return redis.Redis(**diffs_settings['redis'])
else:
return fakeredis.FakeRedis()
|
Update decorator to optionally include DirtyFieldsMixin
|
Update decorator to optionally include DirtyFieldsMixin
Update logic so the class is skipped if it hasattr get_dirty_fields
* Release 0.1.7
|
Python
|
mit
|
linuxlewis/django-diffs
|
---
+++
@@ -1,6 +1,6 @@
from __future__ import absolute_import, unicode_literals
-__version__ = '0.1.6'
+__version__ = '0.1.7'
default_app_config = 'diffs.apps.DiffLogConfig'
klasses_to_connect = []
@@ -19,8 +19,8 @@
from .models import DiffModelManager, DiffModelDescriptor
from .signals import connect
- # Hack to add dirtyfieldsmixin automatically
- if DirtyFieldsMixin not in cls.__bases__:
+ # check if class implemented get_dirty_fields else hack in dirtyfields
+ if not hasattr(cls, 'get_dirty_fields') and DirtyFieldsMixin not in cls.__bases__:
cls.__bases__ = (DirtyFieldsMixin,) + cls.__bases__
cls.add_to_class('diffs', DiffModelDescriptor(DiffModelManager()))
|
260beeaae9daeadb3319b895edc5328504e779b2
|
cansen.py
|
cansen.py
|
#! /usr/bin/python3
print('Test')
|
#! /usr/bin/python3
import cantera as ct
gas = ct.Solution('mech.cti')
gas.TPX = 1000,101325,'H2:2,O2:1,N2:3.76'
reac = ct.Reactor(gas)
netw = ct.ReactorNet([reac])
tend = 10
time = 0
while time < tend:
time = netw.step(tend)
print(time,reac.T,reac.thermo.P)
if reac.T > 1400:
break
|
Create working constant volume reactor test
|
Create working constant volume reactor test
|
Python
|
mit
|
kyleniemeyer/CanSen,bryanwweber/CanSen
|
---
+++
@@ -1,3 +1,13 @@
#! /usr/bin/python3
-
-print('Test')
+import cantera as ct
+gas = ct.Solution('mech.cti')
+gas.TPX = 1000,101325,'H2:2,O2:1,N2:3.76'
+reac = ct.Reactor(gas)
+netw = ct.ReactorNet([reac])
+tend = 10
+time = 0
+while time < tend:
+ time = netw.step(tend)
+ print(time,reac.T,reac.thermo.P)
+ if reac.T > 1400:
+ break
|
105111b0ed02a7c698ba79f88a54636ec3d5b2a8
|
madrona/common/management/commands/install_cleangeometry.py
|
madrona/common/management/commands/install_cleangeometry.py
|
from django.core.management.base import BaseCommand, AppCommand
from django.db import connection, transaction
import os
class Command(BaseCommand):
help = "Installs a cleangeometry function in postgres required for processing incoming geometries."
def handle(self, **options):
path = os.path.abspath(os.path.join(__file__, '../../../cleangeometry.sql'))
sql = open(path,'r').read()
# http://stackoverflow.com/questions/1734814/why-isnt-psycopg2-
# executing-any-of-my-sql-functions-indexerror-tuple-index-o
sql = sql.replace('%','%%')
cursor = connection.cursor()
cursor.execute(sql)
print cursor.statusmessage
|
from django.core.management.base import BaseCommand, AppCommand
from django.db import connection, transaction
import os
class Command(BaseCommand):
help = "Installs a cleangeometry function in postgres required for processing incoming geometries."
def handle(self, **options):
path = os.path.abspath(os.path.join(__file__, '../../../cleangeometry.sql'))
sql = open(path,'r').read()
# http://stackoverflow.com/questions/1734814/why-isnt-psycopg2-
# executing-any-of-my-sql-functions-indexerror-tuple-index-o
sql = sql.replace('%','%%')
cursor = connection.cursor()
cursor.db.enter_transaction_management()
cursor.execute(sql)
print cursor.statusmessage
print "TESTING"
cursor.execute("select cleangeometry(st_geomfromewkt('SRID=4326;POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))'))")
assert cursor.fetchall() == [('0103000020E610000001000000050000000000000000003E4000000000000024400000000000002440000000000000344000000000000034400000000000004440000000000000444000000000000044400000000000003E400000000000002440',)]
cursor.db.commit()
cursor.db.leave_transaction_management()
print "CLEANGEOMETRY function installed successfully"
|
Use transactions to make sure cleangeometry function sticks
|
Use transactions to make sure cleangeometry function sticks
|
Python
|
bsd-3-clause
|
Ecotrust/madrona_addons,Ecotrust/madrona_addons
|
---
+++
@@ -14,5 +14,15 @@
sql = sql.replace('%','%%')
cursor = connection.cursor()
+ cursor.db.enter_transaction_management()
+
cursor.execute(sql)
print cursor.statusmessage
+ print "TESTING"
+
+ cursor.execute("select cleangeometry(st_geomfromewkt('SRID=4326;POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))'))")
+ assert cursor.fetchall() == [('0103000020E610000001000000050000000000000000003E4000000000000024400000000000002440000000000000344000000000000034400000000000004440000000000000444000000000000044400000000000003E400000000000002440',)]
+ cursor.db.commit()
+ cursor.db.leave_transaction_management()
+ print "CLEANGEOMETRY function installed successfully"
+
|
17345dd298860ddfe61f58234d2a38e0a7187d2c
|
rbm2m/worker.py
|
rbm2m/worker.py
|
# -*- coding: utf-8 -*-
"""
Task entry points
"""
from sqlalchemy.exc import SQLAlchemyError
from action import scanner
from helpers import make_config, make_session, make_redis
config = make_config()
sess = make_session(None, config)
redis = make_redis(config)
scanner = scanner.Scanner(config, sess, redis)
def run_task(task_name, *args, **kwargs):
method = getattr(scanner, task_name)
try:
method(*args, **kwargs)
except SQLAlchemyError as e:
sess.rollback()
else:
sess.commit()
finally:
sess.close()
|
# -*- coding: utf-8 -*-
"""
Task entry points
"""
from sqlalchemy.exc import SQLAlchemyError
from action import scanner
from helpers import make_config, make_session, make_redis
config = make_config()
sess = make_session(None, config)
redis = make_redis(config)
scanner = scanner.Scanner(config, sess, redis)
def run_task(task_name, *args, **kwargs):
method = getattr(scanner, task_name)
try:
method(*args, **kwargs)
except SQLAlchemyError as e:
sess.rollback()
raise
else:
sess.commit()
finally:
sess.close()
|
Print SQLAlchemy exceptions to stdout and reraise
|
Print SQLAlchemy exceptions to stdout and reraise
|
Python
|
apache-2.0
|
notapresent/rbm2m,notapresent/rbm2m
|
---
+++
@@ -20,6 +20,7 @@
method(*args, **kwargs)
except SQLAlchemyError as e:
sess.rollback()
+ raise
else:
sess.commit()
finally:
|
e9b5930e7b1865ff1835680c14de58fc9a88d043
|
dominus/main.py
|
dominus/main.py
|
import logging
import chryso.connection
import flask
import dominus.tables
import dominus.views
def run():
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
app = flask.Flask('dominus')
app.config.update(dict(
FLASK_DEBUG = True,
SECRET_KEY = 'development key',
))
db = "postgres://dev:development@localhost:5432/dominus"
engine = chryso.connection.Engine(db, dominus.tables)
chryso.connection.store(engine)
app.route('/')(dominus.views.root)
try:
app.run('localhost', '4554')
except KeyboardInterrupt:
print("Shutting down...")
|
import logging
import chryso.connection
import flask
import dominus.tables
import dominus.views
def setup_db():
db = "postgres://dev:development@localhost:5432/dominus"
engine = chryso.connection.Engine(db, dominus.tables)
chryso.connection.store(engine)
def run():
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
setup_db()
app = flask.Flask('dominus')
app.config.update(dict(
FLASK_DEBUG = True,
SECRET_KEY = 'development key',
))
app.route('/')(dominus.views.root)
app.route('/admin/')(dominus.views.admin)
try:
app.run(host='localhost', port=4554, debug=True)
except KeyboardInterrupt:
print("Shutting down...")
|
Break out DB setup separately, enable debug
|
Break out DB setup separately, enable debug
|
Python
|
mit
|
EliRibble/dominus,EliRibble/dominus,EliRibble/dominus,EliRibble/dominus
|
---
+++
@@ -6,23 +6,27 @@
import dominus.tables
import dominus.views
+def setup_db():
+ db = "postgres://dev:development@localhost:5432/dominus"
+ engine = chryso.connection.Engine(db, dominus.tables)
+ chryso.connection.store(engine)
def run():
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
+
+ setup_db()
app = flask.Flask('dominus')
app.config.update(dict(
FLASK_DEBUG = True,
SECRET_KEY = 'development key',
))
- db = "postgres://dev:development@localhost:5432/dominus"
- engine = chryso.connection.Engine(db, dominus.tables)
- chryso.connection.store(engine)
app.route('/')(dominus.views.root)
+ app.route('/admin/')(dominus.views.admin)
try:
- app.run('localhost', '4554')
+ app.run(host='localhost', port=4554, debug=True)
except KeyboardInterrupt:
print("Shutting down...")
|
f943aa57d6ee462146ff0ab2a091c406d009acce
|
polyaxon/scheduler/spawners/templates/services/default_env_vars.py
|
polyaxon/scheduler/spawners/templates/services/default_env_vars.py
|
from django.conf import settings
from scheduler.spawners.templates.env_vars import get_from_app_secret
def get_service_env_vars():
return [
get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'),
get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'),
get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password',
settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME)
]
|
from django.conf import settings
from libs.api import API_KEY_NAME, get_settings_api_url
from scheduler.spawners.templates.env_vars import get_env_var, get_from_app_secret
def get_service_env_vars():
return [
get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'),
get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'),
get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password',
settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME),
get_env_var(name=API_KEY_NAME, value=get_settings_api_url()),
]
|
Add api url to default env vars
|
Add api url to default env vars
|
Python
|
apache-2.0
|
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
|
---
+++
@@ -1,6 +1,7 @@
from django.conf import settings
-from scheduler.spawners.templates.env_vars import get_from_app_secret
+from libs.api import API_KEY_NAME, get_settings_api_url
+from scheduler.spawners.templates.env_vars import get_env_var, get_from_app_secret
def get_service_env_vars():
@@ -8,5 +9,6 @@
get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'),
get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'),
get_from_app_secret('POLYAXON_RABBITMQ_PASSWORD', 'rabbitmq-password',
- settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME)
+ settings.POLYAXON_K8S_RABBITMQ_SECRET_NAME),
+ get_env_var(name=API_KEY_NAME, value=get_settings_api_url()),
]
|
deef4ac0d34409727d36f273cc63420deae982f7
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import sys
reqs = [
"decorator>=3.3.2",
"Pillow>=2.5.0"
]
if sys.version_info[0] == 2:
# simplejson is not python3 compatible
reqs.append("simplejson>=2.0.9")
if [sys.version_info[0], sys.version_info[1]] < [2, 7]:
reqs.append("argparse>=1.2")
setup(
name = "dogapi",
version = "1.9.1",
packages = find_packages("src"),
package_dir = {'':'src'},
author = "Datadog, Inc.",
author_email = "packages@datadoghq.com",
description = "Python bindings to Datadog's API and a user-facing command line tool.",
license = "BSD",
keywords = "datadog data",
url = "http://www.datadoghq.com",
install_requires = reqs,
entry_points={
'console_scripts': [
'dog = dogshell:main',
'dogwrap = dogshell.wrap:main',
],
},
)
|
from setuptools import setup, find_packages
import sys
install_reqs = [
"decorator>=3.3.2"
]
test_reqs = [
"Pillow>=2.5.0"
]
if sys.version_info[0] == 2:
# simplejson is not python3 compatible
install_reqs.append("simplejson>=2.0.9")
if [sys.version_info[0], sys.version_info[1]] < [2, 7]:
install_reqs.append("argparse>=1.2")
setup(
name = "dogapi",
version = "1.9.1",
packages = find_packages("src"),
package_dir = {'':'src'},
author = "Datadog, Inc.",
author_email = "packages@datadoghq.com",
description = "Python bindings to Datadog's API and a user-facing command line tool.",
license = "BSD",
keywords = "datadog data",
url = "http://www.datadoghq.com",
install_requires = install_reqs,
tests_require = test_reqs,
entry_points = {
'console_scripts': [
'dog = dogshell:main',
'dogwrap = dogshell.wrap:main',
],
},
)
|
Move Pillow to tests requirements
|
Move Pillow to tests requirements
|
Python
|
bsd-3-clause
|
DataDog/dogapi,DataDog/dogapi
|
---
+++
@@ -1,16 +1,19 @@
from setuptools import setup, find_packages
import sys
-reqs = [
- "decorator>=3.3.2",
- "Pillow>=2.5.0"
+install_reqs = [
+ "decorator>=3.3.2"
]
+test_reqs = [
+ "Pillow>=2.5.0"
+]
+
if sys.version_info[0] == 2:
# simplejson is not python3 compatible
- reqs.append("simplejson>=2.0.9")
+ install_reqs.append("simplejson>=2.0.9")
if [sys.version_info[0], sys.version_info[1]] < [2, 7]:
- reqs.append("argparse>=1.2")
+ install_reqs.append("argparse>=1.2")
setup(
name = "dogapi",
@@ -23,8 +26,9 @@
license = "BSD",
keywords = "datadog data",
url = "http://www.datadoghq.com",
- install_requires = reqs,
- entry_points={
+ install_requires = install_reqs,
+ tests_require = test_reqs,
+ entry_points = {
'console_scripts': [
'dog = dogshell:main',
'dogwrap = dogshell.wrap:main',
|
08016cfbc2c0d4dc90158166ef96e0571a581006
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
version = '1.0a1'
setup(name='pystunnel',
version=version,
description='Python interface to stunnel',
#long_description=open('README.rst').read() + '\n' +
# open('CHANGES.rst').read(),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='stunnel ssl tunnel tls',
author='Stefan H. Holek',
author_email='stefan@epy.co.at',
url='https://pypi.python.org/pypi/pystunnel',
license='AGPLv3',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
#test_suite='pystunnel.tests',
install_requires=[
'setuptools',
'six',
],
entry_points={
'console_scripts': 'pystunnel=pystunnel.pystunnel:main',
},
)
|
from setuptools import setup, find_packages
version = '1.0a1'
import sys, functools
if sys.version_info[0] >= 3:
open = functools.partial(open, encoding='utf-8')
setup(name='pystunnel',
version=version,
description='Python interface to stunnel',
long_description=open('README.rst').read() + '\n' +
open('CHANGES.rst').read(),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU Affero General Public License v3',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
keywords='stunnel ssl tunnel tls',
author='Stefan H. Holek',
author_email='stefan@epy.co.at',
url='https://pypi.python.org/pypi/pystunnel',
license='AGPLv3',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
#test_suite='pystunnel.tests',
install_requires=[
'setuptools',
'six',
],
entry_points={
'console_scripts': 'pystunnel=pystunnel.pystunnel:main',
},
)
|
Use README in long description.
|
Use README in long description.
|
Python
|
agpl-3.0
|
zero-db/pystunnel
|
---
+++
@@ -2,11 +2,15 @@
version = '1.0a1'
+import sys, functools
+if sys.version_info[0] >= 3:
+ open = functools.partial(open, encoding='utf-8')
+
setup(name='pystunnel',
version=version,
description='Python interface to stunnel',
- #long_description=open('README.rst').read() + '\n' +
- # open('CHANGES.rst').read(),
+ long_description=open('README.rst').read() + '\n' +
+ open('CHANGES.rst').read(),
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
|
f84d6c2361e78f4ac8a615d28f64a0fd6386c661
|
setup.py
|
setup.py
|
# -*- encoding: UTF-8 -*
from setuptools import setup
with open('README.md') as fp:
README = fp.read()
setup(
name='steeve',
version='0.1',
author='Sviatoslav Abakumov',
author_email='dust.harvesting@gmail.com',
description=u'Tiny GNU Stow–based package manager',
long_description=README,
url='https://github.com/Perlence/steeve',
download_url='https://github.com/Perlence/steeve/archive/master.zip',
py_modules=['steeve'],
zip_safe=False,
entry_points={
'console_scripts': [
'steeve = steeve:cli',
],
},
install_requires=[
'click',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Installation/Setup',
'Topic :: System :: Systems Administration',
'Topic :: Utilities',
]
)
|
# -*- encoding: UTF-8 -*
from setuptools import setup
with open('README.rst') as fp:
README = fp.read()
setup(
name='steeve',
version='0.1',
author='Sviatoslav Abakumov',
author_email='dust.harvesting@gmail.com',
description=u'Tiny GNU Stow–based package manager',
long_description=README,
url='https://github.com/Perlence/steeve',
download_url='https://github.com/Perlence/steeve/archive/master.zip',
py_modules=['steeve'],
zip_safe=False,
entry_points={
'console_scripts': [
'steeve = steeve:cli',
],
},
install_requires=[
'click',
],
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: BSD License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Topic :: System :: Installation/Setup',
'Topic :: System :: Systems Administration',
'Topic :: Utilities',
]
)
|
Read long description from README.rst
|
Read long description from README.rst
|
Python
|
bsd-3-clause
|
Perlence/steeve,Perlence/steeve
|
---
+++
@@ -1,7 +1,7 @@
# -*- encoding: UTF-8 -*
from setuptools import setup
-with open('README.md') as fp:
+with open('README.rst') as fp:
README = fp.read()
setup(
|
a87866811cbdecfc32126a314073a6203ae87b63
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup
setup(name='programmabletuple',
version='0.1',
description='Python metaclass for making named tuples with programmability',
long_description=open('README.rst').read(),
author='Tschijnmo TSCHAU',
author_email='tschijnmotschau@gmail.com',
url='https://github.com/tschijnmo/programmabletuple',
license='MIT',
packages=['programmabletuple', ],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
#!/usr/bin/env python
from setuptools import setup
setup(name='programmabletuple',
version='0.2.0',
description='Python metaclass for making named tuples with programmability',
long_description=open('README.rst').read(),
author='Tschijnmo TSCHAU',
author_email='tschijnmotschau@gmail.com',
url='https://github.com/tschijnmo/programmabletuple',
license='MIT',
packages=['programmabletuple', ],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Change the version number to 0.2.0
|
Change the version number to 0.2.0
|
Python
|
mit
|
tschijnmo/programmabletuple
|
---
+++
@@ -3,7 +3,7 @@
from setuptools import setup
setup(name='programmabletuple',
- version='0.1',
+ version='0.2.0',
description='Python metaclass for making named tuples with programmability',
long_description=open('README.rst').read(),
author='Tschijnmo TSCHAU',
|
96bc1cbf4d67d16753b3dbf9b5b32d6e2d1c521b
|
setup.py
|
setup.py
|
"""
Flask-Celery
------------
Celery integration for Flask
"""
from setuptools import setup
setup(
name='Flask-Celery',
version='2.4.1',
url='http://github.com/ask/flask-celery/',
license='BSD',
author='Ask Solem',
author_email='ask@celeryproject.org',
description='Celery integration for Flask',
long_description=__doc__,
py_modules=['flask_celery'],
zip_safe=False,
platforms='any',
test_suite="nose.collector",
install_requires=[
'Flask>=0.8',
'Flask-Script-fix',
'celery>=2.3.0',
],
tests_require=[
'nose',
'nose-cover3',
'mock',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
"""
Flask-Celery
------------
Celery integration for Flask
"""
from setuptools import setup
setup(
name='Flask-Celery',
version='2.4.1',
url='http://github.com/ask/flask-celery/',
license='BSD',
author='Ask Solem',
author_email='ask@celeryproject.org',
description='Celery integration for Flask',
long_description=__doc__,
py_modules=['flask_celery'],
zip_safe=False,
platforms='any',
test_suite="nose.collector",
install_requires=[
'Flask>=0.8',
'Flask-Script>=0.3.2',
'celery>=2.3.0',
],
tests_require=[
'nose',
'nose-cover3',
'mock',
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Use official Flask-Script distribution (>= 0.3.2)
|
Use official Flask-Script distribution (>= 0.3.2)
|
Python
|
bsd-3-clause
|
ask/flask-celery
|
---
+++
@@ -22,7 +22,7 @@
test_suite="nose.collector",
install_requires=[
'Flask>=0.8',
- 'Flask-Script-fix',
+ 'Flask-Script>=0.3.2',
'celery>=2.3.0',
],
tests_require=[
|
3ac9c317e266d79e96c20121996a4af4d82776dd
|
setup.py
|
setup.py
|
from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://svn.timgolden.me.uk/winsys',
download_url='http://timgolden.me.uk/python/downloads',
license='MIT',
author='Tim Golden',
author_email='mail@timgolden.me.uk',
description='Python tools for the Windows sysadmin',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
],
platforms='win32',
packages=['winsys'],
)
|
from distutils.core import setup
import winsys
if __name__ == '__main__':
setup (
name='WinSys',
version=winsys.__version__,
url='http://code.google.com/p/winsys',
download_url='http://timgolden.me.uk/python/downloads/winsys',
license='MIT',
author='Tim Golden',
author_email='mail@timgolden.me.uk',
description='Python tools for the Windows sysadmin',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: Windows',
'Programming Language :: Python',
'Topic :: Utilities',
],
platforms='win32',
packages=['winsys', 'winsys.test', 'winsys._security', 'winsys.extras'],
)
|
Correct the packaging of packages on winsys
|
Correct the packaging of packages on winsys
modified setup.py
|
Python
|
mit
|
one2pret/winsys,one2pret/winsys
|
---
+++
@@ -6,8 +6,8 @@
setup (
name='WinSys',
version=winsys.__version__,
- url='http://svn.timgolden.me.uk/winsys',
- download_url='http://timgolden.me.uk/python/downloads',
+ url='http://code.google.com/p/winsys',
+ download_url='http://timgolden.me.uk/python/downloads/winsys',
license='MIT',
author='Tim Golden',
author_email='mail@timgolden.me.uk',
@@ -22,5 +22,5 @@
'Topic :: Utilities',
],
platforms='win32',
- packages=['winsys'],
+ packages=['winsys', 'winsys.test', 'winsys._security', 'winsys.extras'],
)
|
abce8024f998dd62a3f0bfac57391c3aebe647fa
|
setup.py
|
setup.py
|
#!/usr/bin/env python3
from setuptools import setup
from ipyrmd import __version__
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
author="Gordon Ball",
author_email="gordon@chronitis.net",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Environment :: Console",
"Framework :: IPython",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
|
#!/usr/bin/env python3
from setuptools import setup
from ipyrmd import __version__
with open("README.md") as f:
long_desc = f.read()
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
long_description=long_desc,
author="Gordon Ball",
author_email="gordon@chronitis.net",
url="https://github.com/chronitis/ipyrmd",
packages=["ipyrmd"],
license="MIT",
install_requires=["nbformat", "pyyaml"],
scripts=["scripts/ipyrmd"],
keywords="ipython jupyter irkernel rmarkdown ipynb",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
"Environment :: Console",
"Framework :: IPython",
"Topic :: Scientific/Engineering",
"Topic :: Utilities"
])
|
Use contents of README as long_description
|
Use contents of README as long_description
|
Python
|
mit
|
chronitis/ipyrmd
|
---
+++
@@ -3,9 +3,13 @@
from setuptools import setup
from ipyrmd import __version__
+with open("README.md") as f:
+ long_desc = f.read()
+
setup(name="ipyrmd",
version=__version__,
description="Convert between IPython/Jupyter notebooks and RMarkdown",
+ long_description=long_desc,
author="Gordon Ball",
author_email="gordon@chronitis.net",
url="https://github.com/chronitis/ipyrmd",
|
a3770920919f02f9609fe0a48789b70ec548cd3d
|
setup.py
|
setup.py
|
import sys
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse", ["src/nerven/epoc/_parse.pyx"])
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='sio@tesser.org',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
|
import sys
import numpy
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
Extension("nerven.epoc._parse",
sources=["src/nerven/epoc/_parse.pyx"],
include_dirs=[".", numpy.get_include()]),
]
setup(name='nerven',
version='0.1',
author='Sharif Olorin',
author_email='sio@tesser.org',
requires=[
'wxmpl',
'numpy',
],
cmdclass={'build_ext' : build_ext},
ext_modules=ext_modules,
package_dir={'' : 'src'},
packages=['nerven', 'nerven.epoc', 'nerven.writer'],
package_data={'nerven' : ['img/*.png']},
scripts=['src/nerven_gui'],
data_files=[('bin', ['src/nerven_gui'])],
)
|
Fix the numpy include path used by the Cython extension
|
Fix the numpy include path used by the Cython extension
Apparently this only worked because I had numpy installed system-wide
(broke on virtualenv-only installs).
|
Python
|
mit
|
olorin/nerven,fractalcat/nerven,fractalcat/nerven,olorin/nerven
|
---
+++
@@ -1,10 +1,15 @@
import sys
+
+import numpy
+
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [
- Extension("nerven.epoc._parse", ["src/nerven/epoc/_parse.pyx"])
+ Extension("nerven.epoc._parse",
+ sources=["src/nerven/epoc/_parse.pyx"],
+ include_dirs=[".", numpy.get_include()]),
]
setup(name='nerven',
|
e0fb70d632553e11f6dd08b31bb81872c3b7bc65
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(
name="django-flexible-images",
version="1.0.0",
url="https://github.com/lewiscollard/django-flexible-images",
author="Lewis Collard",
author_email="lewis.collard@onespacemedia.com",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
description='A responsive image solution for Django.',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication',
],
)
|
#!/usr/bin/env python
# coding: utf-8
from setuptools import find_packages, setup
setup(
name="django-flexible-images",
version="1.0.0",
url="https://github.com/lewiscollard/django-flexible-images",
author="Lewis Collard",
author_email="lewis.collard@onespacemedia.com",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
description='A responsive image solution for Django.',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Natural Language :: English',
'Programming Language :: Python :: 2.7',
'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication',
],
install_requires=[
'django',
'sorl-thumbnail'
]
)
|
Add sorl-thumbnail and Django as installation requirements.
|
Add sorl-thumbnail and Django as installation requirements.
|
Python
|
cc0-1.0
|
lewiscollard/django-flexible-images,lewiscollard/django-flexible-images,lewiscollard/django-flexible-images
|
---
+++
@@ -22,4 +22,8 @@
'Programming Language :: Python :: 2.7',
'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication',
],
+ install_requires=[
+ 'django',
+ 'sorl-thumbnail'
+ ]
)
|
00ebbcb50ada0369dde02b114efc573d9aceea67
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='realex-client',
version='0.8.0',
packages=['realexpayments'],
url='https://github.com/viniciuschiele/realex-client',
license='MIT',
author='Vinicius Chiele',
author_email='vinicius.chiele@gmail.com',
description='Python interface to Realex Payments',
keywords=['realex', 'payments', 'api', 'client'],
install_requires=['requests'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython'
]
)
|
from setuptools import setup
setup(
name='realexpayments',
version='0.8.0',
packages=['realexpayments'],
url='https://github.com/viniciuschiele/realex-sdk',
license='MIT',
author='Vinicius Chiele',
author_email='vinicius.chiele@gmail.com',
description='Realex Payments SDK for Python',
keywords=['realex', 'payments', 'api', 'client'],
install_requires=['requests'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: Implementation :: CPython'
]
)
|
Rename project name to realexpayments
|
Rename project name to realexpayments
|
Python
|
mit
|
viniciuschiele/realex-sdk,viniciuschiele/realex-client
|
---
+++
@@ -1,14 +1,14 @@
from setuptools import setup
setup(
- name='realex-client',
+ name='realexpayments',
version='0.8.0',
packages=['realexpayments'],
- url='https://github.com/viniciuschiele/realex-client',
+ url='https://github.com/viniciuschiele/realex-sdk',
license='MIT',
author='Vinicius Chiele',
author_email='vinicius.chiele@gmail.com',
- description='Python interface to Realex Payments',
+ description='Realex Payments SDK for Python',
keywords=['realex', 'payments', 'api', 'client'],
install_requires=['requests'],
classifiers=[
|
a349fceba7d4c22be8b44323dc759aa5bc605e73
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name='cmsplugin-simple-markdown',
version=".".join(map(str, __import__('cmsplugin_simple_markdown').__version__)),
packages=['cmsplugin_simple_markdown', 'cmsplugin_simple_markdown.migrations'],
package_dir={'cmsplugin_simple_markdown': 'cmsplugin_simple_markdown'},
package_data={'cmsplugin_simple_markdown': ['templates/*/*']},
url='https://www.github.com/Alir3z4/cmsplugin-simple-markdown',
license=open('LICENSE').read(),
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
description='A plugin for django-cms that provides just a markdown plugin and nothing more.',
long_description=open('README.rst').read(),
keywords=[
'django',
'django-cms',
'web',
'cms',
'cmsplugin',
'plugin',
],
platforms='OS Independent',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development'
],
)
|
from setuptools import setup
setup(
name='cmsplugin-simple-markdown',
version=".".join(map(str, __import__('cmsplugin_simple_markdown').__version__)),
packages=['cmsplugin_simple_markdown', 'cmsplugin_simple_markdown.migrations'],
package_dir={'cmsplugin_simple_markdown': 'cmsplugin_simple_markdown'},
package_data={'cmsplugin_simple_markdown': ['templates/*/*']},
install_requires=['markdown'],
url='https://www.github.com/Alir3z4/cmsplugin-simple-markdown',
license=open('LICENSE').read(),
author='Alireza Savand',
author_email='alireza.savand@gmail.com',
description='A plugin for django-cms that provides just a markdown plugin and nothing more.',
long_description=open('README.rst').read(),
keywords=[
'django',
'django-cms',
'web',
'cms',
'cmsplugin',
'plugin',
],
platforms='OS Independent',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Programming Language :: Python',
'Framework :: Django',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development'
],
)
|
Install Python Markdown when installing cmsplugin-simple-markdown.
|
Install Python Markdown when installing cmsplugin-simple-markdown.
|
Python
|
bsd-3-clause
|
Alir3z4/cmsplugin-simple-markdown,Alir3z4/cmsplugin-simple-markdown
|
---
+++
@@ -1,4 +1,4 @@
-from distutils.core import setup
+from setuptools import setup
setup(
name='cmsplugin-simple-markdown',
@@ -6,6 +6,7 @@
packages=['cmsplugin_simple_markdown', 'cmsplugin_simple_markdown.migrations'],
package_dir={'cmsplugin_simple_markdown': 'cmsplugin_simple_markdown'},
package_data={'cmsplugin_simple_markdown': ['templates/*/*']},
+ install_requires=['markdown'],
url='https://www.github.com/Alir3z4/cmsplugin-simple-markdown',
license=open('LICENSE').read(),
author='Alireza Savand',
|
e5a5dfd8a8c50d3df2070dc52ad09c440507a869
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='fapistrano',
version='0.5.1',
license='MIT',
description='Capistrano style deployment with fabric',
zip_safe=False,
include_package_data=True,
platforms='any',
packages=['fapistrano'],
install_requires=[
'Fabric',
'requests',
'PyYaml',
],
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
from setuptools import setup
setup(
name='fapistrano',
version='0.5.1',
license='MIT',
description='Capistrano style deployment with fabric',
zip_safe=False,
include_package_data=True,
platforms='any',
packages=['fapistrano'],
install_requires=[
'Fabric',
'requests',
'PyYaml',
],
entry_points='''
[console_scripts]
fap=fapistrano.cli:fap
'''
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
]
)
|
Add `fap` as a console script.
|
Add `fap` as a console script.
|
Python
|
mit
|
liwushuo/fapistrano
|
---
+++
@@ -15,6 +15,10 @@
'requests',
'PyYaml',
],
+ entry_points='''
+ [console_scripts]
+ fap=fapistrano.cli:fap
+ '''
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
|
47dff0e6847889f386cbf0faf5db567a56bf5eef
|
setup.py
|
setup.py
|
import os
from distutils.core import setup
from setuptools import find_packages
VERSION = __import__("django_shop_payer_backend").VERSION
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development',
]
install_requires = [
'django-shop>=0.2.0',
'python-payer-api==dev',
]
setup(
name="django-shop-payer-backend",
description="Payment backend for django SHOP and Payer.",
version=VERSION,
author="Simon Fransson",
author_email="simon@dessibelle.se",
url="https://github.com/dessibelle/django-shop-payer-backend",
download_url="https://github.com/dessibelle/django-shop-payer-backend/archive/%s.tar.gz" % VERSION,
packages=['django_shop_payer_backend'],
dependency_links = ['https://github.com/dessibelle/python-payer-api/tarball/master#egg=python-payer-api-0.1.0'],
install_requires=install_requires,
classifiers=CLASSIFIERS,
license="MIT",
long_description="""https://github.com/dessibelle/python-payer-api/tarball/master#egg=python-payer-api-dev"""
)
|
import os
from distutils.core import setup
from setuptools import find_packages
VERSION = __import__("django_shop_payer_backend").VERSION
CLASSIFIERS = [
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Software Development',
]
install_requires = [
'django-shop>=0.2.0',
'python-payer-api>=0.1.0',
]
setup(
name="django-shop-payer-backend",
description="Payment backend for django SHOP and Payer.",
version=VERSION,
author="Simon Fransson",
author_email="simon@dessibelle.se",
url="https://github.com/dessibelle/django-shop-payer-backend",
download_url="https://github.com/dessibelle/django-shop-payer-backend/archive/%s.tar.gz" % VERSION,
packages=['django_shop_payer_backend'],
install_requires=install_requires,
classifiers=CLASSIFIERS,
license="MIT",
)
|
Use pip version of python-payer-api instead.
|
Use pip version of python-payer-api instead.
|
Python
|
mit
|
dessibelle/django-shop-payer-backend
|
---
+++
@@ -14,7 +14,7 @@
install_requires = [
'django-shop>=0.2.0',
- 'python-payer-api==dev',
+ 'python-payer-api>=0.1.0',
]
setup(
@@ -26,9 +26,7 @@
url="https://github.com/dessibelle/django-shop-payer-backend",
download_url="https://github.com/dessibelle/django-shop-payer-backend/archive/%s.tar.gz" % VERSION,
packages=['django_shop_payer_backend'],
- dependency_links = ['https://github.com/dessibelle/python-payer-api/tarball/master#egg=python-payer-api-0.1.0'],
install_requires=install_requires,
classifiers=CLASSIFIERS,
license="MIT",
- long_description="""https://github.com/dessibelle/python-payer-api/tarball/master#egg=python-payer-api-dev"""
)
|
fd1e904e1f2b6297801a1c8cd6626bdf1d73a3ec
|
setup.py
|
setup.py
|
from setuptools import setup
__version_info__ = ('0', '2', '0')
__version__ = '.'.join(__version_info__)
setup(
name="staticjinja",
version=__version__,
description="jinja based static site generator",
author="Ceasar Bautista",
author_email="cbautista2010@gmail.com",
url="https://github.com/Ceasar/staticjinja",
keywords=["jinja", "static", "website"],
packages=["staticjinja"],
install_requires=["easywatch", "jinja2"],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.5",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Topic :: Software Development :: Libraries :: Python Modules",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
],
use_2to3=True,
)
|
from setuptools import setup
__version_info__ = ('0', '2', '0')
__version__ = '.'.join(__version_info__)
setup(
name="staticjinja",
version=__version__,
description="jinja based static site generator",
author="Ceasar Bautista",
author_email="cbautista2010@gmail.com",
url="https://github.com/Ceasar/staticjinja",
keywords=["jinja", "static", "website"],
packages=["staticjinja"],
install_requires=["easywatch", "jinja2"],
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries :: Python Modules",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
]
)
|
Update the Python version classifiers, and remove use_2to3
|
Update the Python version classifiers, and remove use_2to3
staticjinja supports Python 2.6, 2.7 and 3.3.
This change also removes support for Python 2.5, which isn't
supported by tox (so ensuring staticjinja works with 2.5 is
tricky).
|
Python
|
mit
|
Ceasar/staticjinja,Ceasar/staticjinja,jerivas/staticjinja,jerivas/staticjinja
|
---
+++
@@ -18,12 +18,13 @@
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
- "Programming Language :: Python :: 2.5",
+ "Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.3",
"Topic :: Software Development :: Libraries :: Python Modules",
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
- ],
- use_2to3=True,
+ ]
)
|
785cbf2f296b425bf0079cba99ee7bae662fc6d1
|
setup.py
|
setup.py
|
"""
A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='paragoo', # pip install paragoo
description='Static site generator',
#long_description=open('README.md', 'rt').read(),
long_description=long_description,
# version
# third part for minor release
# second when api changes
# first when it becomes stable someday
version='0.2.0',
author='Michiel Scholten',
author_email='michiel@diginaut.net',
url='https://github.com/aquatix/paragoo',
license='Apache',
# as a practice no need to hard code version unless you know program wont
# work unless the specific versions are used
install_requires=['Jinja2', 'Markdown', 'MarkupSafe', 'docutils', 'pygments', 'PyYAML', 'click', 'requests', 'bs4','utilkit>=0.3.0'],
py_modules=['paragoo'],
zip_safe=True,
)
|
"""
A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup
# To use a consistent encoding
from codecs import open as codecopen
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with codecopen(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='paragoo', # pip install paragoo
description='Static site generator',
#long_description=open('README.md', 'rt').read(),
long_description=long_description,
# version
# third part for minor release
# second when api changes
# first when it becomes stable someday
version='0.2.0',
author='Michiel Scholten',
author_email='michiel@diginaut.net',
url='https://github.com/aquatix/paragoo',
license='Apache',
# as a practice no need to hard code version unless you know program wont
# work unless the specific versions are used
install_requires=['Jinja2', 'Markdown', 'MarkupSafe', 'docutils', 'pygments', 'PyYAML', 'click', 'requests', 'bs4','utilkit>=0.3.0'],
py_modules=['paragoo'],
zip_safe=True,
)
|
Fix reserved keyword override with import
|
Fix reserved keyword override with import
|
Python
|
apache-2.0
|
aquatix/paragoo,aquatix/paragoo
|
---
+++
@@ -7,13 +7,13 @@
from setuptools import setup
# To use a consistent encoding
-from codecs import open
+from codecs import open as codecopen
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
-with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
+with codecopen(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
|
6131430ff7d1e9e8cd95f8d2793e82cc72679d81
|
auditlog/admin.py
|
auditlog/admin.py
|
from django.contrib import admin
from .filters import ResourceTypeFilter
from .mixins import LogEntryAdminMixin
from .models import LogEntry
class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin):
list_display = ["created", "resource_url", "action", "msg_short", "user_url"]
search_fields = [
"timestamp",
"object_repr",
"changes",
"actor__first_name",
"actor__last_name",
]
list_filter = ["action", ResourceTypeFilter]
readonly_fields = ["created", "resource_url", "action", "user_url", "msg"]
fieldsets = [
(None, {"fields": ["created", "user_url", "resource_url"]}),
("Changes", {"fields": ["action", "msg"]}),
]
admin.site.register(LogEntry, LogEntryAdmin)
|
from django.contrib import admin
from auditlog.filters import ResourceTypeFilter
from auditlog.mixins import LogEntryAdminMixin
from auditlog.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin):
list_display = ["created", "resource_url", "action", "msg_short", "user_url"]
search_fields = [
"timestamp",
"object_repr",
"changes",
"actor__first_name",
"actor__last_name",
]
list_filter = ["action", ResourceTypeFilter]
readonly_fields = ["created", "resource_url", "action", "user_url", "msg"]
fieldsets = [
(None, {"fields": ["created", "user_url", "resource_url"]}),
("Changes", {"fields": ["action", "msg"]}),
]
admin.site.register(LogEntry, LogEntryAdmin)
|
Change relative imports to absolute.
|
Change relative imports to absolute.
|
Python
|
mit
|
jjkester/django-auditlog
|
---
+++
@@ -1,8 +1,8 @@
from django.contrib import admin
-from .filters import ResourceTypeFilter
-from .mixins import LogEntryAdminMixin
-from .models import LogEntry
+from auditlog.filters import ResourceTypeFilter
+from auditlog.mixins import LogEntryAdminMixin
+from auditlog.models import LogEntry
class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin):
|
649dc183ecce5586483155a9bc3699e73b6c4601
|
plugins/configuration/preferences/preferences.py
|
plugins/configuration/preferences/preferences.py
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
"""
Provides a class that allows for creating global application preferences.
"""
import luna.plugins #To get the configuration data type to extend from.
class Preferences:
"""
Offers a system to create global application preferences.
"""
def prepare(self):
"""
Finalizes the class initialisation using data that is only available at
run time.
"""
original_class = self.__class__
parent_class = luna.plugins.api("configuration").Configuration
self.__class__ = original_class.__class__(original_class.__name__ + "Configuration", (original_class, parent_class), {}) #Add the configuration class mixin.
super().__init__() #Execute the Configuration class' initialisation method to create the data structures.
|
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license differs from the license provided with this software, the license provided with this software should be applied.
"""
Provides a class that allows for creating global application preferences.
"""
import luna.listen #To prepare the preferences for use when plug-ins are loaded.
import luna.plugins #To get the configuration data type to extend from.
class Preferences:
"""
Offers a system to create global application preferences.
"""
def __init__(self):
luna.listen.listen(self.check_prepare, luna.plugins, "state")
def check_prepare(self, _, new_state):
if new_state == luna.plugins.PluginsState.LOADED:
self.prepare()
def prepare(self):
"""
Finalizes the class initialisation using data that is only available at
run time.
"""
original_class = self.__class__
parent_class = luna.plugins.api("configuration").Configuration
self.__class__ = original_class.__class__(original_class.__name__ + "Configuration", (original_class, parent_class), {}) #Add the configuration class mixin.
super().__init__() #Execute the Configuration class' initialisation method to create the data structures.
|
Prepare once plug-ins are loaded
|
Prepare once plug-ins are loaded
With the new version of the listen hook.
|
Python
|
cc0-1.0
|
Ghostkeeper/Luna
|
---
+++
@@ -8,12 +8,20 @@
Provides a class that allows for creating global application preferences.
"""
+import luna.listen #To prepare the preferences for use when plug-ins are loaded.
import luna.plugins #To get the configuration data type to extend from.
class Preferences:
"""
Offers a system to create global application preferences.
"""
+
+ def __init__(self):
+ luna.listen.listen(self.check_prepare, luna.plugins, "state")
+
+ def check_prepare(self, _, new_state):
+ if new_state == luna.plugins.PluginsState.LOADED:
+ self.prepare()
def prepare(self):
"""
|
0c2305db6c6792f624cf09a9134aaa090c82d5c1
|
tasks.py
|
tasks.py
|
from invoke import task
import jschema
@task
def pip(ctx):
ctx.run("rm -rf dist jschema.egg-info")
ctx.run("./setup.py sdist")
ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__))
@task
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
|
from invoke import task
from invoke.util import cd
import jschema
@task
def pip(ctx):
ctx.run("rm -rf dist jschema.egg-info")
ctx.run("./setup.py sdist")
ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__))
@task
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
@task
def mezzo(ctx):
ctx.run("mkdir -p build/jschema")
ctx.run("cp -R jschema setup.py build/jschema")
with cd("build"):
ctx.run("tar cf jschema.tar.gz jschema")
ctx.run("mv jschema.tar.gz /opt/mezzo/dependencies")
ctx.run("rm -rf jschema")
|
Add mezzo task, for copy project to mezzo
|
Add mezzo task, for copy project to mezzo
|
Python
|
mit
|
stepan-perlov/jschema,stepan-perlov/jschema
|
---
+++
@@ -1,4 +1,5 @@
from invoke import task
+from invoke.util import cd
import jschema
@@ -12,3 +13,12 @@
def doc(ctx):
ctx.run("./setup.py build_sphinx")
ctx.run("./setup.py upload_sphinx")
+
+@task
+def mezzo(ctx):
+ ctx.run("mkdir -p build/jschema")
+ ctx.run("cp -R jschema setup.py build/jschema")
+ with cd("build"):
+ ctx.run("tar cf jschema.tar.gz jschema")
+ ctx.run("mv jschema.tar.gz /opt/mezzo/dependencies")
+ ctx.run("rm -rf jschema")
|
fa862fdd6be62eb4e79d0dfcef60471aecd46981
|
rest_framework_push_notifications/tests/test_serializers.py
|
rest_framework_push_notifications/tests/test_serializers.py
|
from django.test import TestCase
from .. import serializers
class TestAPNSDeviceSerializer(TestCase):
def test_fields(self):
expected = {'url', 'name', 'device_id', 'registration_id', 'active'}
fields = serializers.APNSDevice().fields.keys()
self.assertEqual(expected, set(fields))
def test_registration_id(self):
serializer = serializers.APNSDevice(data={'registration_id': 'test_id'})
self.assertTrue(serializer.is_valid())
def test_registration_id_required(self):
serializer = serializers.APNSDevice(data={})
self.assertFalse(serializer.is_valid())
|
from django.test import TestCase
from .. import serializers
class TestAPNSDeviceSerializer(TestCase):
def test_fields(self):
expected = {'url', 'name', 'device_id', 'registration_id', 'active'}
fields = serializers.APNSDevice().fields.keys()
self.assertEqual(expected, set(fields))
def test_registration_id(self):
serializer = serializers.APNSDevice(data={'registration_id': 'test_id'})
self.assertTrue(serializer.is_valid())
def test_registration_id_required(self):
serializer = serializers.APNSDevice(data={})
self.assertFalse(serializer.is_valid())
self.assertIn('registration_id', serializer.errors)
|
Check for registration_id in serializer errors
|
Check for registration_id in serializer errors
|
Python
|
bsd-2-clause
|
incuna/rest-framework-push-notifications
|
---
+++
@@ -16,3 +16,4 @@
def test_registration_id_required(self):
serializer = serializers.APNSDevice(data={})
self.assertFalse(serializer.is_valid())
+ self.assertIn('registration_id', serializer.errors)
|
4f1c4f75a3576c4bfb3517e6e9168fc8433a5c4b
|
engine/gobject.py
|
engine/gobject.py
|
from .meta import GObjectMeta
from . import signals
from . import meta
@meta.apply
class GObject(metaclass=GObjectMeta):
# Attributes of the object
__attributes__ = ()
def __init__(self, **kwargs):
for key in self.__attributes__:
setattr(self, key, kwargs.pop(key))
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
def __getstate__(self):
return {k: getattr(self, k) for k in self.__attributes__}
def __setstate__(self, state):
self.__init__(**state)
|
from .meta import GObjectMeta
from . import signals
from . import meta
@meta.apply
class GObject(metaclass=GObjectMeta):
# Attributes of the object
__attributes__ = ()
def __init__(self, **kwargs):
for key in self.__attributes__:
setattr(self, key, kwargs.pop(key))
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
def set(self, **kwargs):
for key, value in kwargs.items():
if key not in self.__attributes__:
raise TypeError('Unexpected attribute {}'.format(key))
setattr(self, key, value)
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
def __getstate__(self):
return {k: getattr(self, k) for k in self.__attributes__}
def __setstate__(self, state):
self.__init__(**state)
|
Add method set to GObject to set attributes
|
Add method set to GObject to set attributes
|
Python
|
bsd-3-clause
|
entwanne/NAGM
|
---
+++
@@ -13,6 +13,12 @@
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
+ def set(self, **kwargs):
+ for key, value in kwargs.items():
+ if key not in self.__attributes__:
+ raise TypeError('Unexpected attribute {}'.format(key))
+ setattr(self, key, value)
+
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
|
70931f5d0d1b90ce2f7853ffcab94838cab0dab5
|
api/base/views.py
|
api/base/views.py
|
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
from api.users.serializers import UserSerializer
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
current_user = UserSerializer(user).data
else:
current_user = None
return Response({
'meta': {
'message': 'Welcome to the OSF API.',
'version': request.version,
'current_user': current_user,
},
'links': {
'nodes': absolute_reverse('nodes:node-list'),
'users': absolute_reverse('users:user-list'),
}
})
|
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .utils import absolute_reverse
from api.users.serializers import UserSerializer
@api_view(('GET',))
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
current_user = UserSerializer(user, context={'request': request}).data
else:
current_user = None
return Response({
'meta': {
'message': 'Welcome to the OSF API.',
'version': request.version,
'current_user': current_user,
},
'links': {
'nodes': absolute_reverse('nodes:node-list'),
'users': absolute_reverse('users:user-list'),
}
})
|
Add context when calling UserSerializer
|
Add context when calling UserSerializer
|
Python
|
apache-2.0
|
brianjgeiger/osf.io,rdhyee/osf.io,billyhunt/osf.io,alexschiller/osf.io,samchrisinger/osf.io,acshi/osf.io,sbt9uc/osf.io,brandonPurvis/osf.io,amyshi188/osf.io,chrisseto/osf.io,baylee-d/osf.io,cosenal/osf.io,samchrisinger/osf.io,jnayak1/osf.io,petermalcolm/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,mluo613/osf.io,MerlinZhang/osf.io,petermalcolm/osf.io,sbt9uc/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,emetsger/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,adlius/osf.io,asanfilippo7/osf.io,asanfilippo7/osf.io,pattisdr/osf.io,ticklemepierce/osf.io,aaxelb/osf.io,mluo613/osf.io,binoculars/osf.io,MerlinZhang/osf.io,wearpants/osf.io,petermalcolm/osf.io,mfraezz/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,monikagrabowska/osf.io,danielneis/osf.io,icereval/osf.io,ticklemepierce/osf.io,brandonPurvis/osf.io,wearpants/osf.io,doublebits/osf.io,RomanZWang/osf.io,hmoco/osf.io,Nesiehr/osf.io,caseyrygt/osf.io,kch8qx/osf.io,GageGaskins/osf.io,njantrania/osf.io,SSJohns/osf.io,haoyuchen1992/osf.io,mfraezz/osf.io,TomBaxter/osf.io,cslzchen/osf.io,caseyrygt/osf.io,ZobairAlijan/osf.io,crcresearch/osf.io,mattclark/osf.io,kch8qx/osf.io,cwisecarver/osf.io,haoyuchen1992/osf.io,baylee-d/osf.io,sbt9uc/osf.io,sloria/osf.io,arpitar/osf.io,billyhunt/osf.io,saradbowman/osf.io,saradbowman/osf.io,binoculars/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,GageGaskins/osf.io,aaxelb/osf.io,cosenal/osf.io,caseyrollins/osf.io,samchrisinger/osf.io,abought/osf.io,zachjanicki/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,rdhyee/osf.io,erinspace/osf.io,cslzchen/osf.io,caseyrygt/osf.io,njantrania/osf.io,jnayak1/osf.io,njantrania/osf.io,caseyrollins/osf.io,Ghalko/osf.io,mluo613/osf.io,Johnetordoff/osf.io,Nesiehr/osf.io,jmcarp/osf.io,TomHeatwole/osf.io,ZobairAlijan/osf.io,KAsante95/osf.io,jnayak1/osf.io,haoyuchen1992/osf.io,samanehsan/osf.io,binoculars/osf.io,ckc6cz/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,mluo613/osf.io,jmcarp/osf.io,jnayak1/osf.io,mattclark/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,kwierman/osf.io,caneruguz/osf.io,kwierman/osf.io,Johnetordoff/osf.io,amyshi188/osf.io,TomHeatwole/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,MerlinZhang/osf.io,zamattiac/osf.io,SSJohns/osf.io,DanielSBrown/osf.io,haoyuchen1992/osf.io,mattclark/osf.io,acshi/osf.io,leb2dg/osf.io,emetsger/osf.io,doublebits/osf.io,cwisecarver/osf.io,emetsger/osf.io,mluo613/osf.io,brandonPurvis/osf.io,mluke93/osf.io,TomHeatwole/osf.io,jmcarp/osf.io,icereval/osf.io,caneruguz/osf.io,chennan47/osf.io,danielneis/osf.io,caneruguz/osf.io,asanfilippo7/osf.io,danielneis/osf.io,doublebits/osf.io,laurenrevere/osf.io,arpitar/osf.io,ckc6cz/osf.io,felliott/osf.io,alexschiller/osf.io,hmoco/osf.io,RomanZWang/osf.io,jmcarp/osf.io,TomBaxter/osf.io,mluke93/osf.io,adlius/osf.io,DanielSBrown/osf.io,RomanZWang/osf.io,ckc6cz/osf.io,cwisecarver/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,Ghalko/osf.io,baylee-d/osf.io,brandonPurvis/osf.io,chennan47/osf.io,KAsante95/osf.io,rdhyee/osf.io,Johnetordoff/osf.io,cosenal/osf.io,Ghalko/osf.io,mluke93/osf.io,DanielSBrown/osf.io,brianjgeiger/osf.io,TomHeatwole/osf.io,felliott/osf.io,zamattiac/osf.io,emetsger/osf.io,doublebits/osf.io,GageGaskins/osf.io,kwierman/osf.io,SSJohns/osf.io,amyshi188/osf.io,ticklemepierce/osf.io,crcresearch/osf.io,CenterForOpenScience/osf.io,acshi/osf.io,mluke93/osf.io,caneruguz/osf.io,aaxelb/osf.io,Nesiehr/osf.io,arpitar/osf.io,HalcyonChimera/osf.io,Ghalko/osf.io,samanehsan/osf.io,zamattiac/osf.io,laurenrevere/osf.io,icereval/osf.io,doublebits/osf.io,arpitar/osf.io,alexschiller/osf.io,ckc6cz/osf.io,kch8qx/osf.io,HalcyonChimera/osf.io,asanfilippo7/osf.io,danielneis/osf.io,GageGaskins/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,samanehsan/osf.io,ZobairAlijan/osf.io,KAsante95/osf.io,RomanZWang/osf.io,DanielSBrown/osf.io,samanehsan/osf.io,crcresearch/osf.io,GageGaskins/osf.io,abought/osf.io,sloria/osf.io,TomBaxter/osf.io,cslzchen/osf.io,pattisdr/osf.io,chrisseto/osf.io,billyhunt/osf.io,caseyrollins/osf.io,pattisdr/osf.io,leb2dg/osf.io,kwierman/osf.io,KAsante95/osf.io,ZobairAlijan/osf.io,laurenrevere/osf.io,zamattiac/osf.io,wearpants/osf.io,petermalcolm/osf.io,kch8qx/osf.io,cwisecarver/osf.io,SSJohns/osf.io,wearpants/osf.io,njantrania/osf.io,brandonPurvis/osf.io,abought/osf.io,billyhunt/osf.io,sbt9uc/osf.io,ticklemepierce/osf.io,abought/osf.io,alexschiller/osf.io,KAsante95/osf.io,kch8qx/osf.io,acshi/osf.io,zachjanicki/osf.io,mfraezz/osf.io,chennan47/osf.io,cosenal/osf.io,billyhunt/osf.io,amyshi188/osf.io,erinspace/osf.io,adlius/osf.io,acshi/osf.io,MerlinZhang/osf.io,hmoco/osf.io,felliott/osf.io,hmoco/osf.io,brianjgeiger/osf.io,adlius/osf.io,RomanZWang/osf.io,rdhyee/osf.io,zachjanicki/osf.io
|
---
+++
@@ -8,7 +8,7 @@
def root(request, format=None):
if request.user and not request.user.is_anonymous():
user = request.user
- current_user = UserSerializer(user).data
+ current_user = UserSerializer(user, context={'request': request}).data
else:
current_user = None
return Response({
|
cdee18e9a937f3dd7e788b92927f35652320e743
|
api/streams/views.py
|
api/streams/views.py
|
from api.streams.models import StreamConfiguration
from django.http import JsonResponse
from django.http.request import HttpRequest
import requests
def get_stream_status(request: HttpRequest, stream_slug: str):
stream = StreamConfiguration.objects.get(slug=stream_slug)
r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5)
r.raise_for_status()
return JsonResponse(r.json())
|
from api.streams.models import StreamConfiguration
from django.http import JsonResponse, Http404
from django.http.request import HttpRequest
import requests
def get_stream_status(request: HttpRequest, stream_slug: str):
try:
stream = StreamConfiguration.objects.get(slug=stream_slug)
except StreamConfiguration.DoesNotExist:
raise Http404("Stream with slug {0} does not exist.".format(stream_slug))
r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5)
if r.status_code != requests.codes.ok:
return JsonResponse({ "error": "Upstream request failed" }, status=500)
return JsonResponse(r.json())
|
Improve error handling in stream status view
|
Improve error handling in stream status view
- Check if stream exists and raise a 404 otherwise
- Check if upstream returned a success status code and raise a 500 otherwise
|
Python
|
mit
|
urfonline/api,urfonline/api,urfonline/api
|
---
+++
@@ -1,12 +1,17 @@
from api.streams.models import StreamConfiguration
-from django.http import JsonResponse
+from django.http import JsonResponse, Http404
from django.http.request import HttpRequest
import requests
def get_stream_status(request: HttpRequest, stream_slug: str):
- stream = StreamConfiguration.objects.get(slug=stream_slug)
+ try:
+ stream = StreamConfiguration.objects.get(slug=stream_slug)
+ except StreamConfiguration.DoesNotExist:
+ raise Http404("Stream with slug {0} does not exist.".format(stream_slug))
r = requests.get('http://{stream.host}:{stream.port}/status-json.xsl'.format(stream=stream), timeout=5)
- r.raise_for_status()
+
+ if r.status_code != requests.codes.ok:
+ return JsonResponse({ "error": "Upstream request failed" }, status=500)
return JsonResponse(r.json())
|
583a32cd1e9e77d7648978d20a5b7631a4fe2334
|
tests/sentry/interfaces/tests.py
|
tests/sentry/interfaces/tests.py
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pickle
from sentry.interfaces import Interface
from sentry.testutils import TestCase
class InterfaceTests(TestCase):
def test_init_sets_attrs(self):
obj = Interface(foo=1)
self.assertEqual(obj.attrs, ['foo'])
def test_setstate_sets_attrs(self):
data = pickle.dumps(Interface(foo=1))
obj = pickle.loads(data)
self.assertEqual(obj.attrs, ['foo'])
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pickle
from sentry.interfaces import Interface, Message, Stacktrace
from sentry.models import Event
from sentry.testutils import TestCase, fixture
class InterfaceBase(TestCase):
@fixture
def event(self):
return Event(
id=1,
)
class InterfaceTest(InterfaceBase):
@fixture
def interface(self):
return Interface(foo=1)
def test_init_sets_attrs(self):
assert self.interface.attrs == ['foo']
def test_setstate_sets_attrs(self):
data = pickle.dumps(self.interface)
obj = pickle.loads(data)
assert obj.attrs == ['foo']
def test_to_html_default(self):
assert self.interface.to_html(self.event) == ''
def test_to_string_default(self):
assert self.interface.to_string(self.event) == ''
class MessageTest(InterfaceBase):
@fixture
def interface(self):
return Message(message='Hello there %s!', params=('world',))
def test_serialize_behavior(self):
assert self.interface.serialize() == {
'message': self.interface.message,
'params': self.interface.params,
}
def test_get_hash_uses_message(self):
assert self.interface.get_hash() == [self.interface.message]
def test_get_search_context_with_params_as_list(self):
interface = self.interface
interface.params = ['world']
assert interface.get_search_context(self.event) == {
'text': [interface.message] + list(interface.params)
}
def test_get_search_context_with_params_as_tuple(self):
assert self.interface.get_search_context(self.event) == {
'text': [self.interface.message] + list(self.interface.params)
}
def test_get_search_context_with_params_as_dict(self):
interface = self.interface
interface.params = {'who': 'world'}
interface.message = 'Hello there %(who)s!'
assert self.interface.get_search_context(self.event) == {
'text': [interface.message] + interface.params.values()
}
|
Improve test coverage on base Interface and Message classes
|
Improve test coverage on base Interface and Message classes
|
Python
|
bsd-3-clause
|
songyi199111/sentry,JTCunning/sentry,JackDanger/sentry,fotinakis/sentry,JamesMura/sentry,kevinlondon/sentry,mitsuhiko/sentry,felixbuenemann/sentry,fotinakis/sentry,jean/sentry,drcapulet/sentry,ifduyue/sentry,alexm92/sentry,pauloschilling/sentry,fuziontech/sentry,jokey2k/sentry,fotinakis/sentry,argonemyth/sentry,zenefits/sentry,Kryz/sentry,beeftornado/sentry,boneyao/sentry,pauloschilling/sentry,hongliang5623/sentry,fuziontech/sentry,imankulov/sentry,rdio/sentry,jean/sentry,BayanGroup/sentry,songyi199111/sentry,rdio/sentry,felixbuenemann/sentry,nicholasserra/sentry,looker/sentry,gg7/sentry,jokey2k/sentry,gg7/sentry,vperron/sentry,alexm92/sentry,mvaled/sentry,SilentCircle/sentry,BayanGroup/sentry,korealerts1/sentry,alexm92/sentry,ngonzalvez/sentry,fuziontech/sentry,BuildingLink/sentry,Natim/sentry,looker/sentry,boneyao/sentry,daevaorn/sentry,Natim/sentry,rdio/sentry,llonchj/sentry,kevinastone/sentry,kevinlondon/sentry,wong2/sentry,looker/sentry,beeftornado/sentry,JTCunning/sentry,JamesMura/sentry,JTCunning/sentry,BuildingLink/sentry,wong2/sentry,camilonova/sentry,gencer/sentry,BuildingLink/sentry,mvaled/sentry,gencer/sentry,BayanGroup/sentry,imankulov/sentry,beni55/sentry,gg7/sentry,felixbuenemann/sentry,Natim/sentry,wong2/sentry,kevinastone/sentry,looker/sentry,1tush/sentry,songyi199111/sentry,nicholasserra/sentry,wujuguang/sentry,SilentCircle/sentry,ifduyue/sentry,jean/sentry,camilonova/sentry,ifduyue/sentry,BuildingLink/sentry,wujuguang/sentry,wujuguang/sentry,TedaLIEz/sentry,pauloschilling/sentry,hongliang5623/sentry,beeftornado/sentry,mvaled/sentry,zenefits/sentry,beni55/sentry,daevaorn/sentry,1tush/sentry,jokey2k/sentry,korealerts1/sentry,gencer/sentry,rdio/sentry,ngonzalvez/sentry,JackDanger/sentry,BuildingLink/sentry,looker/sentry,1tush/sentry,gencer/sentry,TedaLIEz/sentry,JamesMura/sentry,vperron/sentry,argonemyth/sentry,ewdurbin/sentry,zenefits/sentry,jean/sentry,SilentCircle/sentry,drcapulet/sentry,gencer/sentry,NickPresta/sentry,zenefits/sentry,nicholasserra/sentry,ngonzalvez/sentry,drcapulet/sentry,NickPresta/sentry,daevaorn/sentry,ewdurbin/sentry,hongliang5623/sentry,fotinakis/sentry,ifduyue/sentry,kevinlondon/sentry,llonchj/sentry,mitsuhiko/sentry,zenefits/sentry,kevinastone/sentry,mvaled/sentry,JamesMura/sentry,ifduyue/sentry,mvaled/sentry,korealerts1/sentry,jean/sentry,NickPresta/sentry,daevaorn/sentry,beni55/sentry,SilentCircle/sentry,vperron/sentry,JamesMura/sentry,TedaLIEz/sentry,argonemyth/sentry,camilonova/sentry,ewdurbin/sentry,boneyao/sentry,llonchj/sentry,imankulov/sentry,Kryz/sentry,JackDanger/sentry,Kryz/sentry,mvaled/sentry,NickPresta/sentry
|
---
+++
@@ -4,18 +4,69 @@
import pickle
-from sentry.interfaces import Interface
-
-from sentry.testutils import TestCase
+from sentry.interfaces import Interface, Message, Stacktrace
+from sentry.models import Event
+from sentry.testutils import TestCase, fixture
-class InterfaceTests(TestCase):
+class InterfaceBase(TestCase):
+ @fixture
+ def event(self):
+ return Event(
+ id=1,
+ )
+
+
+class InterfaceTest(InterfaceBase):
+ @fixture
+ def interface(self):
+ return Interface(foo=1)
def test_init_sets_attrs(self):
- obj = Interface(foo=1)
- self.assertEqual(obj.attrs, ['foo'])
+ assert self.interface.attrs == ['foo']
def test_setstate_sets_attrs(self):
- data = pickle.dumps(Interface(foo=1))
+ data = pickle.dumps(self.interface)
obj = pickle.loads(data)
- self.assertEqual(obj.attrs, ['foo'])
+ assert obj.attrs == ['foo']
+
+ def test_to_html_default(self):
+ assert self.interface.to_html(self.event) == ''
+
+ def test_to_string_default(self):
+ assert self.interface.to_string(self.event) == ''
+
+
+class MessageTest(InterfaceBase):
+ @fixture
+ def interface(self):
+ return Message(message='Hello there %s!', params=('world',))
+
+ def test_serialize_behavior(self):
+ assert self.interface.serialize() == {
+ 'message': self.interface.message,
+ 'params': self.interface.params,
+ }
+
+ def test_get_hash_uses_message(self):
+ assert self.interface.get_hash() == [self.interface.message]
+
+ def test_get_search_context_with_params_as_list(self):
+ interface = self.interface
+ interface.params = ['world']
+ assert interface.get_search_context(self.event) == {
+ 'text': [interface.message] + list(interface.params)
+ }
+
+ def test_get_search_context_with_params_as_tuple(self):
+ assert self.interface.get_search_context(self.event) == {
+ 'text': [self.interface.message] + list(self.interface.params)
+ }
+
+ def test_get_search_context_with_params_as_dict(self):
+ interface = self.interface
+ interface.params = {'who': 'world'}
+ interface.message = 'Hello there %(who)s!'
+ assert self.interface.get_search_context(self.event) == {
+ 'text': [interface.message] + interface.params.values()
+ }
|
ac02378dcc611fb2c3b8a98e7480e02f64ee716d
|
polling_stations/apps/data_collection/management/commands/import_shepway.py
|
polling_stations/apps/data_collection/management/commands/import_shepway.py
|
from data_collection.morph_importer import BaseMorphApiImporter
class Command(BaseMorphApiImporter):
srid = 4326
districts_srid = 4326
council_id = 'E07000112'
elections = ['parl.2017-06-08']
scraper_name = 'wdiv-scrapers/DC-PollingStations-Shepway'
geom_type = 'geojson'
def district_record_to_dict(self, record):
poly = self.extract_geometry(record, self.geom_type, self.get_srid('districts'))
code = record['dist_code'].strip()
return {
'internal_council_id': code,
'name': record['district_n'].strip() + ' - ' + code,
'area': poly,
'polling_station_id': code,
}
def station_record_to_dict(self, record):
location = self.extract_geometry(record, self.geom_type, self.get_srid('stations'))
codes = record['polling_di'].split('\\')
codes = [code.strip() for code in codes]
stations = []
for code in codes:
stations.append({
'internal_council_id': code,
'postcode': '',
'address': record['address'].strip(),
'location': location,
})
return stations
|
from data_collection.morph_importer import BaseMorphApiImporter
class Command(BaseMorphApiImporter):
srid = 4326
districts_srid = 4326
council_id = 'E07000112'
#elections = ['parl.2017-06-08']
scraper_name = 'wdiv-scrapers/DC-PollingStations-Shepway'
geom_type = 'geojson'
def district_record_to_dict(self, record):
poly = self.extract_geometry(record, self.geom_type, self.get_srid('districts'))
code = record['dist_code'].strip()
return {
'internal_council_id': code,
'name': record['district_n'].strip() + ' - ' + code,
'area': poly,
'polling_station_id': code,
}
def station_record_to_dict(self, record):
location = self.extract_geometry(record, self.geom_type, self.get_srid('stations'))
codes = record['polling_di'].split('\\')
codes = [code.strip() for code in codes]
stations = []
for code in codes:
stations.append({
'internal_council_id': code,
'postcode': '',
'address': record['address'].strip(),
'location': location,
})
return stations
|
Remove Shepway election id (waiting on feedback)
|
Remove Shepway election id (waiting on feedback)
|
Python
|
bsd-3-clause
|
chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
|
---
+++
@@ -5,7 +5,7 @@
srid = 4326
districts_srid = 4326
council_id = 'E07000112'
- elections = ['parl.2017-06-08']
+ #elections = ['parl.2017-06-08']
scraper_name = 'wdiv-scrapers/DC-PollingStations-Shepway'
geom_type = 'geojson'
|
abbe40d2f65c8a4f8d9bae1322b1ec76466a27fb
|
modules/__init__.py
|
modules/__init__.py
|
import pkgutil, os, sys
def getmodules():
"""Returns all modules that are found in the current package.
Excludes modules starting with '__'"""
return [ name for _,name, _ in pkgutil.iter_modules( [ os.path.dirname( __file__ ) ] ) if name[0:2] != '__' ]
def getmodule( module ):
"""Import module <module> and return the class.
This returns the class modules.<module>.<module>"""
mod = __import__( 'modules.{0}'.format( module ), fromlist = [ module ] )
return getattr( mod, module )
def reload_module( module ):
"""Reload a module given the module name.
This should be just the name, not the full module path.
Arguments:
module: the name of the module
"""
try:
reload( getattr( sys.modules[ __name__ ], module ) )
except AttributeError:
pass
|
import pkgutil, os, sys
def getmodules():
"""Returns all modules that are found in the current package.
Excludes modules starting with '_'"""
return [ name for _,name, _ in pkgutil.iter_modules( [ os.path.dirname( __file__ ) ] ) if name[0] != '_' ]
def getmodule( module ):
"""Import module <module> and return the class.
This returns the class modules.<module>.<module>"""
mod = __import__( 'modules.{0}'.format( module ), fromlist = [ module ] )
return getattr( mod, module )
def reload_module( module ):
"""Reload a module given the module name.
This should be just the name, not the full module path.
Arguments:
module: the name of the module
"""
try:
reload( getattr( sys.modules[ __name__ ], module ) )
except AttributeError:
pass
|
Change module finder to ignore modules starting with '_'
|
Change module finder to ignore modules starting with '_'
|
Python
|
mit
|
jawsper/modularirc
|
---
+++
@@ -2,8 +2,8 @@
def getmodules():
"""Returns all modules that are found in the current package.
- Excludes modules starting with '__'"""
- return [ name for _,name, _ in pkgutil.iter_modules( [ os.path.dirname( __file__ ) ] ) if name[0:2] != '__' ]
+ Excludes modules starting with '_'"""
+ return [ name for _,name, _ in pkgutil.iter_modules( [ os.path.dirname( __file__ ) ] ) if name[0] != '_' ]
def getmodule( module ):
"""Import module <module> and return the class.
|
a0c636714530dac69edd02d821e7868a4a560541
|
utils/swift_build_support/swift_build_support/compiler_stage.py
|
utils/swift_build_support/swift_build_support/compiler_stage.py
|
# ===--- compiler_stage.py -----------------------------------------------===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https:#swift.org/LICENSE.txt for license information
# See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ===---------------------------------------------------------------------===#
class StageArgs(object):
def __init__(self, stage, args):
self.__dict__['postfix'] = stage.postfix
self.__dict__['stage'] = stage
self.__dict__['args'] = args
assert(not isinstance(self.args, StageArgs))
def _get_stage_prefix(self):
return self.__dict__['postfix']
def __getattr__(self, key):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
if not hasattr(args, real_key):
return None
return getattr(args, real_key)
def __setattr__(self, key, value):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
setattr(args, real_key, value)
class Stage(object):
def __init__(self, identifier, postfix=""):
self.identifier = identifier
self.postfix = postfix
STAGE_1 = Stage(1, "")
STAGE_2 = Stage(2, "_stage2")
|
# ===--- compiler_stage.py -----------------------------------------------===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https:#swift.org/LICENSE.txt for license information
# See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ===---------------------------------------------------------------------===#
class StageArgs(object):
def __init__(self, stage, args):
self.__dict__['postfix'] = stage.postfix
self.__dict__['stage'] = stage
self.__dict__['args'] = args
assert(not isinstance(self.args, StageArgs))
def _get_stage_prefix(self):
return self.__dict__['postfix']
def __getattr__(self, key):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
if not hasattr(args, real_key):
return None
return getattr(args, real_key)
def __setattr__(self, key, value):
real_key = '{}{}'.format(key, self._get_stage_prefix())
args = self.__dict__['args']
setattr(args, real_key, value)
class Stage(object):
def __init__(self, identifier, postfix=""):
self.identifier = identifier
self.postfix = postfix
STAGE_1 = Stage(1, "")
STAGE_2 = Stage(2, "_stage2")
|
Address Python lint issue in unrelated file
|
Address Python lint issue in unrelated file
|
Python
|
apache-2.0
|
benlangmuir/swift,xwu/swift,xwu/swift,rudkx/swift,atrick/swift,apple/swift,gregomni/swift,benlangmuir/swift,roambotics/swift,xwu/swift,JGiola/swift,JGiola/swift,apple/swift,apple/swift,glessard/swift,benlangmuir/swift,JGiola/swift,gregomni/swift,roambotics/swift,benlangmuir/swift,atrick/swift,xwu/swift,rudkx/swift,gregomni/swift,atrick/swift,ahoppen/swift,gregomni/swift,glessard/swift,ahoppen/swift,JGiola/swift,apple/swift,rudkx/swift,atrick/swift,rudkx/swift,gregomni/swift,xwu/swift,roambotics/swift,JGiola/swift,glessard/swift,roambotics/swift,apple/swift,ahoppen/swift,xwu/swift,glessard/swift,rudkx/swift,atrick/swift,glessard/swift,glessard/swift,ahoppen/swift,roambotics/swift,benlangmuir/swift,ahoppen/swift,rudkx/swift,apple/swift,benlangmuir/swift,atrick/swift,roambotics/swift,ahoppen/swift,xwu/swift,gregomni/swift,JGiola/swift
|
---
+++
@@ -9,6 +9,7 @@
# See https:#swift.org/CONTRIBUTORS.txt for the list of Swift project authors
#
# ===---------------------------------------------------------------------===#
+
class StageArgs(object):
def __init__(self, stage, args):
|
ed2580c14c9e1a0c00fc2df17abb85ab26f86f9f
|
tools/examples/check-modified.py
|
tools/examples/check-modified.py
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, False, adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
#!/usr/bin/python
#
# USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ...
#
# prints out the URL associated with each item
#
import sys
import os
import os.path
import svn.util
import svn.client
import svn.wc
FORCE_COMPARISON = 0
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
sys.exit(0)
def run(files):
svn.util.apr_initialize()
pool = svn.util.svn_pool_create(None)
for f in files:
dirpath = fullpath = os.path.abspath(f)
if not os.path.isdir(dirpath):
dirpath = os.path.dirname(dirpath)
adm_baton = svn.wc.svn_wc_adm_open(None, dirpath, False, True, pool)
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
if svn.wc.svn_wc_text_modified_p(fullpath, FORCE_COMPARISON,
adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
except:
print "? %s" % f
svn.wc.svn_wc_adm_close(adm_baton)
svn.util.svn_pool_destroy(pool)
svn.util.apr_terminate()
if __name__ == '__main__':
run(sys.argv[1:])
|
Fix a broken example script.
|
Fix a broken example script.
* check-modified.py (FORCE_COMPARISON): New variable.
(run): Add FORCE_COMPARISON arg to call to svn_wc_text_modified_p.
|
Python
|
apache-2.0
|
jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion
|
---
+++
@@ -11,6 +11,8 @@
import svn.util
import svn.client
import svn.wc
+
+FORCE_COMPARISON = 0
def usage():
print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n"
@@ -31,7 +33,8 @@
try:
entry = svn.wc.svn_wc_entry(fullpath, adm_baton, 0, pool)
- if svn.wc.svn_wc_text_modified_p(fullpath, False, adm_baton, pool):
+ if svn.wc.svn_wc_text_modified_p(fullpath, FORCE_COMPARISON,
+ adm_baton, pool):
print "M %s" % f
else:
print " %s" % f
|
3ad9029b6bfddb5cef1afed7e0093e8e26fe2884
|
shcol/config.py
|
shcol/config.py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
import logging
import os
import sys
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')
ENCODING = TERMINAL_STREAM.encoding or 'utf-8'
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013-2015, Sebastian Linke
# Released under the Simplified BSD license
# (see LICENSE file for details).
"""
Constants that are used by `shcol` in many places. This is meant to modified (if
needed) only *before* running `shcol`, since most of these constants are only
read during initialization of the `shcol`-package.
"""
import logging
import os
import sys
ERROR_STREAM = sys.stderr
INPUT_STREAM = sys.stdin
LINE_WIDTH = None
LINESEP = '\n'
LOGGER = logging.getLogger('shol')
MAKE_UNIQUE = False
ON_WINDOWS = 'windows' in os.getenv('os', '').lower()
PY_VERSION = sys.version_info[:2]
SORT_ITEMS = False
SPACING = 2
STARTER = os.path.join('bin', 'shcol' + ('.bat' if ON_WINDOWS else ''))
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')
ENCODING = getattr(TERMINAL_STREAM, 'encoding', 'utf-8')
|
Use "utf-8"-encoding if `TERMINAL_STREAM` lacks `encoding`-attribute.
|
Use "utf-8"-encoding if `TERMINAL_STREAM` lacks `encoding`-attribute.
|
Python
|
bsd-2-clause
|
seblin/shcol
|
---
+++
@@ -27,4 +27,4 @@
TERMINAL_STREAM = sys.stdout
UNICODE_TYPE = type(u'')
-ENCODING = TERMINAL_STREAM.encoding or 'utf-8'
+ENCODING = getattr(TERMINAL_STREAM, 'encoding', 'utf-8')
|
6af05b8af7bb284388af4960bbf240122f7f3dae
|
plugins/PerObjectSettingsTool/__init__.py
|
plugins/PerObjectSettingsTool/__init__.py
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Per Object Settings"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml"
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
|
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from . import PerObjectSettingsTool
from UM.i18n import i18nCatalog
i18n_catalog = i18nCatalog("uranium")
def getMetaData():
return {
"plugin": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings Tool"),
"author": "Ultimaker",
"version": "1.0",
"description": i18n_catalog.i18nc("@info:whatsthis", "Provides the Per Object Settings."),
"api": 2
},
"tool": {
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Per Object Settings"),
"icon": "setting_per_object",
"tool_panel": "PerObjectSettingsPanel.qml",
"weight": 3
},
}
def register(app):
return { "tool": PerObjectSettingsTool.PerObjectSettingsTool() }
|
Add order to PerObjectSettings tool
|
Add order to PerObjectSettings tool
|
Python
|
agpl-3.0
|
ynotstartups/Wanhao,hmflash/Cura,fieldOfView/Cura,senttech/Cura,hmflash/Cura,fieldOfView/Cura,Curahelper/Cura,senttech/Cura,Curahelper/Cura,totalretribution/Cura,totalretribution/Cura,ynotstartups/Wanhao
|
---
+++
@@ -19,7 +19,8 @@
"name": i18n_catalog.i18nc("@label", "Per Object Settings"),
"description": i18n_catalog.i18nc("@info:tooltip", "Configure Per Object Settings"),
"icon": "setting_per_object",
- "tool_panel": "PerObjectSettingsPanel.qml"
+ "tool_panel": "PerObjectSettingsPanel.qml",
+ "weight": 3
},
}
|
0aa1fb5d7f4eca6423a7d4b5cdd166bf29f48423
|
ordering/__init__.py
|
ordering/__init__.py
|
from fractions import Fraction
class Ordering:
_start = object()
_end = object()
def __init__(self):
self._labels = {
self._start: Fraction(0),
self._end: Fraction(1)
}
self._successors = {
self._start: self._end
}
self._predecessors = {
self._end: self._start
}
def insert_after(self, existing_item, new_item):
self._labels[new_item] = (self._labels[existing_item] + self._labels[self._successors[existing_item]]) / 2
self._successors[new_item] = self._successors[existing_item]
self._predecessors[new_item] = existing_item
self._predecessors[self._successors[existing_item]] = new_item
self._successors[existing_item] = new_item
def insert_before(self, existing_item, new_item):
self.insert_after(self._predecessors[existing_item], new_item)
def insert_start(self, new_item):
self.insert_after(self._start, new_item)
def insert_end(self, new_item):
self.insert_before(self._end, new_item)
def compare(self, left_item, right_item):
return self._labels[left_item] < self._labels[right_item]
|
from fractions import Fraction
from functools import total_ordering
class Ordering:
_start = object()
_end = object()
def __init__(self):
self._labels = {
self._start: Fraction(0),
self._end: Fraction(1)
}
self._successors = {
self._start: self._end
}
self._predecessors = {
self._end: self._start
}
def insert_after(self, existing_item, new_item):
self._labels[new_item] = (self._labels[existing_item] + self._labels[self._successors[existing_item]]) / 2
self._successors[new_item] = self._successors[existing_item]
self._predecessors[new_item] = existing_item
self._predecessors[self._successors[existing_item]] = new_item
self._successors[existing_item] = new_item
return OrderingItem(self, new_item)
def insert_before(self, existing_item, new_item):
return self.insert_after(self._predecessors[existing_item], new_item)
def insert_start(self, new_item):
return self.insert_after(self._start, new_item)
def insert_end(self, new_item):
return self.insert_before(self._end, new_item)
def compare(self, left_item, right_item):
return self._labels[left_item] < self._labels[right_item]
@total_ordering
class OrderingItem:
def __init__(self, ordering, item):
self.ordering = ordering
self.item = item
def __lt__(self, other):
return self.ordering.compare(self.item, other.item)
|
Add class representing an element in the ordering
|
Add class representing an element in the ordering
|
Python
|
mit
|
madman-bob/python-order-maintenance
|
---
+++
@@ -1,4 +1,5 @@
from fractions import Fraction
+from functools import total_ordering
class Ordering:
@@ -25,14 +26,26 @@
self._predecessors[self._successors[existing_item]] = new_item
self._successors[existing_item] = new_item
+ return OrderingItem(self, new_item)
+
def insert_before(self, existing_item, new_item):
- self.insert_after(self._predecessors[existing_item], new_item)
+ return self.insert_after(self._predecessors[existing_item], new_item)
def insert_start(self, new_item):
- self.insert_after(self._start, new_item)
+ return self.insert_after(self._start, new_item)
def insert_end(self, new_item):
- self.insert_before(self._end, new_item)
+ return self.insert_before(self._end, new_item)
def compare(self, left_item, right_item):
return self._labels[left_item] < self._labels[right_item]
+
+
+@total_ordering
+class OrderingItem:
+ def __init__(self, ordering, item):
+ self.ordering = ordering
+ self.item = item
+
+ def __lt__(self, other):
+ return self.ordering.compare(self.item, other.item)
|
b0e3585251445776683ba18441adae6ed3f0e210
|
ueberwachungspaket/decorators.py
|
ueberwachungspaket/decorators.py
|
from flask import abort, current_app, request
from functools import wraps
from twilio.util import RequestValidator
from config import *
def validate_twilio_request(f):
@wraps(f)
def decorated_function(*args, **kwargs):
validator = RequestValidator(TWILIO_SECRET)
request_valid = validator.validate(
request.url,
request.form,
request.headers.get("X-TWILIO-SIGNATURE", ""))
if request_valid or current_app.debug:
return f(*args, **kwargs)
else:
return abort(403)
return decorated_function
|
from flask import abort, current_app, request
from functools import wraps
from twilio.util import RequestValidator
from config import *
def validate_twilio_request(f):
@wraps(f)
def decorated_function(*args, **kwargs):
validator = RequestValidator(TWILIO_SECRET)
request_valid = validator.validate(
request.url.encode("idna"),
request.form,
request.headers.get("X-TWILIO-SIGNATURE", ""))
if request_valid or current_app.debug:
return f(*args, **kwargs)
else:
return abort(403)
return decorated_function
|
Convert Twilio URL to IDN.
|
Convert Twilio URL to IDN.
|
Python
|
mit
|
PeterTheOne/ueberwachungspaket.at,PeterTheOne/ueberwachungspaket.at,PeterTheOne/ueberwachungspaket.at
|
---
+++
@@ -9,7 +9,7 @@
validator = RequestValidator(TWILIO_SECRET)
request_valid = validator.validate(
- request.url,
+ request.url.encode("idna"),
request.form,
request.headers.get("X-TWILIO-SIGNATURE", ""))
|
3b61b9dfeda38e0a7afd5ec90b32f8abab18ef4f
|
unzip.py
|
unzip.py
|
#!/usr/bin/env python3
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
import argparse
import os
import zipfile
parser = argparse.ArgumentParser(description = "Extract zip file includes cp932 encoding file name")
parser.add_argument("file")
args = parser.parse_args()
with zipfile.ZipFile(args.file, 'r') as archive:
for item in archive.namelist():
filename = item.encode("cp437").decode("cp932")
directory = os.path.dirname(filename)
if not os.path.exists(directory):
os.makedirs(directory)
if os.path.basename(filename):
with open(filename, "wb") as data:
data.write(archive.read(item))
# Local variables:
# tab-width: 4
# c-basic-offset: 4
# c-hanging-comment-ender-p: nil
# End:
|
#!/usr/bin/env python3
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:
import argparse
import os
import zipfile
parser = argparse.ArgumentParser(description = "Extract zip file includes cp932 encoding file name")
parser.add_argument("file")
parser.add_argument("-d", "--directory", nargs="?", type=str, default="")
args = parser.parse_args()
with zipfile.ZipFile(args.file, 'r') as archive:
for item in archive.namelist():
filename = os.path.join(args.directory, item.encode("cp437").decode("cp932"))
directory = os.path.dirname(filename)
if not os.path.exists(directory):
os.makedirs(directory)
if os.path.basename(filename):
with open(filename, "wb") as data:
data.write(archive.read(item))
# Local variables:
# tab-width: 4
# c-basic-offset: 4
# c-hanging-comment-ender-p: nil
# End:
|
Add -d / --directory option
|
Add -d / --directory option
|
Python
|
mit
|
fujimakishouten/unzip-cp932
|
---
+++
@@ -11,11 +11,12 @@
parser = argparse.ArgumentParser(description = "Extract zip file includes cp932 encoding file name")
parser.add_argument("file")
+parser.add_argument("-d", "--directory", nargs="?", type=str, default="")
args = parser.parse_args()
with zipfile.ZipFile(args.file, 'r') as archive:
for item in archive.namelist():
- filename = item.encode("cp437").decode("cp932")
+ filename = os.path.join(args.directory, item.encode("cp437").decode("cp932"))
directory = os.path.dirname(filename)
if not os.path.exists(directory):
|
4d29aa24b39285c491182edd69ecb7c22a9d643d
|
ceph_medic/tests/test_main.py
|
ceph_medic/tests/test_main.py
|
import pytest
import ceph_medic.main
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert out.out == ''
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
|
import pytest
import ceph_medic.main
from mock import patch
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'the given ssh config path does not exist' in out.out
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
def fake_exists(path):
if path == ssh_config:
return True
if path.endswith('cephmedic.conf'):
return False
return True
with patch.object(ceph_medic.main.os.path, 'exists') as m_exists:
m_exists.side_effect = fake_exists
ceph_medic.main.Medic(argv)
out = capsys.readouterr()
assert 'tssh config path does not exist' not in out.out
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
|
Fix test breakage when ssh_config missing
|
tests: Fix test breakage when ssh_config missing
I assumed /etc/ssh/ssh_config would be present, but it turns out in a
mock chroot environment it isn't.
Signed-off-by: Zack Cerza <d7cdf09fc0f0426e98c9978ee42da5d61fa54986@redhat.com>
|
Python
|
mit
|
alfredodeza/ceph-doctor
|
---
+++
@@ -1,5 +1,7 @@
import pytest
import ceph_medic.main
+
+from mock import patch
class TestMain(object):
@@ -16,7 +18,17 @@
def test_valid_ssh_config(self, capsys):
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
- ceph_medic.main.Medic(argv)
+
+ def fake_exists(path):
+ if path == ssh_config:
+ return True
+ if path.endswith('cephmedic.conf'):
+ return False
+ return True
+
+ with patch.object(ceph_medic.main.os.path, 'exists') as m_exists:
+ m_exists.side_effect = fake_exists
+ ceph_medic.main.Medic(argv)
out = capsys.readouterr()
- assert out.out == ''
+ assert 'tssh config path does not exist' not in out.out
assert ssh_config == ceph_medic.main.ceph_medic.config.ssh_config
|
93acb34d999f89d23d2b613f12c1c767304c2ad6
|
gor/middleware.py
|
gor/middleware.py
|
# coding: utf-8
import os, sys
from .base import Gor
from tornado import gen, ioloop, queues
class TornadoGor(Gor):
def __init__(self, *args, **kwargs):
super(TornadoGor, self).__init__(*args, **kwargs)
self.q = queues.Queue()
self.concurrency = kwargs.get('concurrency', 2)
@gen.coroutine
def _process(self):
line = yield self.q.get()
try:
msg = self.parse_message(line)
if msg:
self.emit(msg, line)
finally:
self.q.task_done()
@gen.coroutine
def _worker(self):
while True:
yield self._process()
@gen.coroutine
def _run(self):
for _ in range(self.concurrency):
self._worker()
while True:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
try:
sys.exit(0)
except SystemExit:
os._exit(0)
self.q.put(line)
yield
def run(self):
self.io_loop = ioloop.IOLoop.current()
self.io_loop.run_sync(self._run)
|
# coding: utf-8
import sys
import errno
import logging
from .base import Gor
from tornado import gen, ioloop, queues
import contextlib
from tornado.stack_context import StackContext
@contextlib.contextmanager
def die_on_error():
try:
yield
except Exception:
logging.error("exception in asynchronous operation", exc_info=True)
sys.exit(1)
class TornadoGor(Gor):
def __init__(self, *args, **kwargs):
super(TornadoGor, self).__init__(*args, **kwargs)
self.q = queues.Queue()
self.concurrency = kwargs.get('concurrency', 2)
@gen.coroutine
def _process(self):
line = yield self.q.get()
try:
msg = self.parse_message(line)
if msg:
self.emit(msg, line)
finally:
self.q.task_done()
@gen.coroutine
def _worker(self):
while True:
yield self._process()
@gen.coroutine
def _run(self):
for _ in range(self.concurrency):
self._worker()
while True:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
ioloop.IOLoop.instance().stop()
break
self.q.put(line)
yield
def run(self):
with StackContext(die_on_error):
self.io_loop = ioloop.IOLoop.current()
self.io_loop.run_sync(self._run)
sys.exit(errno.EINTR)
|
Exit as soon as KeyboardInterrupt catched
|
Exit as soon as KeyboardInterrupt catched
|
Python
|
mit
|
amyangfei/GorMW
|
---
+++
@@ -1,10 +1,24 @@
# coding: utf-8
-import os, sys
+import sys
+import errno
+import logging
from .base import Gor
from tornado import gen, ioloop, queues
+
+
+import contextlib
+from tornado.stack_context import StackContext
+
+@contextlib.contextmanager
+def die_on_error():
+ try:
+ yield
+ except Exception:
+ logging.error("exception in asynchronous operation", exc_info=True)
+ sys.exit(1)
class TornadoGor(Gor):
@@ -38,13 +52,13 @@
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
- try:
- sys.exit(0)
- except SystemExit:
- os._exit(0)
+ ioloop.IOLoop.instance().stop()
+ break
self.q.put(line)
yield
def run(self):
- self.io_loop = ioloop.IOLoop.current()
- self.io_loop.run_sync(self._run)
+ with StackContext(die_on_error):
+ self.io_loop = ioloop.IOLoop.current()
+ self.io_loop.run_sync(self._run)
+ sys.exit(errno.EINTR)
|
aaaab0d93723e880119afb52840718634b184054
|
falcom/logtree.py
|
falcom/logtree.py
|
# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class MutableTree:
value = None
def full_length (self):
return 0
def walk (self):
return iter(())
def __len__ (self):
return 0
def __iter__ (self):
return iter(())
def __getitem__ (self, index):
raise IndexError("tree index out of range")
def __repr__ (self):
return "<{}>".format(self.__class__.__name__)
|
# Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
class MutableTree:
def __init__ (self):
self.value = None
def full_length (self):
return 0
def walk (self):
return iter(())
def __len__ (self):
return 0
def __iter__ (self):
return iter(())
def __getitem__ (self, index):
raise IndexError("tree index out of range")
def __repr__ (self):
return "<{}>".format(self.__class__.__name__)
|
Set MutableTree.value on the object only
|
Set MutableTree.value on the object only
|
Python
|
bsd-3-clause
|
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
|
---
+++
@@ -4,7 +4,8 @@
class MutableTree:
- value = None
+ def __init__ (self):
+ self.value = None
def full_length (self):
return 0
|
918e1c59aa2d0e790eb993e091fd7a327fd12cc4
|
utils.py
|
utils.py
|
import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
text = re.sub(r'<a.*?</a>', '', text)
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if not string:
return 'No Description Found'
if strip_html:
string = strip_html_tags(string)
if markdown:
string = text_maker.handle(string)
return string
def get_formatted_book_data(book_data):
template = textwrap.dedent("""\
*Title:* {0} by {1}
*Rating:* {2} by {3} users
*Description:* {4}
*Link*: [click me]({5})
Tip: {6}""")
title = book_data['title']
authors = book_data['authors']
average_rating = book_data['average_rating']
ratings_count = book_data['ratings_count']
description = html_to_md(book_data.get('description', ''))
url = book_data['url']
tip = 'Use author name also for better search results'
response = template.format(title, authors, average_rating, ratings_count,
description, url, tip)
return response
|
import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
text = re.sub(r'<a.*?</a>', '', text)
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if not string:
return 'No Description Found'
if strip_html:
string = strip_html_tags(string)
if markdown:
string = text_maker.handle(string)
return string
def get_formatted_book_data(book_data):
template = textwrap.dedent("""\
*Title:* {0} by {1}
*Rating:* {2} by {3} users
*Description:* {4}
Pages: {7}, Year: {8}
*Link*: [click me]({5})
Tip: {6}""")
title = book_data['title']
authors = book_data['authors']
average_rating = book_data['average_rating']
ratings_count = book_data['ratings_count']
description = html_to_md(book_data.get('description', ''))
url = book_data['url']
pages = book_data['publication_year']
year = book_data['num_pages']
tip = 'Use author name also for better search results'
response = template.format(
title, authors, average_rating, ratings_count, description, url, tip,
pages, year)
return response
|
Update `get_formatted_book_data` to include page number and year
|
Update `get_formatted_book_data` to include page number and year
|
Python
|
mit
|
avinassh/Laozi,avinassh/Laozi
|
---
+++
@@ -27,6 +27,7 @@
*Title:* {0} by {1}
*Rating:* {2} by {3} users
*Description:* {4}
+ Pages: {7}, Year: {8}
*Link*: [click me]({5})
Tip: {6}""")
@@ -36,8 +37,11 @@
ratings_count = book_data['ratings_count']
description = html_to_md(book_data.get('description', ''))
url = book_data['url']
+ pages = book_data['publication_year']
+ year = book_data['num_pages']
tip = 'Use author name also for better search results'
- response = template.format(title, authors, average_rating, ratings_count,
- description, url, tip)
+ response = template.format(
+ title, authors, average_rating, ratings_count, description, url, tip,
+ pages, year)
return response
|
7b0bd58c359f5ea21af907cb90234171a6cfca5c
|
photobox/photobox.py
|
photobox/photobox.py
|
from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
from main import Photobox
from rcswitch import RCSwitch
##########
# config #
##########
photodirectory = '/var/www/html/'
cheesepicfolder = '/home/pi/cheesepics/'
windowwidth = 1024
windowheight = 768
camera = Gphoto()
switch = RCSwitch(2352753, 2352754, "NOT_IMPLEMENTED")
##########
filesystemFolder = RealFolder(photodirectory)
cheesepicFolder = RealFolder(cheesepicfolder)
photofolder = Photofolder(filesystemFolder)
photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch)
photobox.start()
|
from cheesefolder import Cheesefolder
from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
from main import Photobox
from rcswitch import RCSwitch
##########
# config #
##########
photodirectory = '/var/www/html/'
cheesepicpath = '/home/pi/cheesepics/'
windowwidth = 1024
windowheight = 768
camera = Gphoto()
switch = RCSwitch(2352753, 2352754, "NOT_IMPLEMENTED")
##########
filesystemFolder = RealFolder(photodirectory)
cheesepicFolder = RealFolder(cheesepicpath)
cheesef = Cheesefolder(cheesepicFolder)
photofolder = Photofolder(filesystemFolder)
photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch, cheesef)
photobox.start()
|
Use the correct chesefolder objects
|
Use the correct chesefolder objects
|
Python
|
mit
|
MarkusAmshove/Photobox
|
---
+++
@@ -1,3 +1,4 @@
+from cheesefolder import Cheesefolder
from photofolder import Photofolder
from folder import RealFolder
from gphotocamera import Gphoto
@@ -8,14 +9,15 @@
# config #
##########
photodirectory = '/var/www/html/'
-cheesepicfolder = '/home/pi/cheesepics/'
+cheesepicpath = '/home/pi/cheesepics/'
windowwidth = 1024
windowheight = 768
camera = Gphoto()
switch = RCSwitch(2352753, 2352754, "NOT_IMPLEMENTED")
##########
filesystemFolder = RealFolder(photodirectory)
-cheesepicFolder = RealFolder(cheesepicfolder)
+cheesepicFolder = RealFolder(cheesepicpath)
+cheesef = Cheesefolder(cheesepicFolder)
photofolder = Photofolder(filesystemFolder)
-photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch)
+photobox = Photobox((windowwidth, windowheight), photofolder, camera, switch, cheesef)
photobox.start()
|
c3ab90da466e2c4479c9c1865f4302c9c8bdb8e9
|
tests/extmod/ujson_loads.py
|
tests/extmod/ujson_loads.py
|
try:
import ujson as json
except:
import json
def my_print(o):
if isinstance(o, dict):
print('sorted dict', sorted(o.items()))
else:
print(o)
my_print(json.loads('null'))
my_print(json.loads('false'))
my_print(json.loads('true'))
my_print(json.loads('1'))
my_print(json.loads('1.2'))
my_print(json.loads('1e2'))
my_print(json.loads('-2'))
my_print(json.loads('-2.3'))
my_print(json.loads('-2e3'))
my_print(json.loads('-2e-3'))
my_print(json.loads('"abc\\u0064e"'))
my_print(json.loads('[]'))
my_print(json.loads('[null]'))
my_print(json.loads('[null,false,true]'))
my_print(json.loads(' [ null , false , true ] '))
my_print(json.loads('{}'))
my_print(json.loads('{"a":true}'))
my_print(json.loads('{"a":null, "b":false, "c":true}'))
my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
|
try:
import ujson as json
except:
import json
def my_print(o):
if isinstance(o, dict):
print('sorted dict', sorted(o.items()))
elif isinstance(o, float):
print('%.3f' % o)
else:
print(o)
my_print(json.loads('null'))
my_print(json.loads('false'))
my_print(json.loads('true'))
my_print(json.loads('1'))
my_print(json.loads('1.2'))
my_print(json.loads('1e2'))
my_print(json.loads('-2'))
my_print(json.loads('-2.3'))
my_print(json.loads('-2e3'))
my_print(json.loads('-2e-3'))
my_print(json.loads('"abc\\u0064e"'))
my_print(json.loads('[]'))
my_print(json.loads('[null]'))
my_print(json.loads('[null,false,true]'))
my_print(json.loads(' [ null , false , true ] '))
my_print(json.loads('{}'))
my_print(json.loads('{"a":true}'))
my_print(json.loads('{"a":null, "b":false, "c":true}'))
my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))
|
Make printing of floats hopefully more portable.
|
tests: Make printing of floats hopefully more portable.
|
Python
|
mit
|
dinau/micropython,selste/micropython,danicampora/micropython,turbinenreiter/micropython,tobbad/micropython,SungEun-Steve-Kim/test-mp,SungEun-Steve-Kim/test-mp,turbinenreiter/micropython,matthewelse/micropython,dxxb/micropython,ahotam/micropython,torwag/micropython,swegener/micropython,jmarcelino/pycom-micropython,martinribelotta/micropython,EcmaXp/micropython,skybird6672/micropython,tdautc19841202/micropython,misterdanb/micropython,adafruit/circuitpython,mgyenik/micropython,tobbad/micropython,infinnovation/micropython,adafruit/circuitpython,deshipu/micropython,cloudformdesign/micropython,ceramos/micropython,oopy/micropython,KISSMonX/micropython,tobbad/micropython,skybird6672/micropython,blmorris/micropython,utopiaprince/micropython,lowRISC/micropython,tuc-osg/micropython,blazewicz/micropython,cnoviello/micropython,noahwilliamsson/micropython,KISSMonX/micropython,stonegithubs/micropython,ernesto-g/micropython,swegener/micropython,adafruit/micropython,HenrikSolver/micropython,mhoffma/micropython,alex-robbins/micropython,adamkh/micropython,jlillest/micropython,mgyenik/micropython,selste/micropython,adafruit/circuitpython,bvernoux/micropython,turbinenreiter/micropython,Peetz0r/micropython-esp32,blazewicz/micropython,pfalcon/micropython,praemdonck/micropython,suda/micropython,ganshun666/micropython,pozetroninc/micropython,jimkmc/micropython,SHA2017-badge/micropython-esp32,Vogtinator/micropython,Peetz0r/micropython-esp32,cnoviello/micropython,omtinez/micropython,TDAbboud/micropython,dxxb/micropython,ceramos/micropython,deshipu/micropython,tuc-osg/micropython,adafruit/circuitpython,mpalomer/micropython,omtinez/micropython,tralamazza/micropython,dxxb/micropython,ruffy91/micropython,emfcamp/micropython,dmazzella/micropython,orionrobots/micropython,danicampora/micropython,danicampora/micropython,Timmenem/micropython,aethaniel/micropython,ericsnowcurrently/micropython,kostyll/micropython,adafruit/circuitpython,hiway/micropython,tralamazza/micropython,tdautc19841202/micropython,SHA2017-badge/micropython-esp32,bvernoux/micropython,Vogtinator/micropython,vriera/micropython,neilh10/micropython,ryannathans/micropython,ganshun666/micropython,Timmenem/micropython,xuxiaoxin/micropython,supergis/micropython,slzatz/micropython,pozetroninc/micropython,kostyll/micropython,chrisdearman/micropython,lowRISC/micropython,dinau/micropython,warner83/micropython,infinnovation/micropython,jmarcelino/pycom-micropython,hosaka/micropython,suda/micropython,martinribelotta/micropython,praemdonck/micropython,cwyark/micropython,dhylands/micropython,methoxid/micropystat,paul-xxx/micropython,redbear/micropython,utopiaprince/micropython,praemdonck/micropython,PappaPeppar/micropython,Vogtinator/micropython,AriZuu/micropython,kerneltask/micropython,tuc-osg/micropython,mgyenik/micropython,aethaniel/micropython,Timmenem/micropython,ceramos/micropython,toolmacher/micropython,dhylands/micropython,feilongfl/micropython,SHA2017-badge/micropython-esp32,mianos/micropython,ahotam/micropython,EcmaXp/micropython,SungEun-Steve-Kim/test-mp,SHA2017-badge/micropython-esp32,toolmacher/micropython,cloudformdesign/micropython,adamkh/micropython,henriknelson/micropython,ahotam/micropython,ceramos/micropython,henriknelson/micropython,hiway/micropython,feilongfl/micropython,MrSurly/micropython,blmorris/micropython,utopiaprince/micropython,ChuckM/micropython,KISSMonX/micropython,neilh10/micropython,supergis/micropython,pramasoul/micropython,xuxiaoxin/micropython,xyb/micropython,emfcamp/micropython,vitiral/micropython,dmazzella/micropython,cloudformdesign/micropython,xuxiaoxin/micropython,suda/micropython,firstval/micropython,ericsnowcurrently/micropython,praemdonck/micropython,MrSurly/micropython-esp32,selste/micropython,dhylands/micropython,martinribelotta/micropython,noahwilliamsson/micropython,drrk/micropython,noahchense/micropython,tobbad/micropython,orionrobots/micropython,lbattraw/micropython,slzatz/micropython,jimkmc/micropython,EcmaXp/micropython,alex-robbins/micropython,micropython/micropython-esp32,drrk/micropython,mpalomer/micropython,danicampora/micropython,aethaniel/micropython,drrk/micropython,matthewelse/micropython,supergis/micropython,firstval/micropython,feilongfl/micropython,MrSurly/micropython-esp32,cwyark/micropython,alex-march/micropython,galenhz/micropython,tuc-osg/micropython,hiway/micropython,deshipu/micropython,pramasoul/micropython,xhat/micropython,neilh10/micropython,micropython/micropython-esp32,dinau/micropython,firstval/micropython,selste/micropython,ryannathans/micropython,skybird6672/micropython,adafruit/micropython,vriera/micropython,ganshun666/micropython,slzatz/micropython,heisewangluo/micropython,ahotam/micropython,turbinenreiter/micropython,drrk/micropython,stonegithubs/micropython,rubencabrera/micropython,rubencabrera/micropython,xuxiaoxin/micropython,suda/micropython,omtinez/micropython,dinau/micropython,galenhz/micropython,vriera/micropython,rubencabrera/micropython,swegener/micropython,orionrobots/micropython,paul-xxx/micropython,infinnovation/micropython,oopy/micropython,misterdanb/micropython,ceramos/micropython,dxxb/micropython,ganshun666/micropython,henriknelson/micropython,tdautc19841202/micropython,methoxid/micropystat,toolmacher/micropython,rubencabrera/micropython,torwag/micropython,kostyll/micropython,skybird6672/micropython,SungEun-Steve-Kim/test-mp,mianos/micropython,alex-march/micropython,tdautc19841202/micropython,heisewangluo/micropython,PappaPeppar/micropython,AriZuu/micropython,kostyll/micropython,tdautc19841202/micropython,ernesto-g/micropython,MrSurly/micropython,trezor/micropython,toolmacher/micropython,adafruit/circuitpython,xhat/micropython,swegener/micropython,torwag/micropython,redbear/micropython,orionrobots/micropython,galenhz/micropython,alex-march/micropython,micropython/micropython-esp32,warner83/micropython,omtinez/micropython,tralamazza/micropython,alex-march/micropython,noahwilliamsson/micropython,pozetroninc/micropython,jimkmc/micropython,dhylands/micropython,aethaniel/micropython,stonegithubs/micropython,cnoviello/micropython,selste/micropython,pfalcon/micropython,Peetz0r/micropython-esp32,heisewangluo/micropython,mhoffma/micropython,KISSMonX/micropython,cloudformdesign/micropython,ernesto-g/micropython,utopiaprince/micropython,ernesto-g/micropython,alex-robbins/micropython,xyb/micropython,misterdanb/micropython,firstval/micropython,puuu/micropython,jlillest/micropython,matthewelse/micropython,trezor/micropython,lbattraw/micropython,deshipu/micropython,oopy/micropython,EcmaXp/micropython,mianos/micropython,cloudformdesign/micropython,Peetz0r/micropython-esp32,chrisdearman/micropython,dxxb/micropython,lbattraw/micropython,hiway/micropython,MrSurly/micropython-esp32,bvernoux/micropython,HenrikSolver/micropython,methoxid/micropystat,hosaka/micropython,MrSurly/micropython,HenrikSolver/micropython,ahotam/micropython,pfalcon/micropython,firstval/micropython,cwyark/micropython,ericsnowcurrently/micropython,blmorris/micropython,pozetroninc/micropython,warner83/micropython,trezor/micropython,drrk/micropython,ganshun666/micropython,suda/micropython,PappaPeppar/micropython,martinribelotta/micropython,PappaPeppar/micropython,noahchense/micropython,KISSMonX/micropython,ruffy91/micropython,chrisdearman/micropython,HenrikSolver/micropython,puuu/micropython,mhoffma/micropython,xyb/micropython,noahchense/micropython,mgyenik/micropython,blmorris/micropython,pramasoul/micropython,jimkmc/micropython,rubencabrera/micropython,dhylands/micropython,ChuckM/micropython,turbinenreiter/micropython,HenrikSolver/micropython,pozetroninc/micropython,paul-xxx/micropython,blazewicz/micropython,xyb/micropython,ryannathans/micropython,jmarcelino/pycom-micropython,adamkh/micropython,dmazzella/micropython,pramasoul/micropython,oopy/micropython,MrSurly/micropython-esp32,heisewangluo/micropython,hosaka/micropython,mpalomer/micropython,vitiral/micropython,henriknelson/micropython,torwag/micropython,Vogtinator/micropython,jmarcelino/pycom-micropython,mgyenik/micropython,noahwilliamsson/micropython,mpalomer/micropython,dmazzella/micropython,warner83/micropython,bvernoux/micropython,tobbad/micropython,vitiral/micropython,aethaniel/micropython,jlillest/micropython,deshipu/micropython,methoxid/micropystat,methoxid/micropystat,alex-march/micropython,danicampora/micropython,mhoffma/micropython,trezor/micropython,MrSurly/micropython-esp32,MrSurly/micropython,praemdonck/micropython,PappaPeppar/micropython,adamkh/micropython,adafruit/micropython,lowRISC/micropython,mhoffma/micropython,chrisdearman/micropython,lowRISC/micropython,supergis/micropython,hosaka/micropython,infinnovation/micropython,omtinez/micropython,vriera/micropython,Vogtinator/micropython,ericsnowcurrently/micropython,mpalomer/micropython,dinau/micropython,adafruit/micropython,cwyark/micropython,ruffy91/micropython,slzatz/micropython,pfalcon/micropython,chrisdearman/micropython,slzatz/micropython,feilongfl/micropython,xyb/micropython,henriknelson/micropython,kerneltask/micropython,mianos/micropython,blazewicz/micropython,matthewelse/micropython,supergis/micropython,Timmenem/micropython,utopiaprince/micropython,kerneltask/micropython,SungEun-Steve-Kim/test-mp,noahchense/micropython,hosaka/micropython,swegener/micropython,cnoviello/micropython,micropython/micropython-esp32,redbear/micropython,redbear/micropython,xhat/micropython,puuu/micropython,kerneltask/micropython,heisewangluo/micropython,bvernoux/micropython,ryannathans/micropython,paul-xxx/micropython,galenhz/micropython,skybird6672/micropython,ernesto-g/micropython,torwag/micropython,kostyll/micropython,trezor/micropython,misterdanb/micropython,lowRISC/micropython,blazewicz/micropython,xhat/micropython,ruffy91/micropython,Peetz0r/micropython-esp32,galenhz/micropython,AriZuu/micropython,pramasoul/micropython,TDAbboud/micropython,vitiral/micropython,emfcamp/micropython,blmorris/micropython,tuc-osg/micropython,feilongfl/micropython,Timmenem/micropython,jlillest/micropython,matthewelse/micropython,ericsnowcurrently/micropython,jimkmc/micropython,stonegithubs/micropython,lbattraw/micropython,martinribelotta/micropython,noahchense/micropython,alex-robbins/micropython,ruffy91/micropython,SHA2017-badge/micropython-esp32,lbattraw/micropython,xuxiaoxin/micropython,adafruit/micropython,stonegithubs/micropython,tralamazza/micropython,TDAbboud/micropython,AriZuu/micropython,ChuckM/micropython,oopy/micropython,infinnovation/micropython,misterdanb/micropython,orionrobots/micropython,paul-xxx/micropython,TDAbboud/micropython,kerneltask/micropython,xhat/micropython,EcmaXp/micropython,micropython/micropython-esp32,ChuckM/micropython,noahwilliamsson/micropython,redbear/micropython,TDAbboud/micropython,puuu/micropython,neilh10/micropython,pfalcon/micropython,MrSurly/micropython,hiway/micropython,ryannathans/micropython,puuu/micropython,vriera/micropython,vitiral/micropython,cnoviello/micropython,warner83/micropython,emfcamp/micropython,AriZuu/micropython,mianos/micropython,jmarcelino/pycom-micropython,jlillest/micropython,ChuckM/micropython,alex-robbins/micropython,adamkh/micropython,cwyark/micropython,toolmacher/micropython,emfcamp/micropython,matthewelse/micropython,neilh10/micropython
|
---
+++
@@ -6,6 +6,8 @@
def my_print(o):
if isinstance(o, dict):
print('sorted dict', sorted(o.items()))
+ elif isinstance(o, float):
+ print('%.3f' % o)
else:
print(o)
|
6cb6b3d0f9bc3bf8f1662129cd4bd55eec42e6ff
|
pyqode/python/folding.py
|
pyqode/python/folding.py
|
"""
Contains the python code folding mode
"""
from pyqode.core.api import IndentFoldDetector, TextBlockHelper, TextHelper
class PythonFoldDetector(IndentFoldDetector):
def detect_fold_level(self, prev_block, block):
# Python is an indent based language so use indentation for folding
# makes sense but we restrict new regions to indentation after a ':',
# that way only the real logical blocks are displayed.
lvl = super().detect_fold_level(prev_block, block)
prev_lvl = TextBlockHelper.get_fold_lvl(prev_block)
# cancel false indentation, indentation can only happen if there is
# ':' on the previous line
if(prev_block and
lvl > prev_lvl and
not prev_block.text().strip().endswith(':')):
lvl = prev_lvl
th = TextHelper(self.editor)
fmts = ['docstring']
wasdocstring = th.is_comment_or_string(prev_block, formats=fmts)
if block.docstring:
if wasdocstring:
# find block that starts the docstring
p = prev_block.previous()
wasdocstring = th.is_comment_or_string(p, formats=fmts)
while wasdocstring or p.text().strip() == '':
p = p.previous()
wasdocstring = th.is_comment_or_string(p, formats=fmts)
lvl = TextBlockHelper.get_fold_lvl(p.next()) + 1
return lvl
|
"""
Contains the python code folding mode
"""
from pyqode.core.api import IndentFoldDetector, TextBlockHelper, TextHelper
class PythonFoldDetector(IndentFoldDetector):
def detect_fold_level(self, prev_block, block):
# Python is an indent based language so use indentation for folding
# makes sense but we restrict new regions to indentation after a ':',
# that way only the real logical blocks are displayed.
lvl = super().detect_fold_level(prev_block, block)
prev_lvl = TextBlockHelper.get_fold_lvl(prev_block)
# cancel false indentation, indentation can only happen if there is
# ':' on the previous line
# strip end of line comments
txt = prev_block.text().strip() if prev_block else ''
if txt.find('#') != -1:
txt = txt[:txt.find('#')].strip()
if(prev_block and lvl > prev_lvl and not txt.endswith(':')):
lvl = prev_lvl
th = TextHelper(self.editor)
fmts = ['docstring']
wasdocstring = th.is_comment_or_string(prev_block, formats=fmts)
if block.docstring:
if wasdocstring:
# find block that starts the docstring
p = prev_block.previous()
wasdocstring = th.is_comment_or_string(p, formats=fmts)
while wasdocstring or p.text().strip() == '':
p = p.previous()
wasdocstring = th.is_comment_or_string(p, formats=fmts)
lvl = TextBlockHelper.get_fold_lvl(p.next()) + 1
return lvl
|
Fix bug with end of line comments which prevent detection of new fold level
|
Fix bug with end of line comments which prevent detection of new fold level
|
Python
|
mit
|
zwadar/pyqode.python,pyQode/pyqode.python,pyQode/pyqode.python,mmolero/pyqode.python
|
---
+++
@@ -13,9 +13,11 @@
prev_lvl = TextBlockHelper.get_fold_lvl(prev_block)
# cancel false indentation, indentation can only happen if there is
# ':' on the previous line
- if(prev_block and
- lvl > prev_lvl and
- not prev_block.text().strip().endswith(':')):
+ # strip end of line comments
+ txt = prev_block.text().strip() if prev_block else ''
+ if txt.find('#') != -1:
+ txt = txt[:txt.find('#')].strip()
+ if(prev_block and lvl > prev_lvl and not txt.endswith(':')):
lvl = prev_lvl
th = TextHelper(self.editor)
fmts = ['docstring']
|
6ffa10ad56acefe3d3178ff140ebe048bb1a1df9
|
Code/Python/Kamaelia/Kamaelia/Apps/SocialBookmarks/Print.py
|
Code/Python/Kamaelia/Kamaelia/Apps/SocialBookmarks/Print.py
|
import sys
import os
import inspect
def __LINE__ ():
caller = inspect.stack()[1]
return int (caller[2])
def __FUNC__ ():
caller = inspect.stack()[1]
return caller[3]
def __BOTH__():
caller = inspect.stack()[1]
return int (caller[2]), caller[3], caller[1]
def Print(*args):
caller = inspect.stack()[1]
filename = str(os.path.basename(caller[1]))
sys.stdout.write(filename+ " : "+ str(int (caller[2])) + " : ")
for arg in args:
try:
x = str(arg)
except:
pass
try:
print x,
except:
try:
print unicode(x, errors="ignore"),
except:
try:
sys.stdout.write(arg.encode("ascii","ignore"))
except:
print "FAILED PRINT"
print
sys.stdout.flush()
|
import sys
import os
import inspect
import time
def __LINE__ ():
caller = inspect.stack()[1]
return int (caller[2])
def __FUNC__ ():
caller = inspect.stack()[1]
return caller[3]
def __BOTH__():
caller = inspect.stack()[1]
return int (caller[2]), caller[3], caller[1]
def Print(*args):
caller = inspect.stack()[1]
filename = str(os.path.basename(caller[1]))
sys.stdout.write(filename+ " : "+ str(int (caller[2])) + " : ")
sys.stdout.write(str(time.time()) + " : ")
for arg in args:
try:
x = str(arg)
except:
pass
try:
print x,
except:
try:
print unicode(x, errors="ignore"),
except:
try:
sys.stdout.write(arg.encode("ascii","ignore"))
except:
print "FAILED PRINT"
print
sys.stdout.flush()
|
Add in the timestamp for each message, to enable tracking of how long problems take to resolve
|
Add in the timestamp for each message, to enable tracking of how long problems take to resolve
|
Python
|
apache-2.0
|
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
|
---
+++
@@ -2,6 +2,7 @@
import sys
import os
import inspect
+import time
def __LINE__ ():
caller = inspect.stack()[1]
@@ -19,6 +20,7 @@
caller = inspect.stack()[1]
filename = str(os.path.basename(caller[1]))
sys.stdout.write(filename+ " : "+ str(int (caller[2])) + " : ")
+ sys.stdout.write(str(time.time()) + " : ")
for arg in args:
try:
x = str(arg)
|
0a7b88df526016672e18608339524cdb527e5928
|
aspen/__main__.py
|
aspen/__main__.py
|
"""
python -m aspen
===============
Aspen ships with a server (wsgiref.simple_server) that is
suitable for development and testing. It can be invoked via:
python -m aspen
though even for development you'll likely want to specify a
project root, so a more likely incantation is:
ASPEN_PROJECT_ROOT=/path/to/wherever python -m aspen
For production deployment, you should probably deploy using
a higher performance WSGI server like Gunicorn, uwsgi, Spawning,
or the like.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from aspen import serve, Website
if __name__ == '__main__':
website = Website()
serve(website)
|
"""
python -m aspen
===============
Aspen ships with a server (wsgiref.simple_server) that is
suitable for development and testing. It can be invoked via:
python -m aspen
though even for development you'll likely want to specify a
project root, so a more likely incantation is:
ASPEN_PROJECT_ROOT=/path/to/wherever python -m aspen
For production deployment, you should probably deploy using
a higher performance WSGI server like Gunicorn, uwsgi, Spawning,
or the like.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from aspen import serve, website
if __name__ == '__main__':
serve(website.Website())
|
Fix ImportError in `python -m aspen`
|
Fix ImportError in `python -m aspen`
|
Python
|
mit
|
gratipay/aspen.py,gratipay/aspen.py
|
---
+++
@@ -21,8 +21,7 @@
from __future__ import print_function
from __future__ import unicode_literals
-from aspen import serve, Website
+from aspen import serve, website
if __name__ == '__main__':
- website = Website()
- serve(website)
+ serve(website.Website())
|
b7dffc28ebef45293a70561348512d513eaf857c
|
migrations/versions/19b8969073ab_add_latest_green_build_table.py
|
migrations/versions/19b8969073ab_add_latest_green_build_table.py
|
"""add latest green build table
Revision ID: 19b8969073ab
Revises: 2b7153fe25af
Create Date: 2014-07-10 10:53:34.415990
"""
# revision identifiers, used by Alembic.
revision = '19b8969073ab'
down_revision = '2b7153fe25af'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'latest_green_build',
sa.Column('id', sa.GUID(), nullable=False),
sa.Column('project_id', sa.GUID(), nullable=False),
sa.Column('branch', sa.String(length=128), nullable=False),
sa.Column('build_id', sa.GUID(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),
sa.ForeignKeyConstraint(['build_id'], ['build.id'], ),
sa.UniqueConstraint('project_id', 'branch', name='unq_project_branch')
)
def downgrade():
op.drop_table('latest_green_build')
|
"""add latest green build table
Revision ID: 19b8969073ab
Revises: 4d235d421320
Create Date: 2014-07-10 10:53:34.415990
"""
# revision identifiers, used by Alembic.
revision = '19b8969073ab'
down_revision = '4d235d421320'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'latest_green_build',
sa.Column('id', sa.GUID(), nullable=False),
sa.Column('project_id', sa.GUID(), nullable=False),
sa.Column('branch', sa.String(length=128), nullable=False),
sa.Column('build_id', sa.GUID(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.ForeignKeyConstraint(['project_id'], ['project.id'], ),
sa.ForeignKeyConstraint(['build_id'], ['build.id'], ),
sa.UniqueConstraint('project_id', 'branch', name='unq_project_branch')
)
def downgrade():
op.drop_table('latest_green_build')
|
Update latest green build migration
|
Update latest green build migration
|
Python
|
apache-2.0
|
wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,dropbox/changes
|
---
+++
@@ -1,14 +1,14 @@
"""add latest green build table
Revision ID: 19b8969073ab
-Revises: 2b7153fe25af
+Revises: 4d235d421320
Create Date: 2014-07-10 10:53:34.415990
"""
# revision identifiers, used by Alembic.
revision = '19b8969073ab'
-down_revision = '2b7153fe25af'
+down_revision = '4d235d421320'
from alembic import op
import sqlalchemy as sa
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.