commit stringlengths 40 40 | old_file stringlengths 4 106 | new_file stringlengths 4 106 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 2.95k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1 value | license stringclasses 13 values | repos stringlengths 7 43k | ndiff stringlengths 52 3.31k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | diff stringlengths 49 3.61k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
824d769b1b1f55a018b380f6631f11727339a018 | fpsd/run_tests.py | fpsd/run_tests.py |
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_database_methods"])
|
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_database_methods"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_features"])
| Add feature generation tests to test runner | Add feature generation tests to test runner
| Python | agpl-3.0 | freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/fingerprint-securedrop |
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_database_methods"])
+ call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_features"])
| Add feature generation tests to test runner | ## Code Before:
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_database_methods"])
## Instruction:
Add feature generation tests to test runner
## Code After:
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_database_methods"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_features"])
|
from subprocess import call
from os.path import dirname, abspath, join
# Run all the tests using py.test
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_sketchy_sites"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_utils"])
call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_database_methods"])
+ call(["python3.5", "-m", "unittest", "-f", "-v", "test.test_features"]) |
a0ce4d366681f2f62f232f4f952ac18df07667d4 | ideascube/conf/idb_fra_cultura.py | ideascube/conf/idb_fra_cultura.py | """Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
(_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'cpassorcier',
},
{
'id': 'wikisource',
},
{
'id': 'software',
},
{
'id': 'ted',
},
{
'id': 'ubuntudoc',
},
]
| """Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
(_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'cpassorcier',
},
{
'id': 'wikisource',
},
{
'id': 'ted',
},
{
'id': 'ubuntudoc',
},
]
| Remove "software" card from Cultura conf | Remove "software" card from Cultura conf
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | """Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
(_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'cpassorcier',
},
{
'id': 'wikisource',
},
{
- 'id': 'software',
- },
- {
'id': 'ted',
},
{
'id': 'ubuntudoc',
},
]
| Remove "software" card from Cultura conf | ## Code Before:
"""Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
(_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'cpassorcier',
},
{
'id': 'wikisource',
},
{
'id': 'software',
},
{
'id': 'ted',
},
{
'id': 'ubuntudoc',
},
]
## Instruction:
Remove "software" card from Cultura conf
## Code After:
"""Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
(_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'cpassorcier',
},
{
'id': 'wikisource',
},
{
'id': 'ted',
},
{
'id': 'ubuntudoc',
},
]
| """Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['serial', 'user_id', 'birth_year', 'gender']
USER_FORM_FIELDS = (
(_('Personal informations'), ['serial', 'short_name', 'full_name', 'latin_name', 'birth_year', 'gender']), # noqa
)
HOME_CARDS = HOME_CARDS + [
{
'id': 'cpassorcier',
},
{
'id': 'wikisource',
},
{
- 'id': 'software',
- },
- {
'id': 'ted',
},
{
'id': 'ubuntudoc',
},
] |
e4fde66624f74c4b0bbfae7c7c11a50884a0a73c | pyfr/readers/base.py | pyfr/readers/base.py |
from abc import ABCMeta, abstractmethod
import uuid
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
|
from abc import ABCMeta, abstractmethod
import uuid
import numpy as np
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S')
return mesh
| Fix the HDF5 type of mesh_uuid for imported meshes. | Fix the HDF5 type of mesh_uuid for imported meshes.
| Python | bsd-3-clause | BrianVermeire/PyFR,Aerojspark/PyFR |
from abc import ABCMeta, abstractmethod
import uuid
+
+ import numpy as np
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
- mesh['mesh_uuid'] = str(uuid.uuid4())
+ mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S')
return mesh
| Fix the HDF5 type of mesh_uuid for imported meshes. | ## Code Before:
from abc import ABCMeta, abstractmethod
import uuid
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
mesh['mesh_uuid'] = str(uuid.uuid4())
return mesh
## Instruction:
Fix the HDF5 type of mesh_uuid for imported meshes.
## Code After:
from abc import ABCMeta, abstractmethod
import uuid
import numpy as np
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S')
return mesh
|
from abc import ABCMeta, abstractmethod
import uuid
+
+ import numpy as np
class BaseReader(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self):
pass
@abstractmethod
def _to_raw_pyfrm(self):
pass
def to_pyfrm(self):
mesh = self._to_raw_pyfrm()
# Add metadata
- mesh['mesh_uuid'] = str(uuid.uuid4())
+ mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S')
? +++++++++ ++++++++++++
return mesh |
b2a977a7285cbe832350492b967213b5261ad6b4 | flask_app/tasks.py | flask_app/tasks.py | from __future__ import absolute_import
import functools
import os
import sys
import logbook
from celery import Celery
from celery.signals import after_setup_logger, after_setup_task_logger
from .app import create_app
_logger = logbook.Logger(__name__)
queue = Celery('tasks', broker='redis://localhost')
queue.conf.update(
CELERY_TASK_SERIALIZER='json',
CELERY_ACCEPT_CONTENT=['json'], # Ignore other content
CELERY_RESULT_SERIALIZER='json',
CELERY_ENABLE_UTC=True,
)
def setup_log(**args):
logbook.SyslogHandler().push_application()
logbook.StreamHandler(sys.stderr, bubble=True).push_application()
APP = None
def needs_app_context(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
global APP
if APP is None:
APP = create_app()
with APP.app_context():
return f(*args, **kwargs)
return wrapper
after_setup_logger.connect(setup_log)
after_setup_task_logger.connect(setup_log)
| from __future__ import absolute_import
import functools
import os
import sys
import logging
import logging.handlers
import logbook
from celery import Celery
from celery.signals import after_setup_logger, after_setup_task_logger
from celery.log import redirect_stdouts_to_logger
from .app import create_app
_logger = logbook.Logger(__name__)
queue = Celery('tasks', broker='redis://localhost')
queue.conf.update(
CELERY_TASK_SERIALIZER='json',
CELERY_ACCEPT_CONTENT=['json'], # Ignore other content
CELERY_RESULT_SERIALIZER='json',
CELERY_ENABLE_UTC=True,
)
def setup_log(**args):
logbook.SyslogHandler().push_application()
logbook.StreamHandler(sys.stderr, bubble=True).push_application()
redirect_stdouts_to_logger(args['logger']) # logs to local syslog
if os.path.exists('/dev/log'):
h = logging.handlers.SysLogHandler('/dev/log')
else:
h = logging.handlers.SysLogHandler()
h.setLevel(args['loglevel'])
formatter = logging.Formatter(logging.BASIC_FORMAT)
h.setFormatter(formatter)
args['logger'].addHandler(h)
APP = None
def needs_app_context(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
global APP
if APP is None:
APP = create_app()
with APP.app_context():
return f(*args, **kwargs)
return wrapper
after_setup_logger.connect(setup_log)
after_setup_task_logger.connect(setup_log)
| Fix celery logging in deployment | Fix celery logging in deployment
| Python | mit | getslash/mailboxer,getslash/mailboxer,getslash/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer,vmalloc/mailboxer,Infinidat/lanister,Infinidat/lanister | from __future__ import absolute_import
import functools
import os
import sys
+ import logging
+ import logging.handlers
import logbook
from celery import Celery
from celery.signals import after_setup_logger, after_setup_task_logger
+ from celery.log import redirect_stdouts_to_logger
from .app import create_app
_logger = logbook.Logger(__name__)
queue = Celery('tasks', broker='redis://localhost')
queue.conf.update(
CELERY_TASK_SERIALIZER='json',
CELERY_ACCEPT_CONTENT=['json'], # Ignore other content
CELERY_RESULT_SERIALIZER='json',
CELERY_ENABLE_UTC=True,
)
def setup_log(**args):
logbook.SyslogHandler().push_application()
logbook.StreamHandler(sys.stderr, bubble=True).push_application()
+ redirect_stdouts_to_logger(args['logger']) # logs to local syslog
+ if os.path.exists('/dev/log'):
+ h = logging.handlers.SysLogHandler('/dev/log')
+ else:
+ h = logging.handlers.SysLogHandler()
+ h.setLevel(args['loglevel'])
+ formatter = logging.Formatter(logging.BASIC_FORMAT)
+ h.setFormatter(formatter)
+ args['logger'].addHandler(h)
APP = None
def needs_app_context(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
global APP
if APP is None:
APP = create_app()
with APP.app_context():
return f(*args, **kwargs)
return wrapper
after_setup_logger.connect(setup_log)
after_setup_task_logger.connect(setup_log)
| Fix celery logging in deployment | ## Code Before:
from __future__ import absolute_import
import functools
import os
import sys
import logbook
from celery import Celery
from celery.signals import after_setup_logger, after_setup_task_logger
from .app import create_app
_logger = logbook.Logger(__name__)
queue = Celery('tasks', broker='redis://localhost')
queue.conf.update(
CELERY_TASK_SERIALIZER='json',
CELERY_ACCEPT_CONTENT=['json'], # Ignore other content
CELERY_RESULT_SERIALIZER='json',
CELERY_ENABLE_UTC=True,
)
def setup_log(**args):
logbook.SyslogHandler().push_application()
logbook.StreamHandler(sys.stderr, bubble=True).push_application()
APP = None
def needs_app_context(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
global APP
if APP is None:
APP = create_app()
with APP.app_context():
return f(*args, **kwargs)
return wrapper
after_setup_logger.connect(setup_log)
after_setup_task_logger.connect(setup_log)
## Instruction:
Fix celery logging in deployment
## Code After:
from __future__ import absolute_import
import functools
import os
import sys
import logging
import logging.handlers
import logbook
from celery import Celery
from celery.signals import after_setup_logger, after_setup_task_logger
from celery.log import redirect_stdouts_to_logger
from .app import create_app
_logger = logbook.Logger(__name__)
queue = Celery('tasks', broker='redis://localhost')
queue.conf.update(
CELERY_TASK_SERIALIZER='json',
CELERY_ACCEPT_CONTENT=['json'], # Ignore other content
CELERY_RESULT_SERIALIZER='json',
CELERY_ENABLE_UTC=True,
)
def setup_log(**args):
logbook.SyslogHandler().push_application()
logbook.StreamHandler(sys.stderr, bubble=True).push_application()
redirect_stdouts_to_logger(args['logger']) # logs to local syslog
if os.path.exists('/dev/log'):
h = logging.handlers.SysLogHandler('/dev/log')
else:
h = logging.handlers.SysLogHandler()
h.setLevel(args['loglevel'])
formatter = logging.Formatter(logging.BASIC_FORMAT)
h.setFormatter(formatter)
args['logger'].addHandler(h)
APP = None
def needs_app_context(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
global APP
if APP is None:
APP = create_app()
with APP.app_context():
return f(*args, **kwargs)
return wrapper
after_setup_logger.connect(setup_log)
after_setup_task_logger.connect(setup_log)
| from __future__ import absolute_import
import functools
import os
import sys
+ import logging
+ import logging.handlers
import logbook
from celery import Celery
from celery.signals import after_setup_logger, after_setup_task_logger
+ from celery.log import redirect_stdouts_to_logger
from .app import create_app
_logger = logbook.Logger(__name__)
queue = Celery('tasks', broker='redis://localhost')
queue.conf.update(
CELERY_TASK_SERIALIZER='json',
CELERY_ACCEPT_CONTENT=['json'], # Ignore other content
CELERY_RESULT_SERIALIZER='json',
CELERY_ENABLE_UTC=True,
)
def setup_log(**args):
logbook.SyslogHandler().push_application()
logbook.StreamHandler(sys.stderr, bubble=True).push_application()
+ redirect_stdouts_to_logger(args['logger']) # logs to local syslog
+ if os.path.exists('/dev/log'):
+ h = logging.handlers.SysLogHandler('/dev/log')
+ else:
+ h = logging.handlers.SysLogHandler()
+ h.setLevel(args['loglevel'])
+ formatter = logging.Formatter(logging.BASIC_FORMAT)
+ h.setFormatter(formatter)
+ args['logger'].addHandler(h)
APP = None
def needs_app_context(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
global APP
if APP is None:
APP = create_app()
with APP.app_context():
return f(*args, **kwargs)
return wrapper
after_setup_logger.connect(setup_log)
after_setup_task_logger.connect(setup_log) |
2489ed6ff3d812888de4a0a2c45995389499d648 | thread_output_ctrl.py | thread_output_ctrl.py | import Queue
import wx, wx.stc
from editor_fonts import init_stc_style
class ThreadOutputCtrl(wx.stc.StyledTextCtrl):
def __init__(self, parent, style=wx.TE_READONLY):
wx.stc.StyledTextCtrl.__init__(self, parent)
init_stc_style(self)
self.SetIndent(4)
self.SetTabWidth(8)
self.SetUseTabs(False)
self.queue = Queue.Queue(1024)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer)
def __OnTimer(self, evt):
self.flush()
def flush(self):
lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize()))
if lines:
self.AppendText(lines)
def start(self, interval=100):
self.timer.Start(interval)
def stop(self):
self.timer.Stop()
wx.CallAfter(self.flush)
def write(self, s):
self.queue.put(s)
def IsEmpty(self):
return self.GetTextLength() == 0
| import threading
import wx, wx.stc
from editor_fonts import init_stc_style
class ThreadOutputCtrl(wx.stc.StyledTextCtrl):
def __init__(self, parent, style=wx.TE_READONLY):
wx.stc.StyledTextCtrl.__init__(self, parent)
init_stc_style(self)
self.SetIndent(4)
self.SetTabWidth(8)
self.SetUseTabs(False)
self.__lock = threading.Lock()
self.__queue = []
self.__timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer)
def __OnTimer(self, evt):
self.flush()
def flush(self):
with self.__lock:
queue, self.__queue = self.__queue, []
lines = "".join(queue)
if lines:
self.AppendText(lines)
def start(self, interval=100):
self.__timer.Start(interval)
def stop(self):
self.__timer.Stop()
wx.CallAfter(self.flush)
def write(self, s):
with self.__lock:
self.__queue.append(s)
def IsEmpty(self):
return self.GetTextLength() == 0
| Use a lock-protected list instead of a Queue. | Use a lock-protected list instead of a Queue.
| Python | mit | shaurz/devo | - import Queue
+ import threading
import wx, wx.stc
from editor_fonts import init_stc_style
class ThreadOutputCtrl(wx.stc.StyledTextCtrl):
def __init__(self, parent, style=wx.TE_READONLY):
wx.stc.StyledTextCtrl.__init__(self, parent)
init_stc_style(self)
self.SetIndent(4)
self.SetTabWidth(8)
self.SetUseTabs(False)
- self.queue = Queue.Queue(1024)
+ self.__lock = threading.Lock()
+ self.__queue = []
- self.timer = wx.Timer(self)
+ self.__timer = wx.Timer(self)
- self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer)
+ self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer)
def __OnTimer(self, evt):
self.flush()
def flush(self):
- lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize()))
+ with self.__lock:
+ queue, self.__queue = self.__queue, []
+ lines = "".join(queue)
if lines:
self.AppendText(lines)
def start(self, interval=100):
- self.timer.Start(interval)
+ self.__timer.Start(interval)
def stop(self):
- self.timer.Stop()
+ self.__timer.Stop()
wx.CallAfter(self.flush)
def write(self, s):
+ with self.__lock:
- self.queue.put(s)
+ self.__queue.append(s)
def IsEmpty(self):
return self.GetTextLength() == 0
| Use a lock-protected list instead of a Queue. | ## Code Before:
import Queue
import wx, wx.stc
from editor_fonts import init_stc_style
class ThreadOutputCtrl(wx.stc.StyledTextCtrl):
def __init__(self, parent, style=wx.TE_READONLY):
wx.stc.StyledTextCtrl.__init__(self, parent)
init_stc_style(self)
self.SetIndent(4)
self.SetTabWidth(8)
self.SetUseTabs(False)
self.queue = Queue.Queue(1024)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer)
def __OnTimer(self, evt):
self.flush()
def flush(self):
lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize()))
if lines:
self.AppendText(lines)
def start(self, interval=100):
self.timer.Start(interval)
def stop(self):
self.timer.Stop()
wx.CallAfter(self.flush)
def write(self, s):
self.queue.put(s)
def IsEmpty(self):
return self.GetTextLength() == 0
## Instruction:
Use a lock-protected list instead of a Queue.
## Code After:
import threading
import wx, wx.stc
from editor_fonts import init_stc_style
class ThreadOutputCtrl(wx.stc.StyledTextCtrl):
def __init__(self, parent, style=wx.TE_READONLY):
wx.stc.StyledTextCtrl.__init__(self, parent)
init_stc_style(self)
self.SetIndent(4)
self.SetTabWidth(8)
self.SetUseTabs(False)
self.__lock = threading.Lock()
self.__queue = []
self.__timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer)
def __OnTimer(self, evt):
self.flush()
def flush(self):
with self.__lock:
queue, self.__queue = self.__queue, []
lines = "".join(queue)
if lines:
self.AppendText(lines)
def start(self, interval=100):
self.__timer.Start(interval)
def stop(self):
self.__timer.Stop()
wx.CallAfter(self.flush)
def write(self, s):
with self.__lock:
self.__queue.append(s)
def IsEmpty(self):
return self.GetTextLength() == 0
| - import Queue
+ import threading
import wx, wx.stc
from editor_fonts import init_stc_style
class ThreadOutputCtrl(wx.stc.StyledTextCtrl):
def __init__(self, parent, style=wx.TE_READONLY):
wx.stc.StyledTextCtrl.__init__(self, parent)
init_stc_style(self)
self.SetIndent(4)
self.SetTabWidth(8)
self.SetUseTabs(False)
- self.queue = Queue.Queue(1024)
+ self.__lock = threading.Lock()
+ self.__queue = []
- self.timer = wx.Timer(self)
+ self.__timer = wx.Timer(self)
? ++
- self.Bind(wx.EVT_TIMER, self.__OnTimer, self.timer)
+ self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer)
? ++
def __OnTimer(self, evt):
self.flush()
def flush(self):
- lines = "".join(self.queue.get_nowait() for _ in xrange(self.queue.qsize()))
+ with self.__lock:
+ queue, self.__queue = self.__queue, []
+ lines = "".join(queue)
if lines:
self.AppendText(lines)
def start(self, interval=100):
- self.timer.Start(interval)
+ self.__timer.Start(interval)
? ++
def stop(self):
- self.timer.Stop()
+ self.__timer.Stop()
? ++
wx.CallAfter(self.flush)
def write(self, s):
+ with self.__lock:
- self.queue.put(s)
? ^^
+ self.__queue.append(s)
? ++++ ++ + ^^^^
def IsEmpty(self):
return self.GetTextLength() == 0 |
c460fd7d257b25723fc19557ad4404519904e0a9 | simplecoin/tests/__init__.py | simplecoin/tests/__init__.py | import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
| import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
| Fix tests to allow use of random, but not change each time | Fix tests to allow use of random, but not change each time
| Python | mit | nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi | import simplecoin
import unittest
import datetime
+ import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
+ # Set the random seed to a fixed number, causing all use of random
+ # to actually repeat exactly the same every time
+ random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
| Fix tests to allow use of random, but not change each time | ## Code Before:
import simplecoin
import unittest
import datetime
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
## Instruction:
Fix tests to allow use of random, but not change each time
## Code After:
import simplecoin
import unittest
import datetime
import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
# Set the random seed to a fixed number, causing all use of random
# to actually repeat exactly the same every time
random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb()
| import simplecoin
import unittest
import datetime
+ import random
import simplecoin.models as m
from decimal import Decimal
from simplecoin import db
class UnitTest(unittest.TestCase):
""" Represents a set of tests that only need the database iniailized, but
no fixture data """
def setUp(self, **kwargs):
+ # Set the random seed to a fixed number, causing all use of random
+ # to actually repeat exactly the same every time
+ random.seed(0)
extra = dict()
extra.update(kwargs)
app = simplecoin.create_app('webserver', configs=['test.toml'], **extra)
with app.app_context():
self.db = simplecoin.db
self.setup_db()
self.app = app
self._ctx = self.app.test_request_context()
self._ctx.push()
self.client = self.app.test_client()
def tearDown(self):
# dump the test elasticsearch index
db.session.remove()
db.drop_all()
def setup_db(self):
self.db.drop_all()
self.db.create_all()
db.session.commit()
def make_block(self, **kwargs):
vals = dict(currency="LTC",
height=1,
found_at=datetime.datetime.utcnow(),
time_started=datetime.datetime.utcnow(),
difficulty=12,
merged=False,
algo="scrypt",
total_value=Decimal("50"))
vals.update(kwargs)
blk = m.Block(**vals)
db.session.add(blk)
return blk
class RedisUnitTest(UnitTest):
def setUp(self):
UnitTest.setUp(self)
self.app.redis.flushdb() |
ce34a3dbaa824429b91af76ed5882ddffc2d3b2b | examples/happy_birthday.py | examples/happy_birthday.py | """A basic (single function) API written using Hug"""
import hug
@hug.get('/happy_birthday')
def happy_birthday(name, age:hug.types.number, **kwargs):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
| """A basic (single function) API written using Hug"""
import hug
@hug.get('/happy_birthday', example="name=HUG&page=1")
def happy_birthday(name, age:hug.types.number, **kwargs):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
| Add example argument, for direct url | Add example argument, for direct url
| Python | mit | STANAPO/hug,origingod/hug,jean/hug,MuhammadAlkarouri/hug,philiptzou/hug,jean/hug,giserh/hug,STANAPO/hug,MuhammadAlkarouri/hug,gbn972/hug,yasoob/hug,timothycrosley/hug,philiptzou/hug,yasoob/hug,giserh/hug,timothycrosley/hug,MuhammadAlkarouri/hug,shaunstanislaus/hug,timothycrosley/hug,janusnic/hug,janusnic/hug,alisaifee/hug,shaunstanislaus/hug,alisaifee/hug,gbn972/hug,origingod/hug | """A basic (single function) API written using Hug"""
import hug
- @hug.get('/happy_birthday')
+ @hug.get('/happy_birthday', example="name=HUG&page=1")
def happy_birthday(name, age:hug.types.number, **kwargs):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
| Add example argument, for direct url | ## Code Before:
"""A basic (single function) API written using Hug"""
import hug
@hug.get('/happy_birthday')
def happy_birthday(name, age:hug.types.number, **kwargs):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
## Instruction:
Add example argument, for direct url
## Code After:
"""A basic (single function) API written using Hug"""
import hug
@hug.get('/happy_birthday', example="name=HUG&page=1")
def happy_birthday(name, age:hug.types.number, **kwargs):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals())
| """A basic (single function) API written using Hug"""
import hug
- @hug.get('/happy_birthday')
+ @hug.get('/happy_birthday', example="name=HUG&page=1")
def happy_birthday(name, age:hug.types.number, **kwargs):
"""Says happy birthday to a user"""
return "Happy {age} Birthday {name}!".format(**locals()) |
351bc14c66962e5ef386b6d41073697993c95236 | greengraph/test/test_map.py | greengraph/test/test_map.py | from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
import yaml
def test_green():
size = (10,10)
zoom = 10
lat = 50
lon = 50
satellite = True
testMap = Map(lat,lon,satellite,zoom,size)
threshold = 1
trueArray = np.ones(size,dtype=bool)
falseArray = np.zeros(size,dtype=bool)
def assert_images_equal(r,g,b,checkArray):
testPixels = np.dstack((r,g,blue))
testMap.pixels = testPixels
np.testing.assert_array_equal(testMap.green(threshold),checkArray)
green = np.ones(size)
red = np.ones(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
blue = np.zeros(size)
assert_images_equal(red,green,blue,falseArray)
red = np.zeros(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
blue = np.zeros(size)
assert_images_equal(red,green,blue,trueArray)
| from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
from mock import patch
import os
@patch('requests.get')
@patch('matplotlib.image.imread')
@patch('StringIO.StringIO')
def test_green(mock_get,mock_imread,mock_StringIO):
def assert_images_equal(r,g,b,checkArray):
testMap.pixels = np.dstack((r,g,b))
np.testing.assert_array_equal(testMap.green(threshold),checkArray)
lat = 50
lon = 50
testMap = Map(lat,lon)
size = (400,400)
trueArray = np.ones(size,dtype=bool)
falseArray = np.zeros(size,dtype=bool)
threshold = 1
#Check the returned array is false everywhere when the value of the green pixels is identical to the values of the red and blue pixels
green = np.ones(size)
red = np.ones(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
#Check the returned array is false everywhere when the value of the green pixels is greater than the value of the blue pixels but less than the value of the red pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,falseArray)
#As above but with red and blue pixels switched
red = np.zeros(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
#Check the returned array is true everywhere when the value of the green pixels is greater than the value of the red and blue pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,trueArray)
| Add patch decorator to test_green() function | Add patch decorator to test_green() function
| Python | mit | MikeVasmer/GreenGraphCoursework | from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
- import yaml
+ from mock import patch
+ import os
- def test_green():
- size = (10,10)
- zoom = 10
+ @patch('requests.get')
+ @patch('matplotlib.image.imread')
+ @patch('StringIO.StringIO')
+ def test_green(mock_get,mock_imread,mock_StringIO):
+
+ def assert_images_equal(r,g,b,checkArray):
+ testMap.pixels = np.dstack((r,g,b))
+ np.testing.assert_array_equal(testMap.green(threshold),checkArray)
+
lat = 50
lon = 50
+ testMap = Map(lat,lon)
- satellite = True
- testMap = Map(lat,lon,satellite,zoom,size)
- threshold = 1
+ size = (400,400)
trueArray = np.ones(size,dtype=bool)
falseArray = np.zeros(size,dtype=bool)
+ threshold = 1
+ #Check the returned array is false everywhere when the value of the green pixels is identical to the values of the red and blue pixels
- def assert_images_equal(r,g,b,checkArray):
- testPixels = np.dstack((r,g,blue))
- testMap.pixels = testPixels
- np.testing.assert_array_equal(testMap.green(threshold),checkArray)
-
green = np.ones(size)
red = np.ones(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
+ #Check the returned array is false everywhere when the value of the green pixels is greater than the value of the blue pixels but less than the value of the red pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,falseArray)
+ #As above but with red and blue pixels switched
red = np.zeros(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
+ #Check the returned array is true everywhere when the value of the green pixels is greater than the value of the red and blue pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,trueArray)
| Add patch decorator to test_green() function | ## Code Before:
from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
import yaml
def test_green():
size = (10,10)
zoom = 10
lat = 50
lon = 50
satellite = True
testMap = Map(lat,lon,satellite,zoom,size)
threshold = 1
trueArray = np.ones(size,dtype=bool)
falseArray = np.zeros(size,dtype=bool)
def assert_images_equal(r,g,b,checkArray):
testPixels = np.dstack((r,g,blue))
testMap.pixels = testPixels
np.testing.assert_array_equal(testMap.green(threshold),checkArray)
green = np.ones(size)
red = np.ones(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
blue = np.zeros(size)
assert_images_equal(red,green,blue,falseArray)
red = np.zeros(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
blue = np.zeros(size)
assert_images_equal(red,green,blue,trueArray)
## Instruction:
Add patch decorator to test_green() function
## Code After:
from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
from mock import patch
import os
@patch('requests.get')
@patch('matplotlib.image.imread')
@patch('StringIO.StringIO')
def test_green(mock_get,mock_imread,mock_StringIO):
def assert_images_equal(r,g,b,checkArray):
testMap.pixels = np.dstack((r,g,b))
np.testing.assert_array_equal(testMap.green(threshold),checkArray)
lat = 50
lon = 50
testMap = Map(lat,lon)
size = (400,400)
trueArray = np.ones(size,dtype=bool)
falseArray = np.zeros(size,dtype=bool)
threshold = 1
#Check the returned array is false everywhere when the value of the green pixels is identical to the values of the red and blue pixels
green = np.ones(size)
red = np.ones(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
#Check the returned array is false everywhere when the value of the green pixels is greater than the value of the blue pixels but less than the value of the red pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,falseArray)
#As above but with red and blue pixels switched
red = np.zeros(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
#Check the returned array is true everywhere when the value of the green pixels is greater than the value of the red and blue pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,trueArray)
| from greengraph.map import Map
import numpy as np
from nose.tools import assert_equal
- import yaml
+ from mock import patch
+ import os
- def test_green():
- size = (10,10)
- zoom = 10
+ @patch('requests.get')
+ @patch('matplotlib.image.imread')
+ @patch('StringIO.StringIO')
+ def test_green(mock_get,mock_imread,mock_StringIO):
+
+ def assert_images_equal(r,g,b,checkArray):
+ testMap.pixels = np.dstack((r,g,b))
+ np.testing.assert_array_equal(testMap.green(threshold),checkArray)
+
lat = 50
lon = 50
+ testMap = Map(lat,lon)
- satellite = True
- testMap = Map(lat,lon,satellite,zoom,size)
- threshold = 1
+ size = (400,400)
trueArray = np.ones(size,dtype=bool)
falseArray = np.zeros(size,dtype=bool)
+ threshold = 1
+ #Check the returned array is false everywhere when the value of the green pixels is identical to the values of the red and blue pixels
- def assert_images_equal(r,g,b,checkArray):
- testPixels = np.dstack((r,g,blue))
- testMap.pixels = testPixels
- np.testing.assert_array_equal(testMap.green(threshold),checkArray)
-
green = np.ones(size)
red = np.ones(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
+ #Check the returned array is false everywhere when the value of the green pixels is greater than the value of the blue pixels but less than the value of the red pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,falseArray)
+ #As above but with red and blue pixels switched
red = np.zeros(size)
blue = np.ones(size)
assert_images_equal(red,green,blue,falseArray)
+ #Check the returned array is true everywhere when the value of the green pixels is greater than the value of the red and blue pixels
blue = np.zeros(size)
assert_images_equal(red,green,blue,trueArray) |
57f5d8c1f02aa5d3a1be5fdc7302a15d416071dc | utils/decorators.py | utils/decorators.py | from functools import wraps
def bot_only(func):
@wraps(func)
def inner(self, *args, **kwargs):
if not self.user.bot:
return
return func(self, *args, **kwargs)
return inner
| from functools import wraps
def bot_only(coro):
@wraps(coro)
async def inner(self, *args, **kwargs):
if not self.user.bot:
return
return await coro(self, *args, **kwargs)
return inner
| Make bot_only async, because duh | Make bot_only async, because duh
| Python | mit | BeatButton/beattie-bot,BeatButton/beattie | from functools import wraps
- def bot_only(func):
+ def bot_only(coro):
- @wraps(func)
+ @wraps(coro)
- def inner(self, *args, **kwargs):
+ async def inner(self, *args, **kwargs):
if not self.user.bot:
return
- return func(self, *args, **kwargs)
+ return await coro(self, *args, **kwargs)
return inner
| Make bot_only async, because duh | ## Code Before:
from functools import wraps
def bot_only(func):
@wraps(func)
def inner(self, *args, **kwargs):
if not self.user.bot:
return
return func(self, *args, **kwargs)
return inner
## Instruction:
Make bot_only async, because duh
## Code After:
from functools import wraps
def bot_only(coro):
@wraps(coro)
async def inner(self, *args, **kwargs):
if not self.user.bot:
return
return await coro(self, *args, **kwargs)
return inner
| from functools import wraps
- def bot_only(func):
? ---
+ def bot_only(coro):
? +++
- @wraps(func)
? ---
+ @wraps(coro)
? +++
- def inner(self, *args, **kwargs):
+ async def inner(self, *args, **kwargs):
? ++++++
if not self.user.bot:
return
- return func(self, *args, **kwargs)
? ^^^
+ return await coro(self, *args, **kwargs)
? ^^^^^^ +++
return inner |
0b7c27fec5b1b7ececfcf7556f415e8e53cf69b6 | v1.0/v1.0/search.py | v1.0/v1.0/search.py |
import sys
mainfile = sys.argv[1]
indexfile = sys.argv[1] + ".idx1"
term = sys.argv[2]
main = open(mainfile)
index = open(indexfile)
st = term + ": "
for a in index:
if a.startswith(st):
n = [int(i) for i in a[len(st):].split(", ") if i]
linenum = 0
for l in main:
linenum += 1
if linenum in n:
print linenum, l.rstrip()
break
|
from __future__ import print_function
import sys
mainfile = sys.argv[1]
indexfile = sys.argv[1] + ".idx1"
term = sys.argv[2]
main = open(mainfile)
index = open(indexfile)
st = term + ": "
for a in index:
if a.startswith(st):
n = [int(i) for i in a[len(st):].split(", ") if i]
linenum = 0
for l in main:
linenum += 1
if linenum in n:
print(linenum, l.rstrip())
break
| Make conformance test 55 compatible with Python 3 | Make conformance test 55 compatible with Python 3
| Python | apache-2.0 | curoverse/common-workflow-language,curoverse/common-workflow-language,mr-c/common-workflow-language,common-workflow-language/common-workflow-language,mr-c/common-workflow-language,dleehr/common-workflow-language,dleehr/common-workflow-language,common-workflow-language/common-workflow-language,dleehr/common-workflow-language,mr-c/common-workflow-language,common-workflow-language/common-workflow-language,common-workflow-language/common-workflow-language,dleehr/common-workflow-language | +
+ from __future__ import print_function
import sys
mainfile = sys.argv[1]
indexfile = sys.argv[1] + ".idx1"
term = sys.argv[2]
main = open(mainfile)
index = open(indexfile)
st = term + ": "
for a in index:
if a.startswith(st):
n = [int(i) for i in a[len(st):].split(", ") if i]
linenum = 0
for l in main:
linenum += 1
if linenum in n:
- print linenum, l.rstrip()
+ print(linenum, l.rstrip())
break
| Make conformance test 55 compatible with Python 3 | ## Code Before:
import sys
mainfile = sys.argv[1]
indexfile = sys.argv[1] + ".idx1"
term = sys.argv[2]
main = open(mainfile)
index = open(indexfile)
st = term + ": "
for a in index:
if a.startswith(st):
n = [int(i) for i in a[len(st):].split(", ") if i]
linenum = 0
for l in main:
linenum += 1
if linenum in n:
print linenum, l.rstrip()
break
## Instruction:
Make conformance test 55 compatible with Python 3
## Code After:
from __future__ import print_function
import sys
mainfile = sys.argv[1]
indexfile = sys.argv[1] + ".idx1"
term = sys.argv[2]
main = open(mainfile)
index = open(indexfile)
st = term + ": "
for a in index:
if a.startswith(st):
n = [int(i) for i in a[len(st):].split(", ") if i]
linenum = 0
for l in main:
linenum += 1
if linenum in n:
print(linenum, l.rstrip())
break
| +
+ from __future__ import print_function
import sys
mainfile = sys.argv[1]
indexfile = sys.argv[1] + ".idx1"
term = sys.argv[2]
main = open(mainfile)
index = open(indexfile)
st = term + ": "
for a in index:
if a.startswith(st):
n = [int(i) for i in a[len(st):].split(", ") if i]
linenum = 0
for l in main:
linenum += 1
if linenum in n:
- print linenum, l.rstrip()
? ^
+ print(linenum, l.rstrip())
? ^ +
break |
1557de38bcc9fa4099655c210d7e2daf7c19d715 | task/models.py | task/models.py | from django.db import models
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=50, unique=True)
created_at = models.DateField()
status = models.CharField(max_length=30, choices=settings.TASK_CHOICES)
def __unicode__(self): # pragma: no cover
return self.title
| import datetime
from django.db import models
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=50, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=30, choices=settings.TASK_CHOICES)
class Meta:
ordering = ('-created_at',)
def __unicode__(self): # pragma: no cover
return self.title
| Set order getting the list of tasks | Set order getting the list of tasks
| Python | mit | rosadurante/to_do,rosadurante/to_do | + import datetime
+
from django.db import models
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=50, unique=True)
- created_at = models.DateField()
+ created_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=30, choices=settings.TASK_CHOICES)
+
+ class Meta:
+ ordering = ('-created_at',)
def __unicode__(self): # pragma: no cover
return self.title
| Set order getting the list of tasks | ## Code Before:
from django.db import models
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=50, unique=True)
created_at = models.DateField()
status = models.CharField(max_length=30, choices=settings.TASK_CHOICES)
def __unicode__(self): # pragma: no cover
return self.title
## Instruction:
Set order getting the list of tasks
## Code After:
import datetime
from django.db import models
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=50, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=30, choices=settings.TASK_CHOICES)
class Meta:
ordering = ('-created_at',)
def __unicode__(self): # pragma: no cover
return self.title
| + import datetime
+
from django.db import models
from django.conf import settings
class Task(models.Model):
title = models.CharField(max_length=50, unique=True)
- created_at = models.DateField()
+ created_at = models.DateTimeField(auto_now_add=True)
? ++++ +++++++++++++++++
status = models.CharField(max_length=30, choices=settings.TASK_CHOICES)
+
+ class Meta:
+ ordering = ('-created_at',)
def __unicode__(self): # pragma: no cover
return self.title |
dc40793ad27704c83dbbd2e923bf0cbcd7cb00ed | polyaxon/event_manager/event_service.py | polyaxon/event_manager/event_service.py | from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
def get_event(self, event_type, instance, **kwargs):
return self.event_manager.get(
event_type,
).from_instance(instance, **kwargs)
def record(self, event_type, instance=None, **kwargs):
""" Validate and record an event.
>>> record('event.action', object_instance)
"""
if not self.is_setup:
return
if not self.can_handle(event_type=event_type):
return
event = self.get_event(event_type=event_type, instance=instance, **kwargs)
self.record_event(event)
def record_event(self, event):
""" Record an event.
>>> record_event(Event())
"""
pass
| from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
def get_event(self, event_type, event_data=None, instance=None, **kwargs):
if instance or not event_data:
return self.event_manager.get(
event_type,
).from_instance(instance, **kwargs)
return self.event_manager.get(
event_type,
).from_event_data(event_data=event_data, **kwargs)
def record(self, event_type, event_data=None, instance=None, **kwargs):
""" Validate and record an event.
>>> record('event.action', object_instance)
"""
if not self.is_setup:
return
if not self.can_handle(event_type=event_type):
return
event = self.get_event(event_type=event_type,
event_data=event_data,
instance=instance,
**kwargs)
self.record_event(event)
return event
def record_event(self, event):
""" Record an event.
>>> record_event(Event())
"""
pass
| Handle both event instanciation from object and from serialized events | Handle both event instanciation from object and from serialized events
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
- def get_event(self, event_type, instance, **kwargs):
+ def get_event(self, event_type, event_data=None, instance=None, **kwargs):
+ if instance or not event_data:
+ return self.event_manager.get(
+ event_type,
+ ).from_instance(instance, **kwargs)
return self.event_manager.get(
event_type,
- ).from_instance(instance, **kwargs)
+ ).from_event_data(event_data=event_data, **kwargs)
- def record(self, event_type, instance=None, **kwargs):
+ def record(self, event_type, event_data=None, instance=None, **kwargs):
""" Validate and record an event.
>>> record('event.action', object_instance)
"""
if not self.is_setup:
return
if not self.can_handle(event_type=event_type):
return
- event = self.get_event(event_type=event_type, instance=instance, **kwargs)
+ event = self.get_event(event_type=event_type,
+ event_data=event_data,
+ instance=instance,
+ **kwargs)
self.record_event(event)
+ return event
def record_event(self, event):
""" Record an event.
>>> record_event(Event())
"""
pass
| Handle both event instanciation from object and from serialized events | ## Code Before:
from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
def get_event(self, event_type, instance, **kwargs):
return self.event_manager.get(
event_type,
).from_instance(instance, **kwargs)
def record(self, event_type, instance=None, **kwargs):
""" Validate and record an event.
>>> record('event.action', object_instance)
"""
if not self.is_setup:
return
if not self.can_handle(event_type=event_type):
return
event = self.get_event(event_type=event_type, instance=instance, **kwargs)
self.record_event(event)
def record_event(self, event):
""" Record an event.
>>> record_event(Event())
"""
pass
## Instruction:
Handle both event instanciation from object and from serialized events
## Code After:
from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
def get_event(self, event_type, event_data=None, instance=None, **kwargs):
if instance or not event_data:
return self.event_manager.get(
event_type,
).from_instance(instance, **kwargs)
return self.event_manager.get(
event_type,
).from_event_data(event_data=event_data, **kwargs)
def record(self, event_type, event_data=None, instance=None, **kwargs):
""" Validate and record an event.
>>> record('event.action', object_instance)
"""
if not self.is_setup:
return
if not self.can_handle(event_type=event_type):
return
event = self.get_event(event_type=event_type,
event_data=event_data,
instance=instance,
**kwargs)
self.record_event(event)
return event
def record_event(self, event):
""" Record an event.
>>> record_event(Event())
"""
pass
| from libs.services import Service
class EventService(Service):
__all__ = ('record', 'setup')
event_manager = None
def can_handle(self, event_type):
return isinstance(event_type, str) and self.event_manager.knows(event_type)
- def get_event(self, event_type, instance, **kwargs):
+ def get_event(self, event_type, event_data=None, instance=None, **kwargs):
? +++++++++++++++++ +++++
+ if instance or not event_data:
+ return self.event_manager.get(
+ event_type,
+ ).from_instance(instance, **kwargs)
return self.event_manager.get(
event_type,
- ).from_instance(instance, **kwargs)
+ ).from_event_data(event_data=event_data, **kwargs)
- def record(self, event_type, instance=None, **kwargs):
+ def record(self, event_type, event_data=None, instance=None, **kwargs):
? +++++++++++++++++
""" Validate and record an event.
>>> record('event.action', object_instance)
"""
if not self.is_setup:
return
if not self.can_handle(event_type=event_type):
return
- event = self.get_event(event_type=event_type, instance=instance, **kwargs)
? -----------------------------
+ event = self.get_event(event_type=event_type,
+ event_data=event_data,
+ instance=instance,
+ **kwargs)
self.record_event(event)
+ return event
def record_event(self, event):
""" Record an event.
>>> record_event(Event())
"""
pass |
954fae8ece0c1f2c36a9f8eace9d060546022b2e | filters/tests/config_test.py | filters/tests/config_test.py | from __future__ import absolute_import
import unittest
from flask import Flask
from .. import config
app = Flask('__config_test')
class GetFuncsTest(unittest.TestCase):
"""All tests for get funcs function."""
def test_get_module_funcs(self):
"""Test the return value."""
self.assertIsInstance(config._get_funcs('__main__'), dict)
class InjectFiltersTest(unittest.TestCase):
"""All tests for inject filters function."""
def test_inject_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config._inject_filters(app, {}), Flask)
def test_inject_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config._inject_filters(app, {'foo': lambda x: x})
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
assert 'foo' in app.jinja_env.filters
class ConfigFlaskFiltersTest(unittest.TestCase):
"""All tests for config flask filters function."""
def test_config_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config.config_flask_filters(app), Flask)
def test_config_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config.config_flask_filters(app)
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
| """Test configuration utilities."""
from __future__ import absolute_import
import unittest
from flask import Flask
from .. import config
app = Flask('__config_test')
class GetFuncsTest(unittest.TestCase):
"""All tests for get funcs function."""
def test_get_module_funcs(self):
"""Test the return value."""
self.assertIsInstance(config._get_funcs(config), dict)
def test_get_module_funcs_notempty(self):
"""Test the return value functions length."""
self.assertGreater(len(config._get_funcs(config).items()), 0)
class InjectFiltersTest(unittest.TestCase):
"""All tests for inject filters function."""
def test_inject_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config._inject_filters(app, {}), Flask)
def test_inject_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config._inject_filters(app, {'foo': lambda x: x})
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
assert 'foo' in app.jinja_env.filters
class ConfigFlaskFiltersTest(unittest.TestCase):
"""All tests for config flask filters function."""
def test_config_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config.config_flask_filters(app), Flask)
def test_config_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config.config_flask_filters(app)
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
| Remove protected class access, add module docstrings. | Remove protected class access, add module docstrings.
| Python | mit | christabor/flask_extras,christabor/jinja2_template_pack,christabor/jinja2_template_pack,christabor/flask_extras | + """Test configuration utilities."""
+
from __future__ import absolute_import
import unittest
from flask import Flask
from .. import config
app = Flask('__config_test')
class GetFuncsTest(unittest.TestCase):
"""All tests for get funcs function."""
def test_get_module_funcs(self):
"""Test the return value."""
- self.assertIsInstance(config._get_funcs('__main__'), dict)
+ self.assertIsInstance(config._get_funcs(config), dict)
+
+ def test_get_module_funcs_notempty(self):
+ """Test the return value functions length."""
+ self.assertGreater(len(config._get_funcs(config).items()), 0)
class InjectFiltersTest(unittest.TestCase):
"""All tests for inject filters function."""
def test_inject_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config._inject_filters(app, {}), Flask)
def test_inject_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config._inject_filters(app, {'foo': lambda x: x})
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
assert 'foo' in app.jinja_env.filters
class ConfigFlaskFiltersTest(unittest.TestCase):
"""All tests for config flask filters function."""
def test_config_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config.config_flask_filters(app), Flask)
def test_config_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config.config_flask_filters(app)
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
| Remove protected class access, add module docstrings. | ## Code Before:
from __future__ import absolute_import
import unittest
from flask import Flask
from .. import config
app = Flask('__config_test')
class GetFuncsTest(unittest.TestCase):
"""All tests for get funcs function."""
def test_get_module_funcs(self):
"""Test the return value."""
self.assertIsInstance(config._get_funcs('__main__'), dict)
class InjectFiltersTest(unittest.TestCase):
"""All tests for inject filters function."""
def test_inject_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config._inject_filters(app, {}), Flask)
def test_inject_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config._inject_filters(app, {'foo': lambda x: x})
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
assert 'foo' in app.jinja_env.filters
class ConfigFlaskFiltersTest(unittest.TestCase):
"""All tests for config flask filters function."""
def test_config_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config.config_flask_filters(app), Flask)
def test_config_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config.config_flask_filters(app)
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
## Instruction:
Remove protected class access, add module docstrings.
## Code After:
"""Test configuration utilities."""
from __future__ import absolute_import
import unittest
from flask import Flask
from .. import config
app = Flask('__config_test')
class GetFuncsTest(unittest.TestCase):
"""All tests for get funcs function."""
def test_get_module_funcs(self):
"""Test the return value."""
self.assertIsInstance(config._get_funcs(config), dict)
def test_get_module_funcs_notempty(self):
"""Test the return value functions length."""
self.assertGreater(len(config._get_funcs(config).items()), 0)
class InjectFiltersTest(unittest.TestCase):
"""All tests for inject filters function."""
def test_inject_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config._inject_filters(app, {}), Flask)
def test_inject_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config._inject_filters(app, {'foo': lambda x: x})
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
assert 'foo' in app.jinja_env.filters
class ConfigFlaskFiltersTest(unittest.TestCase):
"""All tests for config flask filters function."""
def test_config_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config.config_flask_filters(app), Flask)
def test_config_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config.config_flask_filters(app)
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
| + """Test configuration utilities."""
+
from __future__ import absolute_import
import unittest
from flask import Flask
from .. import config
app = Flask('__config_test')
class GetFuncsTest(unittest.TestCase):
"""All tests for get funcs function."""
def test_get_module_funcs(self):
"""Test the return value."""
- self.assertIsInstance(config._get_funcs('__main__'), dict)
? ^^^^^ ^^^^
+ self.assertIsInstance(config._get_funcs(config), dict)
? ^^^^ ^
+
+ def test_get_module_funcs_notempty(self):
+ """Test the return value functions length."""
+ self.assertGreater(len(config._get_funcs(config).items()), 0)
class InjectFiltersTest(unittest.TestCase):
"""All tests for inject filters function."""
def test_inject_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config._inject_filters(app, {}), Flask)
def test_inject_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config._inject_filters(app, {'foo': lambda x: x})
new = len(app.jinja_env.filters)
self.assertGreater(new, old)
assert 'foo' in app.jinja_env.filters
class ConfigFlaskFiltersTest(unittest.TestCase):
"""All tests for config flask filters function."""
def test_config_filters_inst(self):
"""Test the return value."""
self.assertIsInstance(config.config_flask_filters(app), Flask)
def test_config_filters_count(self):
"""Test the return value."""
old = len(app.jinja_env.filters)
config.config_flask_filters(app)
new = len(app.jinja_env.filters)
self.assertGreater(new, old) |
1dd257b157cfcb13a13a9c97ff6580045026118c | __openerp__.py | __openerp__.py | {
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
'account_menu_entries.xml',
'account_move_line_journal_view.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| {
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
'account_move_line_journal_view.xml',
'account_menu_entries.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| Change the order when loading xml data | Change the order when loading xml data
| Python | agpl-3.0 | xcgd/account_streamline | {
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
+ 'account_move_line_journal_view.xml',
'account_menu_entries.xml',
- 'account_move_line_journal_view.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| Change the order when loading xml data | ## Code Before:
{
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
'account_menu_entries.xml',
'account_move_line_journal_view.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
## Instruction:
Change the order when loading xml data
## Code After:
{
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
'account_move_line_journal_view.xml',
'account_menu_entries.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| {
"name": "Account Streamline",
"version": "0.1",
"author": "XCG Consulting",
"category": 'Accounting',
"description": """Enhancements to the account module to streamline its
usage.
""",
'website': 'http://www.openerp-experts.com',
'init_xml': [],
"depends": [
'base',
'account_accountant',
'account_voucher',
'account_payment',
'account_sequence',
'analytic_structure',
'advanced_filter'],
"data": [
'data/partner_data.xml',
'wizard/account_reconcile_view.xml',
'account_move_line_search_unreconciled.xml',
'account_move_line_tree.xml',
'account_move_view.xml',
'account_view.xml',
'partner_view.xml',
'payment_selection.xml',
'account_move_line_journal_items.xml',
+ 'account_move_line_journal_view.xml',
'account_menu_entries.xml',
- 'account_move_line_journal_view.xml',
'data/analytic.code.csv',
'data/analytic.dimension.csv',
'data/analytic.structure.csv'
],
#'demo_xml': [],
'test': [],
'installable': True,
'active': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
9ce5a020ac6e9bbdf7e2fc0c34c98cdfaf9e0a45 | tests/formatters/conftest.py | tests/formatters/conftest.py | import npc
import pytest
@pytest.fixture(scope="module")
def character():
char = npc.character.Character()
char.append('description', 'Fee fie foe fum')
char.append('type', 'human')
return char
| import npc
import pytest
@pytest.fixture(scope="module")
def character():
char = npc.character.Character()
char.tags('description').append('Fee fie foe fum')
char.tags('type').append('human')
return char
| Set up defaults using tag syntax | Set up defaults using tag syntax
| Python | mit | aurule/npc,aurule/npc | import npc
import pytest
@pytest.fixture(scope="module")
def character():
char = npc.character.Character()
- char.append('description', 'Fee fie foe fum')
+ char.tags('description').append('Fee fie foe fum')
- char.append('type', 'human')
+ char.tags('type').append('human')
return char
| Set up defaults using tag syntax | ## Code Before:
import npc
import pytest
@pytest.fixture(scope="module")
def character():
char = npc.character.Character()
char.append('description', 'Fee fie foe fum')
char.append('type', 'human')
return char
## Instruction:
Set up defaults using tag syntax
## Code After:
import npc
import pytest
@pytest.fixture(scope="module")
def character():
char = npc.character.Character()
char.tags('description').append('Fee fie foe fum')
char.tags('type').append('human')
return char
| import npc
import pytest
@pytest.fixture(scope="module")
def character():
char = npc.character.Character()
- char.append('description', 'Fee fie foe fum')
? ^^^^^ ^^
+ char.tags('description').append('Fee fie foe fum')
? + ^^ ^^^^^^^^^
- char.append('type', 'human')
+ char.tags('type').append('human')
return char |
d37dc009f1c4f6e8855657dd6dbf17df9332f765 | test/os_win7.py | test/os_win7.py |
import unittest
from mbed_lstools.lstools_win7 import MbedLsToolsWin7
class Win7TestCase(unittest.TestCase):
""" Basic test cases checking trivial asserts
"""
def setUp(self):
pass
def test_os_supported(self):
pass
if __name__ == '__main__':
unittest.main()
|
import unittest
from mbed_lstools.lstools_win7 import MbedLsToolsWin7
# Since we don't have mock, let's monkey-patch
def get_mbed_devices_new(self):
return [
('\\DosDevices\\D:', '_??_USBSTOR#Disk&Ven_MBED&Prod_XPRO&Rev_1.00#9&35913356&0&ATML2127031800007973&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}'),
]
class Win7TestCase(unittest.TestCase):
""" Basic test cases checking trivial asserts
"""
def setUp(self):
pass
def test_os_supported(self):
pass
def test_get_mbeds(self):
m = MbedLsToolsWin7()
func_type = type(MbedLsToolsWin7.get_mbed_devices)
m.get_mbed_devices = func_type(get_mbed_devices_new, m, MbedLsToolsWin7)
mbeds = m.get_mbeds()
self.assertIsNotNone(mbeds)
self.assertEqual(1, len(mbeds))
mbed = mbeds[0]
self.assertEqual("D:", mbed[0])
self.assertEqual("ATML2127031800007973", mbed[1])
if __name__ == '__main__':
unittest.main()
| Add test for mbed parsing | Add test for mbed parsing
| Python | apache-2.0 | jupe/mbed-ls,jupe/mbed-ls,mazimkhan/mbed-ls,mtmtech/mbed-ls,mazimkhan/mbed-ls,mtmtech/mbed-ls |
import unittest
from mbed_lstools.lstools_win7 import MbedLsToolsWin7
+ # Since we don't have mock, let's monkey-patch
+
+ def get_mbed_devices_new(self):
+ return [
+ ('\\DosDevices\\D:', '_??_USBSTOR#Disk&Ven_MBED&Prod_XPRO&Rev_1.00#9&35913356&0&ATML2127031800007973&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}'),
+ ]
class Win7TestCase(unittest.TestCase):
""" Basic test cases checking trivial asserts
"""
def setUp(self):
pass
def test_os_supported(self):
pass
+
+ def test_get_mbeds(self):
+
+ m = MbedLsToolsWin7()
+
+ func_type = type(MbedLsToolsWin7.get_mbed_devices)
+ m.get_mbed_devices = func_type(get_mbed_devices_new, m, MbedLsToolsWin7)
+
+ mbeds = m.get_mbeds()
+
+ self.assertIsNotNone(mbeds)
+ self.assertEqual(1, len(mbeds))
+
+ mbed = mbeds[0]
+
+ self.assertEqual("D:", mbed[0])
+ self.assertEqual("ATML2127031800007973", mbed[1])
+
if __name__ == '__main__':
unittest.main()
| Add test for mbed parsing | ## Code Before:
import unittest
from mbed_lstools.lstools_win7 import MbedLsToolsWin7
class Win7TestCase(unittest.TestCase):
""" Basic test cases checking trivial asserts
"""
def setUp(self):
pass
def test_os_supported(self):
pass
if __name__ == '__main__':
unittest.main()
## Instruction:
Add test for mbed parsing
## Code After:
import unittest
from mbed_lstools.lstools_win7 import MbedLsToolsWin7
# Since we don't have mock, let's monkey-patch
def get_mbed_devices_new(self):
return [
('\\DosDevices\\D:', '_??_USBSTOR#Disk&Ven_MBED&Prod_XPRO&Rev_1.00#9&35913356&0&ATML2127031800007973&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}'),
]
class Win7TestCase(unittest.TestCase):
""" Basic test cases checking trivial asserts
"""
def setUp(self):
pass
def test_os_supported(self):
pass
def test_get_mbeds(self):
m = MbedLsToolsWin7()
func_type = type(MbedLsToolsWin7.get_mbed_devices)
m.get_mbed_devices = func_type(get_mbed_devices_new, m, MbedLsToolsWin7)
mbeds = m.get_mbeds()
self.assertIsNotNone(mbeds)
self.assertEqual(1, len(mbeds))
mbed = mbeds[0]
self.assertEqual("D:", mbed[0])
self.assertEqual("ATML2127031800007973", mbed[1])
if __name__ == '__main__':
unittest.main()
|
import unittest
from mbed_lstools.lstools_win7 import MbedLsToolsWin7
+ # Since we don't have mock, let's monkey-patch
+
+ def get_mbed_devices_new(self):
+ return [
+ ('\\DosDevices\\D:', '_??_USBSTOR#Disk&Ven_MBED&Prod_XPRO&Rev_1.00#9&35913356&0&ATML2127031800007973&0#{53f56307-b6bf-11d0-94f2-00a0c91efb8b}'),
+ ]
class Win7TestCase(unittest.TestCase):
""" Basic test cases checking trivial asserts
"""
def setUp(self):
pass
def test_os_supported(self):
pass
+
+ def test_get_mbeds(self):
+
+ m = MbedLsToolsWin7()
+
+ func_type = type(MbedLsToolsWin7.get_mbed_devices)
+ m.get_mbed_devices = func_type(get_mbed_devices_new, m, MbedLsToolsWin7)
+
+ mbeds = m.get_mbeds()
+
+ self.assertIsNotNone(mbeds)
+ self.assertEqual(1, len(mbeds))
+
+ mbed = mbeds[0]
+
+ self.assertEqual("D:", mbed[0])
+ self.assertEqual("ATML2127031800007973", mbed[1])
+
if __name__ == '__main__':
unittest.main() |
9437b7fa2ef7f581968d6628561940dcb1e3f4ad | test_tws/__init__.py | test_tws/__init__.py | '''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__(self):
self.errors = []
def error(self, id, code, text):
self.errors.append((id, code, text))
class mock_socket(object):
def __init__(self):
self._peer = ()
def connect(self, peer, error=False):
if error: raise socket.error()
self._peer = peer
def getpeername(self):
if not self._peer: raise socket.error()
return self._peer
def makefile(self, mode):
return StringIO()
| '''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__(self):
self.calldata = []
self.errors = []
def error(self, id, code, text):
self.errors.append((id, code, text))
def __getattr__(self, name):
# Any arbitrary unknown attribute is mapped to a function call which is
# recorded into self.calldata.
return lambda *args, **kwds: self.calldata.append((name, args, kwds))
class mock_socket(object):
def __init__(self):
self._peer = ()
def connect(self, peer, error=False):
if error: raise socket.error()
self._peer = peer
def getpeername(self):
if not self._peer: raise socket.error()
return self._peer
def makefile(self, mode):
return StringIO()
| Implement a __getattr__() for mock_wrapper that just returns a lambda that records whatever call was attempted along with the call params. | Implement a __getattr__() for mock_wrapper that just returns a lambda that records whatever call was attempted along with the call params. | Python | bsd-3-clause | kbluck/pytws,kbluck/pytws | '''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__(self):
+ self.calldata = []
self.errors = []
def error(self, id, code, text):
self.errors.append((id, code, text))
-
+
+ def __getattr__(self, name):
+ # Any arbitrary unknown attribute is mapped to a function call which is
+ # recorded into self.calldata.
+ return lambda *args, **kwds: self.calldata.append((name, args, kwds))
+
+
class mock_socket(object):
def __init__(self):
self._peer = ()
def connect(self, peer, error=False):
if error: raise socket.error()
self._peer = peer
def getpeername(self):
if not self._peer: raise socket.error()
return self._peer
def makefile(self, mode):
return StringIO()
| Implement a __getattr__() for mock_wrapper that just returns a lambda that records whatever call was attempted along with the call params. | ## Code Before:
'''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__(self):
self.errors = []
def error(self, id, code, text):
self.errors.append((id, code, text))
class mock_socket(object):
def __init__(self):
self._peer = ()
def connect(self, peer, error=False):
if error: raise socket.error()
self._peer = peer
def getpeername(self):
if not self._peer: raise socket.error()
return self._peer
def makefile(self, mode):
return StringIO()
## Instruction:
Implement a __getattr__() for mock_wrapper that just returns a lambda that records whatever call was attempted along with the call params.
## Code After:
'''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__(self):
self.calldata = []
self.errors = []
def error(self, id, code, text):
self.errors.append((id, code, text))
def __getattr__(self, name):
# Any arbitrary unknown attribute is mapped to a function call which is
# recorded into self.calldata.
return lambda *args, **kwds: self.calldata.append((name, args, kwds))
class mock_socket(object):
def __init__(self):
self._peer = ()
def connect(self, peer, error=False):
if error: raise socket.error()
self._peer = peer
def getpeername(self):
if not self._peer: raise socket.error()
return self._peer
def makefile(self, mode):
return StringIO()
| '''Unit test package for package "tws".'''
__copyright__ = "Copyright (c) 2008 Kevin J Bluck"
__version__ = "$Id$"
import socket
from tws import EWrapper
def test_import():
'''Verify successful import of top-level "tws" package'''
import tws
assert tws
class mock_wrapper(EWrapper):
def __init__(self):
+ self.calldata = []
self.errors = []
def error(self, id, code, text):
self.errors.append((id, code, text))
-
+
+ def __getattr__(self, name):
+ # Any arbitrary unknown attribute is mapped to a function call which is
+ # recorded into self.calldata.
+ return lambda *args, **kwds: self.calldata.append((name, args, kwds))
+
+
class mock_socket(object):
def __init__(self):
self._peer = ()
def connect(self, peer, error=False):
if error: raise socket.error()
self._peer = peer
def getpeername(self):
if not self._peer: raise socket.error()
return self._peer
def makefile(self, mode):
return StringIO()
|
3b5f1749a8065bb9241d6a8ed77c047a05b3f6e2 | bcbio/distributed/sge.py | bcbio/distributed/sge.py | import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
run_info = subprocess.check_output(["qstat"])
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
# handle SGE errors, retrying to get the current status
max_retries = 10
tried = 0
while 1:
try:
run_info = subprocess.check_output(["qstat"])
break
except:
tried += 1
if tried > max_retries:
raise
time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| Handle temporary errors returned from SGE qstat | Handle temporary errors returned from SGE qstat
| Python | mit | biocyberman/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,mjafin/bcbio-nextgen,chapmanb/bcbio-nextgen,lpantano/bcbio-nextgen,fw1121/bcbio-nextgen,brainstorm/bcbio-nextgen,fw1121/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,verdurin/bcbio-nextgen,mjafin/bcbio-nextgen,vladsaveliev/bcbio-nextgen,SciLifeLab/bcbio-nextgen,SciLifeLab/bcbio-nextgen,chapmanb/bcbio-nextgen,lbeltrame/bcbio-nextgen,a113n/bcbio-nextgen,biocyberman/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,hjanime/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,hjanime/bcbio-nextgen,verdurin/bcbio-nextgen,vladsaveliev/bcbio-nextgen,a113n/bcbio-nextgen,lpantano/bcbio-nextgen,mjafin/bcbio-nextgen,gifford-lab/bcbio-nextgen,gifford-lab/bcbio-nextgen,hjanime/bcbio-nextgen,brainstorm/bcbio-nextgen,gifford-lab/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,chapmanb/bcbio-nextgen,vladsaveliev/bcbio-nextgen,lpantano/bcbio-nextgen,a113n/bcbio-nextgen,brainstorm/bcbio-nextgen,elkingtonmcb/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,biocyberman/bcbio-nextgen,Cyberbio-Lab/bcbio-nextgen,SciLifeLab/bcbio-nextgen,fw1121/bcbio-nextgen,verdurin/bcbio-nextgen,lbeltrame/bcbio-nextgen,guillermo-carrasco/bcbio-nextgen,lbeltrame/bcbio-nextgen | import re
+ import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
+ # handle SGE errors, retrying to get the current status
+ max_retries = 10
+ tried = 0
+ while 1:
+ try:
- run_info = subprocess.check_output(["qstat"])
+ run_info = subprocess.check_output(["qstat"])
+ break
+ except:
+ tried += 1
+ if tried > max_retries:
+ raise
+ time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| Handle temporary errors returned from SGE qstat | ## Code Before:
import re
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
run_info = subprocess.check_output(["qstat"])
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
## Instruction:
Handle temporary errors returned from SGE qstat
## Code After:
import re
import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
# handle SGE errors, retrying to get the current status
max_retries = 10
tried = 0
while 1:
try:
run_info = subprocess.check_output(["qstat"])
break
except:
tried += 1
if tried > max_retries:
raise
time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids)
| import re
+ import time
import subprocess
_jobid_pat = re.compile('Your job (?P<jobid>\d+) \("')
def submit_job(scheduler_args, command):
"""Submit a job to the scheduler, returning the supplied job ID.
"""
cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command
status = subprocess.check_output(cl)
match = _jobid_pat.search(status)
return match.groups("jobid")[0]
def stop_job(jobid):
cl = ["qdel", jobid]
subprocess.check_call(cl)
def are_running(jobids):
"""Check if submitted job IDs are running.
"""
+ # handle SGE errors, retrying to get the current status
+ max_retries = 10
+ tried = 0
+ while 1:
+ try:
- run_info = subprocess.check_output(["qstat"])
+ run_info = subprocess.check_output(["qstat"])
? ++++++++
+ break
+ except:
+ tried += 1
+ if tried > max_retries:
+ raise
+ time.sleep(5)
running = []
for parts in (l.split() for l in run_info.split("\n") if l.strip()):
if len(parts) >= 5:
pid, _, _, _, status = parts[:5]
if status.lower() in ["r"]:
running.append(pid)
want_running = set(running).intersection(set(jobids))
return len(want_running) == len(jobids) |
766ea05836544b808cd2c346873d9e4f60c858a1 | ping/tests/test_ping.py | ping/tests/test_ping.py | import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
| import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
aggregator.assert_metric('network.ping.can_connect', value=1)
| Update test to assert metric | Update test to assert metric
| Python | bsd-3-clause | DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras | import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
+ aggregator.assert_metric('network.ping.can_connect', value=1)
| Update test to assert metric | ## Code Before:
import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
## Instruction:
Update test to assert metric
## Code After:
import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
aggregator.assert_metric('network.ping.can_connect', value=1)
| import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.093/0.093/0.093/0.000 ms"""
def test_check(aggregator, instance):
c = PingCheck('ping', {}, {})
# empty instance
instance = {}
with pytest.raises(CheckException):
c.check(instance)
# only name
with pytest.raises(CheckException):
c.check({'name': 'Datadog'})
test_check
# good check
instance = {
'host': '127.0.0.1',
'name': "Localhost"
}
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
+ aggregator.assert_metric('network.ping.can_connect', value=1) |
5d622e350784ede5af2490495ce3119a2589b1e9 | hb_res/resources/build_assets.py | hb_res/resources/build_assets.py | from .Resource import names_registered, resource_by_name
def build():
for name in names_registered():
resource = resource_by_name(name)()
for explanation in resource:
r = explanation
for functor in resource.modifiers:
r = functor(r)
# write res in file 'name'
print(r)
| from .Resource import names_registered, resource_by_name
def build():
for name in names_registered():
resource = resource_by_name(name)()
for explanation in resource:
r = explanation
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is None:
continue
# write res in file 'name'
print(r)
| Add None check while applying modifiers | Add None check while applying modifiers
| Python | mit | hatbot-team/hatbot_resources | - from .Resource import names_registered, resource_by_name
+ from .Resource import names_registered, resource_by_name
+
def build():
for name in names_registered():
resource = resource_by_name(name)()
for explanation in resource:
r = explanation
for functor in resource.modifiers:
+ if r is None:
+ break
r = functor(r)
+ if r is None:
+ continue
# write res in file 'name'
print(r)
| Add None check while applying modifiers | ## Code Before:
from .Resource import names_registered, resource_by_name
def build():
for name in names_registered():
resource = resource_by_name(name)()
for explanation in resource:
r = explanation
for functor in resource.modifiers:
r = functor(r)
# write res in file 'name'
print(r)
## Instruction:
Add None check while applying modifiers
## Code After:
from .Resource import names_registered, resource_by_name
def build():
for name in names_registered():
resource = resource_by_name(name)()
for explanation in resource:
r = explanation
for functor in resource.modifiers:
if r is None:
break
r = functor(r)
if r is None:
continue
# write res in file 'name'
print(r)
| - from .Resource import names_registered, resource_by_name
? -
+ from .Resource import names_registered, resource_by_name
+
def build():
for name in names_registered():
resource = resource_by_name(name)()
for explanation in resource:
r = explanation
for functor in resource.modifiers:
+ if r is None:
+ break
r = functor(r)
+ if r is None:
+ continue
# write res in file 'name'
print(r) |
d54cb3d29f78ce1e06e549de783326c052054777 | mezzanine_api/settings.py | mezzanine_api/settings.py |
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_path': '/',
'api_key': '', # Your OAuth2 Access Token
'token_type': 'Bearer',
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
'info': {
'title': 'API Resource Documentation',
'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. '
'This interactive document will guide you through the relevant API endpoints, data structures, '
'and query parameters for filtering, searching and pagination. Otherwise, for further '
'information and examples, consult the general '
'<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation'
'</a>.',
},
'doc_expansion': 'none',
}
|
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
# API login URL for oauth2_provider (based on default routing in urls.py)
LOGIN_URL = "/api/auth/login/"
SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_path': '/',
'api_key': '', # Your OAuth2 Access Token
'token_type': 'Bearer',
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
'info': {
'title': 'API Resource Documentation',
'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. '
'This interactive document will guide you through the relevant API endpoints, data structures, '
'and query parameters for filtering, searching and pagination. Otherwise, for further '
'information and examples, consult the general '
'<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation'
'</a>.',
},
'doc_expansion': 'none',
}
| Add LOGIN_URL setting for Oauth2 | Add LOGIN_URL setting for Oauth2
| Python | mit | gcushen/mezzanine-api,gcushen/mezzanine-api |
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
+
+ # API login URL for oauth2_provider (based on default routing in urls.py)
+ LOGIN_URL = "/api/auth/login/"
SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_path': '/',
'api_key': '', # Your OAuth2 Access Token
'token_type': 'Bearer',
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
'info': {
'title': 'API Resource Documentation',
'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. '
'This interactive document will guide you through the relevant API endpoints, data structures, '
'and query parameters for filtering, searching and pagination. Otherwise, for further '
'information and examples, consult the general '
'<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation'
'</a>.',
},
'doc_expansion': 'none',
}
+ | Add LOGIN_URL setting for Oauth2 | ## Code Before:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_path': '/',
'api_key': '', # Your OAuth2 Access Token
'token_type': 'Bearer',
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
'info': {
'title': 'API Resource Documentation',
'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. '
'This interactive document will guide you through the relevant API endpoints, data structures, '
'and query parameters for filtering, searching and pagination. Otherwise, for further '
'information and examples, consult the general '
'<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation'
'</a>.',
},
'doc_expansion': 'none',
}
## Instruction:
Add LOGIN_URL setting for Oauth2
## Code After:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
# API login URL for oauth2_provider (based on default routing in urls.py)
LOGIN_URL = "/api/auth/login/"
SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_path': '/',
'api_key': '', # Your OAuth2 Access Token
'token_type': 'Bearer',
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
'info': {
'title': 'API Resource Documentation',
'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. '
'This interactive document will guide you through the relevant API endpoints, data structures, '
'and query parameters for filtering, searching and pagination. Otherwise, for further '
'information and examples, consult the general '
'<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation'
'</a>.',
},
'doc_expansion': 'none',
}
|
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'oauth2_provider.ext.rest_framework.OAuth2Authentication',
),
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
'TEST_REQUEST_DEFAULT_FORMAT': 'json',
}
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
+
+ # API login URL for oauth2_provider (based on default routing in urls.py)
+ LOGIN_URL = "/api/auth/login/"
SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_path': '/',
'api_key': '', # Your OAuth2 Access Token
'token_type': 'Bearer',
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
'info': {
'title': 'API Resource Documentation',
'description': 'The RESTful web API exposes Mezzanine data using JSON serialization and OAuth2 protection. '
'This interactive document will guide you through the relevant API endpoints, data structures, '
'and query parameters for filtering, searching and pagination. Otherwise, for further '
'information and examples, consult the general '
'<a href="http://gcushen.github.io/mezzanine-api" target="_blank">Mezzanine API Documentation'
'</a>.',
},
'doc_expansion': 'none',
}
+ |
115ffb22128e12a0cc88b7c0cd1dd9bde04fb768 | wagtail/utils/compat.py | wagtail/utils/compat.py | def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
return getattr(rel, 'related_model', rel.model)
| import django
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
if django.VERSION >= (1, 8):
return rel.related_model
else:
return rel.model
| Check Django version instead of hasattr | Check Django version instead of hasattr
| Python | bsd-3-clause | mixxorz/wagtail,taedori81/wagtail,FlipperPA/wagtail,mixxorz/wagtail,bjesus/wagtail,mjec/wagtail,stevenewey/wagtail,gasman/wagtail,hanpama/wagtail,thenewguy/wagtail,serzans/wagtail,kurtw/wagtail,Klaudit/wagtail,hamsterbacke23/wagtail,rv816/wagtail,Klaudit/wagtail,janusnic/wagtail,kurtrwall/wagtail,marctc/wagtail,rjsproxy/wagtail,jordij/wagtail,quru/wagtail,davecranwell/wagtail,hanpama/wagtail,zerolab/wagtail,JoshBarr/wagtail,takeflight/wagtail,rv816/wagtail,Klaudit/wagtail,inonit/wagtail,JoshBarr/wagtail,gasman/wagtail,mephizzle/wagtail,mayapurmedia/wagtail,jnns/wagtail,quru/wagtail,mixxorz/wagtail,iho/wagtail,janusnic/wagtail,timorieber/wagtail,darith27/wagtail,bjesus/wagtail,KimGlazebrook/wagtail-experiment,taedori81/wagtail,WQuanfeng/wagtail,nilnvoid/wagtail,kaedroho/wagtail,gogobook/wagtail,jnns/wagtail,chrxr/wagtail,mjec/wagtail,hamsterbacke23/wagtail,wagtail/wagtail,gogobook/wagtail,rsalmaso/wagtail,takeflight/wagtail,nimasmi/wagtail,kaedroho/wagtail,WQuanfeng/wagtail,hamsterbacke23/wagtail,nutztherookie/wagtail,nrsimha/wagtail,FlipperPA/wagtail,iansprice/wagtail,mayapurmedia/wagtail,rjsproxy/wagtail,thenewguy/wagtail,takeshineshiro/wagtail,mjec/wagtail,nilnvoid/wagtail,davecranwell/wagtail,thenewguy/wagtail,chrxr/wagtail,rsalmaso/wagtail,takeshineshiro/wagtail,Klaudit/wagtail,kurtrwall/wagtail,mephizzle/wagtail,taedori81/wagtail,jnns/wagtail,iho/wagtail,janusnic/wagtail,nrsimha/wagtail,serzans/wagtail,stevenewey/wagtail,FlipperPA/wagtail,nimasmi/wagtail,hanpama/wagtail,kaedroho/wagtail,m-sanders/wagtail,stevenewey/wagtail,hanpama/wagtail,jnns/wagtail,jordij/wagtail,taedori81/wagtail,mikedingjan/wagtail,gogobook/wagtail,mayapurmedia/wagtail,bjesus/wagtail,kurtw/wagtail,nimasmi/wagtail,torchbox/wagtail,takeflight/wagtail,m-sanders/wagtail,mixxorz/wagtail,kurtrwall/wagtail,kurtw/wagtail,Toshakins/wagtail,stevenewey/wagtail,wagtail/wagtail,mikedingjan/wagtail,kaedroho/wagtail,jordij/wagtail,nealtodd/wagtail,mixxorz/wagtail,m-sanders/wagtail,Tivix/wagtail,JoshBarr/wagtail,torchbox/wagtail,torchbox/wagtail,zerolab/wagtail,nilnvoid/wagtail,rsalmaso/wagtail,Tivix/wagtail,zerolab/wagtail,iansprice/wagtail,Pennebaker/wagtail,nilnvoid/wagtail,serzans/wagtail,Tivix/wagtail,timorieber/wagtail,quru/wagtail,zerolab/wagtail,mikedingjan/wagtail,hamsterbacke23/wagtail,gasman/wagtail,mikedingjan/wagtail,darith27/wagtail,rv816/wagtail,gogobook/wagtail,marctc/wagtail,nrsimha/wagtail,zerolab/wagtail,tangentlabs/wagtail,Pennebaker/wagtail,gasman/wagtail,chrxr/wagtail,davecranwell/wagtail,thenewguy/wagtail,rsalmaso/wagtail,Tivix/wagtail,nealtodd/wagtail,nimasmi/wagtail,Pennebaker/wagtail,WQuanfeng/wagtail,bjesus/wagtail,nutztherookie/wagtail,kurtrwall/wagtail,darith27/wagtail,tangentlabs/wagtail,Toshakins/wagtail,inonit/wagtail,jordij/wagtail,rv816/wagtail,marctc/wagtail,nutztherookie/wagtail,wagtail/wagtail,janusnic/wagtail,inonit/wagtail,WQuanfeng/wagtail,m-sanders/wagtail,iansprice/wagtail,thenewguy/wagtail,mayapurmedia/wagtail,tangentlabs/wagtail,timorieber/wagtail,mjec/wagtail,gasman/wagtail,rjsproxy/wagtail,iansprice/wagtail,wagtail/wagtail,takeshineshiro/wagtail,nutztherookie/wagtail,serzans/wagtail,nealtodd/wagtail,quru/wagtail,inonit/wagtail,Toshakins/wagtail,takeflight/wagtail,chrxr/wagtail,darith27/wagtail,nealtodd/wagtail,Toshakins/wagtail,takeshineshiro/wagtail,mephizzle/wagtail,JoshBarr/wagtail,KimGlazebrook/wagtail-experiment,FlipperPA/wagtail,wagtail/wagtail,davecranwell/wagtail,tangentlabs/wagtail,torchbox/wagtail,kaedroho/wagtail,KimGlazebrook/wagtail-experiment,mephizzle/wagtail,marctc/wagtail,kurtw/wagtail,iho/wagtail,rjsproxy/wagtail,taedori81/wagtail,nrsimha/wagtail,iho/wagtail,timorieber/wagtail,Pennebaker/wagtail,KimGlazebrook/wagtail-experiment,rsalmaso/wagtail | + import django
+
+
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
- return getattr(rel, 'related_model', rel.model)
+ if django.VERSION >= (1, 8):
+ return rel.related_model
+ else:
+ return rel.model
| Check Django version instead of hasattr | ## Code Before:
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
return getattr(rel, 'related_model', rel.model)
## Instruction:
Check Django version instead of hasattr
## Code After:
import django
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
if django.VERSION >= (1, 8):
return rel.related_model
else:
return rel.model
| + import django
+
+
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
- return getattr(rel, 'related_model', rel.model)
+ if django.VERSION >= (1, 8):
+ return rel.related_model
+ else:
+ return rel.model |
bfdf65558e2f9b5b4e8d385b2911db374ffbfe03 | qipipe/qiprofile/update.py | qipipe/qiprofile/update.py | from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, filename):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
:param filename: the XLS input file location
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
clinical.update(sbj, filename)
# Update the imaging information from XNAT.
imaging.update(sbj, session)
| from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, spreadsheet):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
:param spreadsheet: the spreadsheet input file location
:param modeling_technique: the modeling technique
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
clinical.update(sbj, spreadsheet)
# Update the imaging information from XNAT.
imaging.update(sbj, session)
| Rename the filename argument to spreadsheet. | Rename the filename argument to spreadsheet.
| Python | bsd-2-clause | ohsu-qin/qipipe | from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
- def update(project, collection, subject, session, filename):
+ def update(project, collection, subject, session, spreadsheet):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
- :param filename: the XLS input file location
+ :param spreadsheet: the spreadsheet input file location
+ :param modeling_technique: the modeling technique
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
- clinical.update(sbj, filename)
+ clinical.update(sbj, spreadsheet)
# Update the imaging information from XNAT.
imaging.update(sbj, session)
| Rename the filename argument to spreadsheet. | ## Code Before:
from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, filename):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
:param filename: the XLS input file location
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
clinical.update(sbj, filename)
# Update the imaging information from XNAT.
imaging.update(sbj, session)
## Instruction:
Rename the filename argument to spreadsheet.
## Code After:
from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
def update(project, collection, subject, session, spreadsheet):
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
:param spreadsheet: the spreadsheet input file location
:param modeling_technique: the modeling technique
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
clinical.update(sbj, spreadsheet)
# Update the imaging information from XNAT.
imaging.update(sbj, session)
| from qiprofile_rest_client.helpers import database
from qiprofile_rest_client.model.subject import Subject
from qiprofile_rest_client.model.imaging import Session
from . import (clinical, imaging)
- def update(project, collection, subject, session, filename):
? ^^^ - ^
+ def update(project, collection, subject, session, spreadsheet):
? ^^^ ^^^ ++
"""
Updates the qiprofile database from the clinical spreadsheet and
XNAT database for the given session.
:param project: the XNAT project name
:param collection: the image collection name
:param subject: the subject number
:param session: the XNAT session number
- :param filename: the XLS input file location
+ :param spreadsheet: the spreadsheet input file location
+ :param modeling_technique: the modeling technique
"""
# Get or create the subject database subject.
key = dict(project=project, collection=collection, number=subject)
sbj = database.get_or_create(Subject, key)
# Update the clinical information from the XLS input.
- clinical.update(sbj, filename)
? ^^^ - ^
+ clinical.update(sbj, spreadsheet)
? ^^^ ^^^ ++
# Update the imaging information from XNAT.
imaging.update(sbj, session) |
47f495e7e5b8fa06991e0c263bc9239818dd5b4f | airpy/list.py | airpy/list.py | import os
import airpy
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n') | from __future__ import print_function
import os
import airpy
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n')
| Add a Backwards compatibility for python 2.7 by adding a __future__ import | Add a Backwards compatibility for python 2.7 by adding a __future__ import
| Python | mit | kevinaloys/airpy | + from __future__ import print_function
import os
import airpy
+
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n')
+ | Add a Backwards compatibility for python 2.7 by adding a __future__ import | ## Code Before:
import os
import airpy
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n')
## Instruction:
Add a Backwards compatibility for python 2.7 by adding a __future__ import
## Code After:
from __future__ import print_function
import os
import airpy
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n')
| + from __future__ import print_function
import os
import airpy
+
def airlist():
installed_docs = os.listdir(airpy.data_directory)
for dir in installed_docs:
print(dir, end= ' ')
print(end = '\n') |
1633fe8e8e3d97273256fd64cac0447737ef1594 | jsonrpcclient/__init__.py | jsonrpcclient/__init__.py | """__init__.py"""
from jsonrpcclient.request import Request
| """__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| Add NullHandler to logger to quiet Python 2.7 | Add NullHandler to logger to quiet Python 2.7
| Python | mit | bcb/jsonrpcclient | """__init__.py"""
+
+ import logging
+ logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
+
from jsonrpcclient.request import Request
| Add NullHandler to logger to quiet Python 2.7 | ## Code Before:
"""__init__.py"""
from jsonrpcclient.request import Request
## Instruction:
Add NullHandler to logger to quiet Python 2.7
## Code After:
"""__init__.py"""
import logging
logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
from jsonrpcclient.request import Request
| """__init__.py"""
+
+ import logging
+ logging.getLogger('jsonrpcclient').addHandler(logging.NullHandler())
+
from jsonrpcclient.request import Request |
08797de13a88bc742d905f2067df533a1a319c83 | yawf/revision/models.py | yawf/revision/models.py | from django.db import models
from django.contrib.contenttypes import generic
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
versions = generic.GenericRelation('reversion.Version')
def save(self, *args, **kwargs):
self.revision += 1
super(RevisionModelMixin, self).save(*args, **kwargs)
| from django.db import models
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
def save(self, *args, **kwargs):
self.revision += 1
super(RevisionModelMixin, self).save(*args, **kwargs)
| Remove generic relation to reversion.Version from RevisionModelMixin | Remove generic relation to reversion.Version from RevisionModelMixin
| Python | mit | freevoid/yawf | from django.db import models
- from django.contrib.contenttypes import generic
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
- versions = generic.GenericRelation('reversion.Version')
-
def save(self, *args, **kwargs):
self.revision += 1
super(RevisionModelMixin, self).save(*args, **kwargs)
| Remove generic relation to reversion.Version from RevisionModelMixin | ## Code Before:
from django.db import models
from django.contrib.contenttypes import generic
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
versions = generic.GenericRelation('reversion.Version')
def save(self, *args, **kwargs):
self.revision += 1
super(RevisionModelMixin, self).save(*args, **kwargs)
## Instruction:
Remove generic relation to reversion.Version from RevisionModelMixin
## Code After:
from django.db import models
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
def save(self, *args, **kwargs):
self.revision += 1
super(RevisionModelMixin, self).save(*args, **kwargs)
| from django.db import models
- from django.contrib.contenttypes import generic
class RevisionModelMixin(models.Model):
class Meta:
abstract = True
_has_revision_support = True
revision = models.PositiveIntegerField(default=0,
db_index=True, editable=False)
- versions = generic.GenericRelation('reversion.Version')
-
def save(self, *args, **kwargs):
self.revision += 1
super(RevisionModelMixin, self).save(*args, **kwargs) |
2a71b48fb3ff2ec720ace74e30a83102c31863dc | labonneboite/common/email_util.py | labonneboite/common/email_util.py |
import json
import logging
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
response = self.mandrill.send_email(
subject=self.subject,
to=[{'email': to_email}],
html=html,
from_email=from_email)
content = json.loads(response.content.decode())
if content[0]["status"] != "sent":
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
return response
|
import json
import logging
from urllib.error import HTTPError
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
try:
response = self.mandrill.send_email(
subject=self.subject,
to=[{'email': to_email}],
html=html,
from_email=from_email)
content = json.loads(response.content.decode())
if content[0]["status"] != "sent":
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
except HTTPError:
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
return response
| Handle HttpError when sending email | Handle HttpError when sending email
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite |
import json
import logging
+ from urllib.error import HTTPError
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
+
+ try:
- response = self.mandrill.send_email(
+ response = self.mandrill.send_email(
- subject=self.subject,
+ subject=self.subject,
- to=[{'email': to_email}],
+ to=[{'email': to_email}],
- html=html,
+ html=html,
- from_email=from_email)
+ from_email=from_email)
- content = json.loads(response.content.decode())
+ content = json.loads(response.content.decode())
- if content[0]["status"] != "sent":
+ if content[0]["status"] != "sent":
+ raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
+ except HTTPError:
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
+
return response
| Handle HttpError when sending email | ## Code Before:
import json
import logging
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
response = self.mandrill.send_email(
subject=self.subject,
to=[{'email': to_email}],
html=html,
from_email=from_email)
content = json.loads(response.content.decode())
if content[0]["status"] != "sent":
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
return response
## Instruction:
Handle HttpError when sending email
## Code After:
import json
import logging
from urllib.error import HTTPError
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
try:
response = self.mandrill.send_email(
subject=self.subject,
to=[{'email': to_email}],
html=html,
from_email=from_email)
content = json.loads(response.content.decode())
if content[0]["status"] != "sent":
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
except HTTPError:
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
return response
|
import json
import logging
+ from urllib.error import HTTPError
from labonneboite.conf import settings
logger = logging.getLogger('main')
class MailNoSendException(Exception):
pass
class EmailClient(object):
to = settings.FORM_EMAIL
from_email = settings.ADMIN_EMAIL
subject = 'nouveau message entreprise LBB'
class MandrillClient(EmailClient):
def __init__(self, mandrill):
self.mandrill = mandrill
def send(self, html):
from_email = self.from_email
to_email = self.to
+
+ try:
- response = self.mandrill.send_email(
+ response = self.mandrill.send_email(
? ++++
- subject=self.subject,
+ subject=self.subject,
? ++++
- to=[{'email': to_email}],
+ to=[{'email': to_email}],
? ++++
- html=html,
+ html=html,
? ++++
- from_email=from_email)
+ from_email=from_email)
? ++++
- content = json.loads(response.content.decode())
+ content = json.loads(response.content.decode())
? ++++
- if content[0]["status"] != "sent":
+ if content[0]["status"] != "sent":
? ++++
+ raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
+ except HTTPError:
raise MailNoSendException("email was not sent from %s to %s" % (from_email, to_email))
+
return response |
e195ab1f4e83febf7b3b7dff7e1b63b578986167 | tests.py | tests.py | from unittest import TestCase
from markdown import Markdown
from mdx_attr_cols import AttrColTreeProcessor
class TestAttrColTreeProcessor(TestCase):
def mk_processor(self, **conf):
md = Markdown()
return AttrColTreeProcessor(md, conf)
def test_config_defaults(self):
p = self.mk_processor()
self.assertEqual(p.columns, 12)
self.assertEqual(p.attr, 'cols')
self.assertEqual(p.tags, set(['section']))
def test_config_overrides(self):
p = self.mk_processor(
columns=16,
attr='columns',
tags=['section', 'div'],
)
self.assertEqual(p.columns, 16)
self.assertEqual(p.attr, 'columns')
self.assertEqual(p.tags, set(['section', 'div']))
| from unittest import TestCase
import xmltodict
from markdown import Markdown
from markdown.util import etree
from mdx_attr_cols import AttrColTreeProcessor
class XmlTestCaseMixin(object):
def mk_doc(self, s):
return etree.fromstring(
"<div>" + s.strip() + "</div>")
def assertXmlEqual(self, a, b):
self.assertEqual(
xmltodict.parse(etree.tostring(a)),
xmltodict.parse(etree.tostring(b)))
class TestAttrColTreeProcessor(XmlTestCaseMixin, TestCase):
def mk_processor(self, **conf):
md = Markdown()
return AttrColTreeProcessor(md, conf)
def test_config_defaults(self):
p = self.mk_processor()
self.assertEqual(p.columns, 12)
self.assertEqual(p.attr, 'cols')
self.assertEqual(p.tags, set(['section']))
def test_config_overrides(self):
p = self.mk_processor(
columns=16,
attr='columns',
tags=['section', 'div'],
)
self.assertEqual(p.columns, 16)
self.assertEqual(p.attr, 'columns')
self.assertEqual(p.tags, set(['section', 'div']))
def test_simple_rows(self):
root = self.mk_doc("""
<section cols='4'>Foo</section>
<section cols='6'>Bar</section>
<section cols='2'>Beep</section>
""")
p = self.mk_processor()
new_root = p.run(root)
self.assertXmlEqual(new_root, self.mk_doc("""
<div class="row"><div class="col-md-4"><section>Foo</section>
</div><div class="col-md-6"><section>Bar</section>
</div><div class="col-md-2"><section>Beep</section>
</div></div>
"""))
| Check handling of simple rows. | Check handling of simple rows.
| Python | isc | CTPUG/mdx_attr_cols | from unittest import TestCase
+ import xmltodict
+
from markdown import Markdown
+ from markdown.util import etree
from mdx_attr_cols import AttrColTreeProcessor
+ class XmlTestCaseMixin(object):
+ def mk_doc(self, s):
+ return etree.fromstring(
+ "<div>" + s.strip() + "</div>")
+
+ def assertXmlEqual(self, a, b):
+ self.assertEqual(
+ xmltodict.parse(etree.tostring(a)),
+ xmltodict.parse(etree.tostring(b)))
+
+
- class TestAttrColTreeProcessor(TestCase):
+ class TestAttrColTreeProcessor(XmlTestCaseMixin, TestCase):
def mk_processor(self, **conf):
md = Markdown()
return AttrColTreeProcessor(md, conf)
def test_config_defaults(self):
p = self.mk_processor()
self.assertEqual(p.columns, 12)
self.assertEqual(p.attr, 'cols')
self.assertEqual(p.tags, set(['section']))
def test_config_overrides(self):
p = self.mk_processor(
columns=16,
attr='columns',
tags=['section', 'div'],
)
self.assertEqual(p.columns, 16)
self.assertEqual(p.attr, 'columns')
self.assertEqual(p.tags, set(['section', 'div']))
+ def test_simple_rows(self):
+ root = self.mk_doc("""
+ <section cols='4'>Foo</section>
+ <section cols='6'>Bar</section>
+ <section cols='2'>Beep</section>
+ """)
+ p = self.mk_processor()
+ new_root = p.run(root)
+ self.assertXmlEqual(new_root, self.mk_doc("""
+ <div class="row"><div class="col-md-4"><section>Foo</section>
+ </div><div class="col-md-6"><section>Bar</section>
+ </div><div class="col-md-2"><section>Beep</section>
+ </div></div>
+ """))
+ | Check handling of simple rows. | ## Code Before:
from unittest import TestCase
from markdown import Markdown
from mdx_attr_cols import AttrColTreeProcessor
class TestAttrColTreeProcessor(TestCase):
def mk_processor(self, **conf):
md = Markdown()
return AttrColTreeProcessor(md, conf)
def test_config_defaults(self):
p = self.mk_processor()
self.assertEqual(p.columns, 12)
self.assertEqual(p.attr, 'cols')
self.assertEqual(p.tags, set(['section']))
def test_config_overrides(self):
p = self.mk_processor(
columns=16,
attr='columns',
tags=['section', 'div'],
)
self.assertEqual(p.columns, 16)
self.assertEqual(p.attr, 'columns')
self.assertEqual(p.tags, set(['section', 'div']))
## Instruction:
Check handling of simple rows.
## Code After:
from unittest import TestCase
import xmltodict
from markdown import Markdown
from markdown.util import etree
from mdx_attr_cols import AttrColTreeProcessor
class XmlTestCaseMixin(object):
def mk_doc(self, s):
return etree.fromstring(
"<div>" + s.strip() + "</div>")
def assertXmlEqual(self, a, b):
self.assertEqual(
xmltodict.parse(etree.tostring(a)),
xmltodict.parse(etree.tostring(b)))
class TestAttrColTreeProcessor(XmlTestCaseMixin, TestCase):
def mk_processor(self, **conf):
md = Markdown()
return AttrColTreeProcessor(md, conf)
def test_config_defaults(self):
p = self.mk_processor()
self.assertEqual(p.columns, 12)
self.assertEqual(p.attr, 'cols')
self.assertEqual(p.tags, set(['section']))
def test_config_overrides(self):
p = self.mk_processor(
columns=16,
attr='columns',
tags=['section', 'div'],
)
self.assertEqual(p.columns, 16)
self.assertEqual(p.attr, 'columns')
self.assertEqual(p.tags, set(['section', 'div']))
def test_simple_rows(self):
root = self.mk_doc("""
<section cols='4'>Foo</section>
<section cols='6'>Bar</section>
<section cols='2'>Beep</section>
""")
p = self.mk_processor()
new_root = p.run(root)
self.assertXmlEqual(new_root, self.mk_doc("""
<div class="row"><div class="col-md-4"><section>Foo</section>
</div><div class="col-md-6"><section>Bar</section>
</div><div class="col-md-2"><section>Beep</section>
</div></div>
"""))
| from unittest import TestCase
+ import xmltodict
+
from markdown import Markdown
+ from markdown.util import etree
from mdx_attr_cols import AttrColTreeProcessor
+ class XmlTestCaseMixin(object):
+ def mk_doc(self, s):
+ return etree.fromstring(
+ "<div>" + s.strip() + "</div>")
+
+ def assertXmlEqual(self, a, b):
+ self.assertEqual(
+ xmltodict.parse(etree.tostring(a)),
+ xmltodict.parse(etree.tostring(b)))
+
+
- class TestAttrColTreeProcessor(TestCase):
+ class TestAttrColTreeProcessor(XmlTestCaseMixin, TestCase):
? ++++++++++++++++++
def mk_processor(self, **conf):
md = Markdown()
return AttrColTreeProcessor(md, conf)
def test_config_defaults(self):
p = self.mk_processor()
self.assertEqual(p.columns, 12)
self.assertEqual(p.attr, 'cols')
self.assertEqual(p.tags, set(['section']))
def test_config_overrides(self):
p = self.mk_processor(
columns=16,
attr='columns',
tags=['section', 'div'],
)
self.assertEqual(p.columns, 16)
self.assertEqual(p.attr, 'columns')
self.assertEqual(p.tags, set(['section', 'div']))
+
+ def test_simple_rows(self):
+ root = self.mk_doc("""
+ <section cols='4'>Foo</section>
+ <section cols='6'>Bar</section>
+ <section cols='2'>Beep</section>
+ """)
+ p = self.mk_processor()
+ new_root = p.run(root)
+ self.assertXmlEqual(new_root, self.mk_doc("""
+ <div class="row"><div class="col-md-4"><section>Foo</section>
+ </div><div class="col-md-6"><section>Bar</section>
+ </div><div class="col-md-2"><section>Beep</section>
+ </div></div>
+ """)) |
98acdc9262cfa8c5da092e0c3b1264afdcbde66a | locations/spiders/speedway.py | locations/spiders/speedway.py | import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "superamerica"
allowed_domains = ["superamerica.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
yield scrapy.Request(
'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
callback=self.parse_search,
method='POST',
body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
headers={
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
}
)
def parse_search(self, response):
data = json.loads(response.body_as_unicode())
for store in data:
properties = {
'addr:full': store['address'],
'addr:city': store['city'],
'addr:state': store['state'],
'addr:postcode': store['zip'],
'phone': store['phoneNumber'],
'ref': store['costCenterId'],
}
lon_lat = [
store['longitude'],
store['latitude'],
]
yield GeojsonPointItem(
properties=properties,
lon_lat=lon_lat,
)
| import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "speedway"
allowed_domains = ["www.speedway.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
yield scrapy.Request(
'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
callback=self.parse_search,
method='POST',
body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
headers={
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
}
)
def parse_search(self, response):
data = json.loads(response.body_as_unicode())
for store in data:
properties = {
'addr:full': store['address'],
'addr:city': store['city'],
'addr:state': store['state'],
'addr:postcode': store['zip'],
'phone': store['phoneNumber'],
'ref': store['costCenterId'],
}
lon_lat = [
store['longitude'],
store['latitude'],
]
yield GeojsonPointItem(
properties=properties,
lon_lat=lon_lat,
)
| Correct the name of the spider | Correct the name of the spider
| Python | mit | iandees/all-the-places,iandees/all-the-places,iandees/all-the-places | import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
- name = "superamerica"
+ name = "speedway"
- allowed_domains = ["superamerica.com"]
+ allowed_domains = ["www.speedway.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
yield scrapy.Request(
'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
callback=self.parse_search,
method='POST',
body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
headers={
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
}
)
def parse_search(self, response):
data = json.loads(response.body_as_unicode())
for store in data:
properties = {
'addr:full': store['address'],
'addr:city': store['city'],
'addr:state': store['state'],
'addr:postcode': store['zip'],
'phone': store['phoneNumber'],
'ref': store['costCenterId'],
}
lon_lat = [
store['longitude'],
store['latitude'],
]
yield GeojsonPointItem(
properties=properties,
lon_lat=lon_lat,
)
| Correct the name of the spider | ## Code Before:
import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "superamerica"
allowed_domains = ["superamerica.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
yield scrapy.Request(
'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
callback=self.parse_search,
method='POST',
body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
headers={
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
}
)
def parse_search(self, response):
data = json.loads(response.body_as_unicode())
for store in data:
properties = {
'addr:full': store['address'],
'addr:city': store['city'],
'addr:state': store['state'],
'addr:postcode': store['zip'],
'phone': store['phoneNumber'],
'ref': store['costCenterId'],
}
lon_lat = [
store['longitude'],
store['latitude'],
]
yield GeojsonPointItem(
properties=properties,
lon_lat=lon_lat,
)
## Instruction:
Correct the name of the spider
## Code After:
import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
name = "speedway"
allowed_domains = ["www.speedway.com"]
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
yield scrapy.Request(
'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
callback=self.parse_search,
method='POST',
body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
headers={
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
}
)
def parse_search(self, response):
data = json.loads(response.body_as_unicode())
for store in data:
properties = {
'addr:full': store['address'],
'addr:city': store['city'],
'addr:state': store['state'],
'addr:postcode': store['zip'],
'phone': store['phoneNumber'],
'ref': store['costCenterId'],
}
lon_lat = [
store['longitude'],
store['latitude'],
]
yield GeojsonPointItem(
properties=properties,
lon_lat=lon_lat,
)
| import scrapy
import json
from locations.items import GeojsonPointItem
class SuperAmericaSpider(scrapy.Spider):
- name = "superamerica"
+ name = "speedway"
- allowed_domains = ["superamerica.com"]
? - ^ ^^^^^^
+ allowed_domains = ["www.speedway.com"]
? ++++ ^^^ ^
start_urls = (
'https://www.speedway.com/GasPriceSearch',
)
def parse(self, response):
yield scrapy.Request(
'https://www.speedway.com/Services/StoreService.svc/getstoresbyproximity',
callback=self.parse_search,
method='POST',
body='{"latitude":45.0,"longitude":-90.0,"radius":-1,"limit":0}',
headers={
'Content-Type': 'application/json;charset=UTF-8',
'Accept': 'application/json',
}
)
def parse_search(self, response):
data = json.loads(response.body_as_unicode())
for store in data:
properties = {
'addr:full': store['address'],
'addr:city': store['city'],
'addr:state': store['state'],
'addr:postcode': store['zip'],
'phone': store['phoneNumber'],
'ref': store['costCenterId'],
}
lon_lat = [
store['longitude'],
store['latitude'],
]
yield GeojsonPointItem(
properties=properties,
lon_lat=lon_lat,
) |
89929acbb2ee3c5617758966d8916139726d7b74 | app/state.py | app/state.py | import multiprocessing
import unicornhathd as unicornhat
import importlib
import sys
import os
import app.programs.hd
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self._process = None
def start_program(self, name, params={}):
try:
program = getattr(app.programs.hd, name)
except AttributeError:
raise ProgramNotFound(name)
self.stop_program()
if params.get("brightness"):
unicornhat.brightness(float(params["brightness"]))
if params.get("rotation"):
unicornhat.rotation(int(params["rotation"]))
self._process = multiprocessing.Process(target=program.run, args=(params,))
self._process.start()
def stop_program(self):
if self._process is not None:
self._process.terminate()
unicornhat.show()
class ProgramNotFound(Exception):
pass | import multiprocessing
import unicornhathd as unicornhat
import importlib
import sys
import os
import app.programs.hd
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self._process = None
def start_program(self, name, params={}):
try:
program = getattr(app.programs.hd, name)
except AttributeError:
raise ProgramNotFound(name)
self.stop_program()
if params.get("brightness") is not None:
unicornhat.brightness(float(params["brightness"]))
if params.get("rotation") is not None:
unicornhat.rotation(int(params["rotation"]))
self._process = multiprocessing.Process(target=program.run, args=(params,))
self._process.start()
def stop_program(self):
if self._process is not None:
self._process.terminate()
unicornhat.show()
class ProgramNotFound(Exception):
pass | Fix setting rotation to 0 | Fix setting rotation to 0
| Python | mit | njbbaer/unicorn-remote,njbbaer/unicorn-remote,njbbaer/unicorn-remote | import multiprocessing
import unicornhathd as unicornhat
import importlib
import sys
import os
import app.programs.hd
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self._process = None
def start_program(self, name, params={}):
try:
program = getattr(app.programs.hd, name)
except AttributeError:
raise ProgramNotFound(name)
self.stop_program()
- if params.get("brightness"):
+ if params.get("brightness") is not None:
unicornhat.brightness(float(params["brightness"]))
- if params.get("rotation"):
+ if params.get("rotation") is not None:
unicornhat.rotation(int(params["rotation"]))
self._process = multiprocessing.Process(target=program.run, args=(params,))
self._process.start()
def stop_program(self):
if self._process is not None:
self._process.terminate()
unicornhat.show()
class ProgramNotFound(Exception):
pass | Fix setting rotation to 0 | ## Code Before:
import multiprocessing
import unicornhathd as unicornhat
import importlib
import sys
import os
import app.programs.hd
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self._process = None
def start_program(self, name, params={}):
try:
program = getattr(app.programs.hd, name)
except AttributeError:
raise ProgramNotFound(name)
self.stop_program()
if params.get("brightness"):
unicornhat.brightness(float(params["brightness"]))
if params.get("rotation"):
unicornhat.rotation(int(params["rotation"]))
self._process = multiprocessing.Process(target=program.run, args=(params,))
self._process.start()
def stop_program(self):
if self._process is not None:
self._process.terminate()
unicornhat.show()
class ProgramNotFound(Exception):
pass
## Instruction:
Fix setting rotation to 0
## Code After:
import multiprocessing
import unicornhathd as unicornhat
import importlib
import sys
import os
import app.programs.hd
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self._process = None
def start_program(self, name, params={}):
try:
program = getattr(app.programs.hd, name)
except AttributeError:
raise ProgramNotFound(name)
self.stop_program()
if params.get("brightness") is not None:
unicornhat.brightness(float(params["brightness"]))
if params.get("rotation") is not None:
unicornhat.rotation(int(params["rotation"]))
self._process = multiprocessing.Process(target=program.run, args=(params,))
self._process.start()
def stop_program(self):
if self._process is not None:
self._process.terminate()
unicornhat.show()
class ProgramNotFound(Exception):
pass | import multiprocessing
import unicornhathd as unicornhat
import importlib
import sys
import os
import app.programs.hd
class State:
''' Handles the Unicorn HAT state'''
def __init__(self):
self._process = None
def start_program(self, name, params={}):
try:
program = getattr(app.programs.hd, name)
except AttributeError:
raise ProgramNotFound(name)
self.stop_program()
- if params.get("brightness"):
+ if params.get("brightness") is not None:
? ++++++++++++
unicornhat.brightness(float(params["brightness"]))
- if params.get("rotation"):
+ if params.get("rotation") is not None:
? ++++++++++++
unicornhat.rotation(int(params["rotation"]))
self._process = multiprocessing.Process(target=program.run, args=(params,))
self._process.start()
def stop_program(self):
if self._process is not None:
self._process.terminate()
unicornhat.show()
class ProgramNotFound(Exception):
pass |
7eadc9e514b1311409356f4c6c40ef8cdb2de809 | manager/__init__.py | manager/__init__.py | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
# Load Blueprints
from manager.core import core
from manager.dns import dns
app.register_blueprint(core)
app.register_blueprint(dns, url_prefix="/dns")
# Configure flask-login
login_manager.login_view = "core.login"
# Asset Management
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
output='css_all.css'
)
)
| import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
# Load Blueprints
from manager.core import core
from manager.dns import dns
app.register_blueprint(core)
app.register_blueprint(dns, url_prefix="/dns")
# Configure flask-login
login_manager.login_view = "core.login"
# Asset Management
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'fontawesome/css/font-awesome.min.css',
'admin-lte/dist/css/AdminLTE.css',
'admin-lte/dist/css/skins/skin-black.min.css',
output='css_all.css'
)
)
| Add new stuff to the css bundle | Add new stuff to the css bundle
| Python | mit | hreeder/ignition,hreeder/ignition,hreeder/ignition | import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
# Load Blueprints
from manager.core import core
from manager.dns import dns
app.register_blueprint(core)
app.register_blueprint(dns, url_prefix="/dns")
# Configure flask-login
login_manager.login_view = "core.login"
# Asset Management
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
+ 'fontawesome/css/font-awesome.min.css',
+ 'admin-lte/dist/css/AdminLTE.css',
+ 'admin-lte/dist/css/skins/skin-black.min.css',
output='css_all.css'
)
)
| Add new stuff to the css bundle | ## Code Before:
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
# Load Blueprints
from manager.core import core
from manager.dns import dns
app.register_blueprint(core)
app.register_blueprint(dns, url_prefix="/dns")
# Configure flask-login
login_manager.login_view = "core.login"
# Asset Management
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
output='css_all.css'
)
)
## Instruction:
Add new stuff to the css bundle
## Code After:
import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
# Load Blueprints
from manager.core import core
from manager.dns import dns
app.register_blueprint(core)
app.register_blueprint(dns, url_prefix="/dns")
# Configure flask-login
login_manager.login_view = "core.login"
# Asset Management
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
'fontawesome/css/font-awesome.min.css',
'admin-lte/dist/css/AdminLTE.css',
'admin-lte/dist/css/skins/skin-black.min.css',
output='css_all.css'
)
)
| import os
from flask import Flask
from flask.ext.assets import Bundle, Environment
from flask.ext.bcrypt import Bcrypt
from flask.ext.login import LoginManager, current_user
from flask.ext.migrate import Migrate
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
# Load the app config
app.config.from_object("config.Config")
assets = Environment(app)
bcrypt = Bcrypt(app)
db = SQLAlchemy(app)
login_manager = LoginManager(app)
migrate = Migrate(app, db)
# Load Blueprints
from manager.core import core
from manager.dns import dns
app.register_blueprint(core)
app.register_blueprint(dns, url_prefix="/dns")
# Configure flask-login
login_manager.login_view = "core.login"
# Asset Management
assets.load_path = [
os.path.join(os.path.dirname(__file__), 'static'),
os.path.join(os.path.dirname(__file__), 'static', 'bower')
]
assets.register(
'js_all',
Bundle(
'jquery/dist/jquery.min.js',
'bootstrap/dist/js/bootstrap.min.js',
output='js_all.js'
)
)
assets.register(
'css_all',
Bundle(
'bootstrap/dist/css/bootstrap.css',
+ 'fontawesome/css/font-awesome.min.css',
+ 'admin-lte/dist/css/AdminLTE.css',
+ 'admin-lte/dist/css/skins/skin-black.min.css',
output='css_all.css'
)
) |
e665154e1b522feac8cd46c39ba523bc7197afab | annoying/tests/urls.py | annoying/tests/urls.py | """URLs for django-annoying's tests"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^ajax-request/$', views.ajax_request_view),
url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
]
| """URLs for django-annoying's tests"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
import django
from distutils.version import StrictVersion
django_version = django.get_version()
# Use old URL Conf settings for Django <= 1.8.
if StrictVersion(django_version) < StrictVersion('1.8.0'):
from django.conf.urls import patterns
urlpatterns = patterns('',
(r'^ajax-request/$', views.ajax_request_view),
(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
)
else:
urlpatterns = [
url(r'^ajax-request/$', views.ajax_request_view),
url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
]
| Use old URL Conf settings for Django <= 1.8. | Use old URL Conf settings for Django <= 1.8.
| Python | bsd-3-clause | kabakchey/django-annoying,skorokithakis/django-annoying,YPCrumble/django-annoying,kabakchey/django-annoying,skorokithakis/django-annoying | """URLs for django-annoying's tests"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
+ import django
+ from distutils.version import StrictVersion
+ django_version = django.get_version()
- urlpatterns = [
- url(r'^ajax-request/$', views.ajax_request_view),
- url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
- url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
- url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
- url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
- ]
+ # Use old URL Conf settings for Django <= 1.8.
+ if StrictVersion(django_version) < StrictVersion('1.8.0'):
+ from django.conf.urls import patterns
+ urlpatterns = patterns('',
+ (r'^ajax-request/$', views.ajax_request_view),
+ (r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
+ (r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
+ (r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
+ (r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
+ )
+ else:
+ urlpatterns = [
+ url(r'^ajax-request/$', views.ajax_request_view),
+ url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
+ url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
+ url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
+ url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
+ ]
+ | Use old URL Conf settings for Django <= 1.8. | ## Code Before:
"""URLs for django-annoying's tests"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^ajax-request/$', views.ajax_request_view),
url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
]
## Instruction:
Use old URL Conf settings for Django <= 1.8.
## Code After:
"""URLs for django-annoying's tests"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
import django
from distutils.version import StrictVersion
django_version = django.get_version()
# Use old URL Conf settings for Django <= 1.8.
if StrictVersion(django_version) < StrictVersion('1.8.0'):
from django.conf.urls import patterns
urlpatterns = patterns('',
(r'^ajax-request/$', views.ajax_request_view),
(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
)
else:
urlpatterns = [
url(r'^ajax-request/$', views.ajax_request_view),
url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
]
| """URLs for django-annoying's tests"""
from __future__ import absolute_import
from django.conf.urls import url
from . import views
+ import django
+ from distutils.version import StrictVersion
+ django_version = django.get_version()
+
+ # Use old URL Conf settings for Django <= 1.8.
+ if StrictVersion(django_version) < StrictVersion('1.8.0'):
+ from django.conf.urls import patterns
+ urlpatterns = patterns('',
+ (r'^ajax-request/$', views.ajax_request_view),
+ (r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
+ (r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
+ (r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
+ (r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
+ )
+ else:
- urlpatterns = [
+ urlpatterns = [
? ++++
- url(r'^ajax-request/$', views.ajax_request_view),
+ url(r'^ajax-request/$', views.ajax_request_view),
? ++++
- url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
+ url(r'^ajax-request-httpresponse/$', views.ajax_request_httpresponse_view),
? ++++
- url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
+ url(r'^render-to-content-type-kwarg/$', views.render_to_content_type_kwarg),
? ++++
- url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
+ url(r'^render-to-mimetype-kwarg/$', views.render_to_mimetype_kwarg),
? ++++
- url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
+ url(r'^render-to-content-type-positional/$', views.render_to_content_type_positional),
? ++++
- ]
+ ] |
5682c2a311dbaf94f0b7876b10cabbc90eb88628 | hooks/post_gen_project.py | hooks/post_gen_project.py |
from __future__ import print_function
import os
from subprocess import call
# Get the root project directory
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def remove_version_file():
"""Removes the _version file if versionner is going to be used."""
file_name = os.path.join(PROJECT_DIRECTORY,
'{{ cookiecutter.project_name }}/_version.py')
remove_file(file_name)
def install_versioneer():
"""Start versioneer in the repository, this will create
versioneer.py and _version.py."""
call(['versioneer', 'install'])
# 1. Removes _version file and run versionner install if use_versionner == y
if '{{ cookiecutter.use_versioneer }}'.lower() == 'y':
remove_version_file()
try:
install_versioneer()
except Exception:
print(
"versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
|
from __future__ import print_function
import os
from subprocess import call
# Get the root project directory
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def remove_version_file():
"""Removes the _version file if versionner is going to be used."""
file_name = os.path.join(PROJECT_DIRECTORY,
'{{ cookiecutter.project_name }}/_version.py')
remove_file(file_name)
def install_versioneer():
"""Start versioneer in the repository, this will create
versioneer.py and _version.py."""
try:
call(['versioneer', 'install'])
except Exception:
print(
"versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
def init_git():
"""Start git repository"""
try:
call(['git', 'init'])
except Exception:
print("git isn't avalaible, please install git and run:\n $ git init")
# 1. Removes _version file and run versionner install if use_versionner == y
if '{{ cookiecutter.use_versioneer }}'.lower() == 'y':
remove_version_file()
init_git()
install_versioneer()
| Add git init to post hooks, and move error handling to functions | Add git init to post hooks, and move error handling to functions
| Python | mit | rlaverde/spyder-plugin-cookiecutter |
from __future__ import print_function
import os
from subprocess import call
# Get the root project directory
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def remove_version_file():
"""Removes the _version file if versionner is going to be used."""
file_name = os.path.join(PROJECT_DIRECTORY,
'{{ cookiecutter.project_name }}/_version.py')
remove_file(file_name)
def install_versioneer():
"""Start versioneer in the repository, this will create
versioneer.py and _version.py."""
+ try:
- call(['versioneer', 'install'])
+ call(['versioneer', 'install'])
+ except Exception:
+ print(
+ "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
+
+ def init_git():
+ """Start git repository"""
+ try:
+ call(['git', 'init'])
+ except Exception:
+ print("git isn't avalaible, please install git and run:\n $ git init")
+
# 1. Removes _version file and run versionner install if use_versionner == y
if '{{ cookiecutter.use_versioneer }}'.lower() == 'y':
remove_version_file()
- try:
- install_versioneer()
- except Exception:
- print(
- "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
+ init_git()
+ install_versioneer()
+ | Add git init to post hooks, and move error handling to functions | ## Code Before:
from __future__ import print_function
import os
from subprocess import call
# Get the root project directory
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def remove_version_file():
"""Removes the _version file if versionner is going to be used."""
file_name = os.path.join(PROJECT_DIRECTORY,
'{{ cookiecutter.project_name }}/_version.py')
remove_file(file_name)
def install_versioneer():
"""Start versioneer in the repository, this will create
versioneer.py and _version.py."""
call(['versioneer', 'install'])
# 1. Removes _version file and run versionner install if use_versionner == y
if '{{ cookiecutter.use_versioneer }}'.lower() == 'y':
remove_version_file()
try:
install_versioneer()
except Exception:
print(
"versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
## Instruction:
Add git init to post hooks, and move error handling to functions
## Code After:
from __future__ import print_function
import os
from subprocess import call
# Get the root project directory
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def remove_version_file():
"""Removes the _version file if versionner is going to be used."""
file_name = os.path.join(PROJECT_DIRECTORY,
'{{ cookiecutter.project_name }}/_version.py')
remove_file(file_name)
def install_versioneer():
"""Start versioneer in the repository, this will create
versioneer.py and _version.py."""
try:
call(['versioneer', 'install'])
except Exception:
print(
"versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
def init_git():
"""Start git repository"""
try:
call(['git', 'init'])
except Exception:
print("git isn't avalaible, please install git and run:\n $ git init")
# 1. Removes _version file and run versionner install if use_versionner == y
if '{{ cookiecutter.use_versioneer }}'.lower() == 'y':
remove_version_file()
init_git()
install_versioneer()
|
from __future__ import print_function
import os
from subprocess import call
# Get the root project directory
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_file(file_name):
if os.path.exists(file_name):
os.remove(file_name)
def remove_version_file():
"""Removes the _version file if versionner is going to be used."""
file_name = os.path.join(PROJECT_DIRECTORY,
'{{ cookiecutter.project_name }}/_version.py')
remove_file(file_name)
def install_versioneer():
"""Start versioneer in the repository, this will create
versioneer.py and _version.py."""
+ try:
- call(['versioneer', 'install'])
+ call(['versioneer', 'install'])
? ++++
+ except Exception:
+ print(
+ "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install")
+
+ def init_git():
+ """Start git repository"""
+ try:
+ call(['git', 'init'])
+ except Exception:
+ print("git isn't avalaible, please install git and run:\n $ git init")
+
# 1. Removes _version file and run versionner install if use_versionner == y
if '{{ cookiecutter.use_versioneer }}'.lower() == 'y':
remove_version_file()
- try:
+
+ init_git()
- install_versioneer()
? ----
+ install_versioneer()
- except Exception:
- print(
- "versioneer isn't avalaible, please install versioneer and run:\n $ versioneer install") |
cbdcdf16285823a8e13a68c8e86d6957aa7aa6d8 | kivy/tools/packaging/pyinstaller_hooks/pyi_rth_kivy.py | kivy/tools/packaging/pyinstaller_hooks/pyi_rth_kivy.py | import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
os.environ['GST_PLUGIN_PATH'] = '{};{}'.format(
sys._MEIPASS, os.path.join(sys._MEIPASS, 'gst-plugins'))
os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPASS, 'registry.bin')
sys.path += [os.path.join(root, '_libs')]
if sys.platform == 'darwin':
sitepackages = os.path.join(sys._MEIPASS, 'sitepackages')
sys.path += [sitepackages, os.path.join(sitepackages, 'gst-0.10')]
os.putenv('GST_REGISTRY_FORK', 'no')
| import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
os.environ['GST_PLUGIN_PATH'] = os.path.join(sys._MEIPASS, 'gst-plugins')
os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPASS, 'registry.bin')
sys.path += [os.path.join(root, '_libs')]
if sys.platform == 'darwin':
sitepackages = os.path.join(sys._MEIPASS, 'sitepackages')
sys.path += [sitepackages, os.path.join(sitepackages, 'gst-0.10')]
os.putenv('GST_REGISTRY_FORK', 'no')
| Fix GST_PLUGIN_PATH in runtime hook | Fix GST_PLUGIN_PATH in runtime hook
- Only include `gst-plugins`
- Also, semicolon was only correct on Windows
| Python | mit | inclement/kivy,inclement/kivy,kivy/kivy,kivy/kivy,akshayaurora/kivy,akshayaurora/kivy,kivy/kivy,matham/kivy,rnixx/kivy,matham/kivy,inclement/kivy,matham/kivy,matham/kivy,rnixx/kivy,akshayaurora/kivy,rnixx/kivy | import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
+ os.environ['GST_PLUGIN_PATH'] = os.path.join(sys._MEIPASS, 'gst-plugins')
- os.environ['GST_PLUGIN_PATH'] = '{};{}'.format(
- sys._MEIPASS, os.path.join(sys._MEIPASS, 'gst-plugins'))
os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPASS, 'registry.bin')
sys.path += [os.path.join(root, '_libs')]
if sys.platform == 'darwin':
sitepackages = os.path.join(sys._MEIPASS, 'sitepackages')
sys.path += [sitepackages, os.path.join(sitepackages, 'gst-0.10')]
os.putenv('GST_REGISTRY_FORK', 'no')
| Fix GST_PLUGIN_PATH in runtime hook | ## Code Before:
import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
os.environ['GST_PLUGIN_PATH'] = '{};{}'.format(
sys._MEIPASS, os.path.join(sys._MEIPASS, 'gst-plugins'))
os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPASS, 'registry.bin')
sys.path += [os.path.join(root, '_libs')]
if sys.platform == 'darwin':
sitepackages = os.path.join(sys._MEIPASS, 'sitepackages')
sys.path += [sitepackages, os.path.join(sitepackages, 'gst-0.10')]
os.putenv('GST_REGISTRY_FORK', 'no')
## Instruction:
Fix GST_PLUGIN_PATH in runtime hook
## Code After:
import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
os.environ['GST_PLUGIN_PATH'] = os.path.join(sys._MEIPASS, 'gst-plugins')
os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPASS, 'registry.bin')
sys.path += [os.path.join(root, '_libs')]
if sys.platform == 'darwin':
sitepackages = os.path.join(sys._MEIPASS, 'sitepackages')
sys.path += [sitepackages, os.path.join(sitepackages, 'gst-0.10')]
os.putenv('GST_REGISTRY_FORK', 'no')
| import os
import sys
root = os.path.join(sys._MEIPASS, 'kivy_install')
os.environ['KIVY_DATA_DIR'] = os.path.join(root, 'data')
os.environ['KIVY_MODULES_DIR'] = os.path.join(root, 'modules')
+ os.environ['GST_PLUGIN_PATH'] = os.path.join(sys._MEIPASS, 'gst-plugins')
- os.environ['GST_PLUGIN_PATH'] = '{};{}'.format(
- sys._MEIPASS, os.path.join(sys._MEIPASS, 'gst-plugins'))
os.environ['GST_REGISTRY'] = os.path.join(sys._MEIPASS, 'registry.bin')
sys.path += [os.path.join(root, '_libs')]
if sys.platform == 'darwin':
sitepackages = os.path.join(sys._MEIPASS, 'sitepackages')
sys.path += [sitepackages, os.path.join(sitepackages, 'gst-0.10')]
os.putenv('GST_REGISTRY_FORK', 'no') |
3e1f5adf1402d6e9ddd4ef6a08f4a667be950e1d | src/ansible/admin.py | src/ansible/admin.py | from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
| from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
admin.site.site_title = 'Ansible Admin'
admin.site.index_title = 'Admin Tool'
| Add ansible app site title | Add ansible app site title
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
+ admin.site.site_title = 'Ansible Admin'
+ admin.site.index_title = 'Admin Tool'
| Add ansible app site title | ## Code Before:
from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
## Instruction:
Add ansible app site title
## Code After:
from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
admin.site.site_title = 'Ansible Admin'
admin.site.index_title = 'Admin Tool'
| from django.contrib import admin
from .models import Playbook, Registry, Repository
admin.site.register(Playbook)
admin.site.register(Registry)
admin.site.register(Repository)
admin.site.site_header = 'Ansible Admin'
+ admin.site.site_title = 'Ansible Admin'
+ admin.site.index_title = 'Admin Tool' |
b494a5b2ed94c1def6fb8bbbab5df5612ef30aa7 | tests/test_api.py | tests/test_api.py | from bmi_tester.api import check_bmi
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write("input.yaml")
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
| import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write(os.linesep.join(["input.yaml", "data.dat"]))
touch_file("input.yaml")
touch_file("data.dat")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
| Test a manifest with multiple files. | Test a manifest with multiple files.
| Python | mit | csdms/bmi-tester | + import os
+
from bmi_tester.api import check_bmi
+
+
+ def touch_file(fname):
+ with open(fname, "w"):
+ pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
+ touch_file("input.yaml")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
+ touch_file("input.yaml")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
+ fp.write(os.linesep.join(["input.yaml", "data.dat"]))
- fp.write("input.yaml")
+ touch_file("input.yaml")
+ touch_file("data.dat")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
| Test a manifest with multiple files. | ## Code Before:
from bmi_tester.api import check_bmi
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write("input.yaml")
with open("input.yaml", "w"):
pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
## Instruction:
Test a manifest with multiple files.
## Code After:
import os
from bmi_tester.api import check_bmi
def touch_file(fname):
with open(fname, "w"):
pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
touch_file("input.yaml")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
fp.write(os.linesep.join(["input.yaml", "data.dat"]))
touch_file("input.yaml")
touch_file("data.dat")
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
)
| + import os
+
from bmi_tester.api import check_bmi
+
+
+ def touch_file(fname):
+ with open(fname, "w"):
+ pass
def test_bmi_check(tmpdir):
with tmpdir.as_cwd():
+ touch_file("input.yaml")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi", input_file="input.yaml", extra_args=["-vvv"]
)
== 0
)
def test_bmi_check_with_manifest_as_list(tmpdir):
with tmpdir.as_cwd():
+ touch_file("input.yaml")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest=["input.yaml"],
)
== 0
)
def test_bmi_check_with_manifest_as_string(tmpdir):
with tmpdir.as_cwd():
with open("manifest.txt", "w") as fp:
+ fp.write(os.linesep.join(["input.yaml", "data.dat"]))
- fp.write("input.yaml")
? ^^^^ ---- ^
+ touch_file("input.yaml")
? ^^^^^^ ^
+ touch_file("data.dat")
- with open("input.yaml", "w"):
- pass
assert (
check_bmi(
"bmi_tester.bmi:Bmi",
extra_args=["-vvv"],
input_file="input.yaml",
manifest="manifest.txt",
)
== 0
) |
394ed06411d3ca3ada66aab3bee796682895acc0 | cla_backend/apps/core/testing.py | cla_backend/apps/core/testing.py | from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION pgcrypto')
call_command('loaddata', 'initial_groups')
return ret
| from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS pgcrypto')
call_command('loaddata', 'initial_groups')
return ret
| Install pgcrypto PGSQL extension but only if it does not exist already (e.g. from template1) | Install pgcrypto PGSQL extension but only if it does not exist already (e.g. from template1)
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
- cursor.execute('CREATE EXTENSION pgcrypto')
+ cursor.execute('CREATE EXTENSION IF NOT EXISTS pgcrypto')
call_command('loaddata', 'initial_groups')
return ret
| Install pgcrypto PGSQL extension but only if it does not exist already (e.g. from template1) | ## Code Before:
from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION pgcrypto')
call_command('loaddata', 'initial_groups')
return ret
## Instruction:
Install pgcrypto PGSQL extension but only if it does not exist already (e.g. from template1)
## Code After:
from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
cursor.execute('CREATE EXTENSION IF NOT EXISTS pgcrypto')
call_command('loaddata', 'initial_groups')
return ret
| from django.core.management import call_command
from django.test.utils import get_runner
from django.conf import settings
from django.db import connections, DEFAULT_DB_ALIAS
# use jenkins runner if present otherwise the default django one
if 'django_jenkins' in settings.INSTALLED_APPS:
base_runner = 'django_jenkins.runner.CITestSuiteRunner'
else:
base_runner = 'django.test.runner.DiscoverRunner'
class CLADiscoverRunner(get_runner(settings, base_runner)):
"""
Overrides the default Runner and loads the initial_groups fixture.
This is because migrations are switched off during testing but
we do need `initial_groups` in order for the tests to pass.
"""
def setup_databases(self, **kwargs):
ret = super(CLADiscoverRunner, self).setup_databases(**kwargs)
connection = connections[DEFAULT_DB_ALIAS]
cursor = connection.cursor()
- cursor.execute('CREATE EXTENSION pgcrypto')
+ cursor.execute('CREATE EXTENSION IF NOT EXISTS pgcrypto')
? ++++++++++++++
call_command('loaddata', 'initial_groups')
return ret |
914e419cd753f6815b2aa308b49d7ed357b523d6 | muzicast/web/__init__.py | muzicast/web/__init__.py | import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
app.secret_key = os.urandom(24)
| import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
#from muzicast.web.music import artist, album, track
#app.register_module(artist, url_prefix='/artist')
#app.register_module(album, url_prefix='/album')
#app.register_module(track, url_prefix='/track')
from muzicast.web.main import main
app.register_module(main, url_prefix='/')
app.secret_key = os.urandom(24)
| Add handler modules as required | Add handler modules as required
| Python | mit | nikhilm/muzicast,nikhilm/muzicast | import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
+ #from muzicast.web.music import artist, album, track
+ #app.register_module(artist, url_prefix='/artist')
+ #app.register_module(album, url_prefix='/album')
+ #app.register_module(track, url_prefix='/track')
+
+ from muzicast.web.main import main
+ app.register_module(main, url_prefix='/')
+
app.secret_key = os.urandom(24)
| Add handler modules as required | ## Code Before:
import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
app.secret_key = os.urandom(24)
## Instruction:
Add handler modules as required
## Code After:
import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
#from muzicast.web.music import artist, album, track
#app.register_module(artist, url_prefix='/artist')
#app.register_module(album, url_prefix='/album')
#app.register_module(track, url_prefix='/track')
from muzicast.web.main import main
app.register_module(main, url_prefix='/')
app.secret_key = os.urandom(24)
| import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
+ #from muzicast.web.music import artist, album, track
+ #app.register_module(artist, url_prefix='/artist')
+ #app.register_module(album, url_prefix='/album')
+ #app.register_module(track, url_prefix='/track')
+
+ from muzicast.web.main import main
+ app.register_module(main, url_prefix='/')
+
app.secret_key = os.urandom(24) |
ec3a70e038efc565ce88294caf0e78d5efaa9a85 | djangocms_picture/cms_plugins.py | djangocms_picture/cms_plugins.py | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
def icon_src(self, instance):
# TODO - possibly use 'instance' and provide a thumbnail image
return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"
plugin_pool.register_plugin(PicturePlugin)
| from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
plugin_pool.register_plugin(PicturePlugin)
| Modify the picture plugin slightly | Modify the picture plugin slightly
| Python | mit | okfn/foundation,okfn/website,okfn/website,okfn/foundation,MjAbuz/foundation,MjAbuz/foundation,okfn/website,okfn/foundation,MjAbuz/foundation,okfn/foundation,okfn/website,MjAbuz/foundation | from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
- def icon_src(self, instance):
- # TODO - possibly use 'instance' and provide a thumbnail image
- return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"
plugin_pool.register_plugin(PicturePlugin)
| Modify the picture plugin slightly | ## Code Before:
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
def icon_src(self, instance):
# TODO - possibly use 'instance' and provide a thumbnail image
return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"
plugin_pool.register_plugin(PicturePlugin)
## Instruction:
Modify the picture plugin slightly
## Code After:
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
plugin_pool.register_plugin(PicturePlugin)
| from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import Picture
class PicturePlugin(CMSPluginBase):
model = Picture
name = _("Picture")
render_template = "cms/plugins/picture.html"
text_enabled = True
def render(self, context, instance, placeholder):
if instance.url:
link = instance.url
elif instance.page_link:
link = instance.page_link.get_absolute_url()
else:
link = ""
context.update({
'picture': instance,
'link': link,
'placeholder': placeholder
})
return context
- def icon_src(self, instance):
- # TODO - possibly use 'instance' and provide a thumbnail image
- return settings.STATIC_URL + u"cms/img/icons/plugins/image.png"
plugin_pool.register_plugin(PicturePlugin) |
ef43e04970151ec5bba9688f268b2f85b5debd3f | bfg9000/builtins/__init__.py | bfg9000/builtins/__init__.py | import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
return result
| import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
result['env'] = env
return result
| Make the Environment object available to build.bfg files | Make the Environment object available to build.bfg files
| Python | bsd-3-clause | jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000 | import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
+ result['env'] = env
return result
| Make the Environment object available to build.bfg files | ## Code Before:
import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
return result
## Instruction:
Make the Environment object available to build.bfg files
## Code After:
import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
result['env'] = env
return result
| import functools
import glob
import os
import pkgutil
_all_builtins = {}
_loaded_builtins = False
class Binder(object):
def __init__(self, fn):
self.fn = fn
def bind(self, build_inputs, env):
return functools.partial(self.fn, build_inputs, env)
def builtin(fn):
bound = Binder(fn)
_all_builtins[fn.__name__] = bound
return bound
def _load_builtins():
for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'):
loader.find_module(name).load_module(name)
def bind(build_inputs, env):
global _loaded_builtins
if not _loaded_builtins:
_load_builtins()
_loaded_builtins = True
result = {}
for k, v in _all_builtins.iteritems():
result[k] = v.bind(build_inputs, env)
+ result['env'] = env
return result |
b902c32237febd976ae899bea41195adc58920d0 | tests/context.py | tests/context.py | from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
@patch('invoke.context.run')
def honors_warn_state(self, run):
Context(run={'warn': True}).run('x')
run.assert_called_with('x', warn=True)
| from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
def _honors(self, kwarg, value):
with patch('invoke.context.run') as run:
Context(run={kwarg: value}).run('x')
run.assert_called_with('x', **{kwarg: value})
def honors_warn_state(self):
self._honors('warn', True)
def honors_hide_state(self):
self._honors('hide', 'both')
| Refactor + add test for run(hide) | Refactor + add test for run(hide)
| Python | bsd-2-clause | pyinvoke/invoke,mattrobenolt/invoke,pfmoore/invoke,tyewang/invoke,pyinvoke/invoke,frol/invoke,kejbaly2/invoke,mkusz/invoke,frol/invoke,mkusz/invoke,kejbaly2/invoke,pfmoore/invoke,singingwolfboy/invoke,sophacles/invoke,mattrobenolt/invoke | from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
+ def _honors(self, kwarg, value):
- @patch('invoke.context.run')
+ with patch('invoke.context.run') as run:
- def honors_warn_state(self, run):
- Context(run={'warn': True}).run('x')
+ Context(run={kwarg: value}).run('x')
- run.assert_called_with('x', warn=True)
+ run.assert_called_with('x', **{kwarg: value})
+ def honors_warn_state(self):
+ self._honors('warn', True)
+
+ def honors_hide_state(self):
+ self._honors('hide', 'both')
+ | Refactor + add test for run(hide) | ## Code Before:
from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
@patch('invoke.context.run')
def honors_warn_state(self, run):
Context(run={'warn': True}).run('x')
run.assert_called_with('x', warn=True)
## Instruction:
Refactor + add test for run(hide)
## Code After:
from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
def _honors(self, kwarg, value):
with patch('invoke.context.run') as run:
Context(run={kwarg: value}).run('x')
run.assert_called_with('x', **{kwarg: value})
def honors_warn_state(self):
self._honors('warn', True)
def honors_hide_state(self):
self._honors('hide', 'both')
| from spec import Spec
from mock import patch
from invoke.context import Context
class Context_(Spec):
class run_:
+ def _honors(self, kwarg, value):
- @patch('invoke.context.run')
? ^
+ with patch('invoke.context.run') as run:
? ^^^^^^^^^ ++++++++
+ Context(run={kwarg: value}).run('x')
+ run.assert_called_with('x', **{kwarg: value})
+
- def honors_warn_state(self, run):
? -----
+ def honors_warn_state(self):
- Context(run={'warn': True}).run('x')
- run.assert_called_with('x', warn=True)
+ self._honors('warn', True)
+
+ def honors_hide_state(self):
+ self._honors('hide', 'both') |
d546d6901859a5fee8a16ffea6df560ecbb1e280 | tests/unit_tests.py | tests/unit_tests.py |
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
float_list = self.of.get_oxy_floats()
print len(float_list)
self.assertNotEqual(len(float_list), 0)
if __name__ == '__main__':
unittest.main()
|
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
self.oga_floats = self.of.get_oxy_floats()
self.assertNotEqual(len(self.oga_floats), 0)
def _get_dac_urls(self):
# Testing with a float that has data
oga_floats = ['1900650']
for dac_url in self.of.get_dac_urls(oga_floats):
self.dac_url = dac_url
self.assertTrue(self.dac_url.startswith('http'))
break
def _get_profile_opendap_urls(self):
for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
self.profile_url = profile_url
break
def _get_profile_data(self):
d = self.of.get_profile_data(self.profile_url)
self.assertNotEqual(len(d), 0)
def test_read_data(self):
# Methods need to be called in order
self._get_dac_urls()
self._get_profile_opendap_urls()
self._get_profile_data()
if __name__ == '__main__':
unittest.main()
| Add tests for reading profile data | Add tests for reading profile data
| Python | mit | biofloat/biofloat,MBARIMike/biofloat,biofloat/biofloat,MBARIMike/biofloat,MBARIMike/oxyfloat,MBARIMike/oxyfloat |
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
- float_list = self.of.get_oxy_floats()
+ self.oga_floats = self.of.get_oxy_floats()
- print len(float_list)
- self.assertNotEqual(len(float_list), 0)
+ self.assertNotEqual(len(self.oga_floats), 0)
+ def _get_dac_urls(self):
+ # Testing with a float that has data
+ oga_floats = ['1900650']
+ for dac_url in self.of.get_dac_urls(oga_floats):
+ self.dac_url = dac_url
+ self.assertTrue(self.dac_url.startswith('http'))
+ break
+
+ def _get_profile_opendap_urls(self):
+ for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
+ self.profile_url = profile_url
+ break
+
+ def _get_profile_data(self):
+ d = self.of.get_profile_data(self.profile_url)
+ self.assertNotEqual(len(d), 0)
+
+ def test_read_data(self):
+ # Methods need to be called in order
+ self._get_dac_urls()
+ self._get_profile_opendap_urls()
+ self._get_profile_data()
if __name__ == '__main__':
unittest.main()
| Add tests for reading profile data | ## Code Before:
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
float_list = self.of.get_oxy_floats()
print len(float_list)
self.assertNotEqual(len(float_list), 0)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add tests for reading profile data
## Code After:
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
self.oga_floats = self.of.get_oxy_floats()
self.assertNotEqual(len(self.oga_floats), 0)
def _get_dac_urls(self):
# Testing with a float that has data
oga_floats = ['1900650']
for dac_url in self.of.get_dac_urls(oga_floats):
self.dac_url = dac_url
self.assertTrue(self.dac_url.startswith('http'))
break
def _get_profile_opendap_urls(self):
for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
self.profile_url = profile_url
break
def _get_profile_data(self):
d = self.of.get_profile_data(self.profile_url)
self.assertNotEqual(len(d), 0)
def test_read_data(self):
# Methods need to be called in order
self._get_dac_urls()
self._get_profile_opendap_urls()
self._get_profile_data()
if __name__ == '__main__':
unittest.main()
|
import os
import sys
import unittest
parentDir = os.path.join(os.path.dirname(__file__), "../")
sys.path.insert(0, parentDir)
from oxyfloat import OxyFloat
class DataTest(unittest.TestCase):
def setUp(self):
self.of = OxyFloat()
def test_get_oxyfloats(self):
- float_list = self.of.get_oxy_floats()
? --- -
+ self.oga_floats = self.of.get_oxy_floats()
? +++++++++
- print len(float_list)
- self.assertNotEqual(len(float_list), 0)
? --- -
+ self.assertNotEqual(len(self.oga_floats), 0)
? +++++++++
+ def _get_dac_urls(self):
+ # Testing with a float that has data
+ oga_floats = ['1900650']
+ for dac_url in self.of.get_dac_urls(oga_floats):
+ self.dac_url = dac_url
+ self.assertTrue(self.dac_url.startswith('http'))
+ break
+
+ def _get_profile_opendap_urls(self):
+ for profile_url in self.of.get_profile_opendap_urls(self.dac_url):
+ self.profile_url = profile_url
+ break
+
+ def _get_profile_data(self):
+ d = self.of.get_profile_data(self.profile_url)
+ self.assertNotEqual(len(d), 0)
+
+ def test_read_data(self):
+ # Methods need to be called in order
+ self._get_dac_urls()
+ self._get_profile_opendap_urls()
+ self._get_profile_data()
if __name__ == '__main__':
unittest.main() |
73c7161d4414a9259ee6123ee3d3540153f30b9e | purchase_edi_file/models/purchase_order_line.py | purchase_edi_file/models/purchase_order_line.py |
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
seller = product._select_seller(partner_id=partner)
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines
|
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
seller = product._select_seller(
partner_id=partner, quantity=line.product_uom_qty
)
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines
| Add qty when searching seller because even if not passed a verification is made by default in _select_seller | Add qty when searching seller because even if not passed a verification is made by default in _select_seller
| Python | agpl-3.0 | akretion/ak-odoo-incubator,akretion/ak-odoo-incubator,akretion/ak-odoo-incubator,akretion/ak-odoo-incubator |
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
- seller = product._select_seller(partner_id=partner)
+ seller = product._select_seller(
+ partner_id=partner, quantity=line.product_uom_qty
+ )
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines
| Add qty when searching seller because even if not passed a verification is made by default in _select_seller | ## Code Before:
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
seller = product._select_seller(partner_id=partner)
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines
## Instruction:
Add qty when searching seller because even if not passed a verification is made by default in _select_seller
## Code After:
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
seller = product._select_seller(
partner_id=partner, quantity=line.product_uom_qty
)
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines
|
from odoo import _, exceptions, models
class PurchaseOrderLine(models.Model):
_inherit = "purchase.order.line"
def _get_lines_by_profiles(self, partner):
profile_lines = {
key: self.env["purchase.order.line"]
for key in partner.edi_purchase_profile_ids
}
for line in self:
product = line.product_id
- seller = product._select_seller(partner_id=partner)
? -------------------
+ seller = product._select_seller(
+ partner_id=partner, quantity=line.product_uom_qty
+ )
purchase_edi = seller.purchase_edi_id
# Services should not appear in EDI file unless an EDI profile
# is specifically on the supplier info. This way, we avoid
# adding transport of potential discount or anything else
# in the EDI file.
if product.type == "service" and not purchase_edi:
continue
if purchase_edi:
profile_lines[purchase_edi] |= line
elif partner.default_purchase_profile_id:
profile_lines[partner.default_purchase_profile_id] |= line
else:
raise exceptions.UserError(
_("Some products don't have edi profile configured : %s")
% (product.default_code,)
)
return profile_lines |
bc6e6f0faec8405849c896b0661c181e9853359d | match/management/commands/import-users.py | match/management/commands/import-users.py | from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
tsvin = csv.reader(sys.stdin, delimiter='\t')
for row in tsvin:
User.objects.create(
name = row[0]
)
| from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
User.objects.all().delete()
tsvin = csv.reader(sys.stdin, delimiter='\t')
for row in tsvin:
User.objects.create(
name = row[0]
)
| Delete users before importing them | Delete users before importing them
| Python | mit | maxf/address-matcher,maxf/address-matcher,maxf/address-matcher,maxf/address-matcher | from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
+ User.objects.all().delete()
+
tsvin = csv.reader(sys.stdin, delimiter='\t')
for row in tsvin:
User.objects.create(
name = row[0]
)
| Delete users before importing them | ## Code Before:
from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
tsvin = csv.reader(sys.stdin, delimiter='\t')
for row in tsvin:
User.objects.create(
name = row[0]
)
## Instruction:
Delete users before importing them
## Code After:
from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
User.objects.all().delete()
tsvin = csv.reader(sys.stdin, delimiter='\t')
for row in tsvin:
User.objects.create(
name = row[0]
)
| from django.core.management.base import BaseCommand, CommandError
from match.models import User
import csv
import sys
class Command(BaseCommand):
help = 'Import a list of users from stdin'
def handle(self, *args, **options):
# read a file and copy its contents as test users
+ User.objects.all().delete()
+
tsvin = csv.reader(sys.stdin, delimiter='\t')
for row in tsvin:
User.objects.create(
name = row[0]
) |
d966b0973da71f5c883697ddd12c2728b2a04cce | ci/cleanup-binary-tags.py | ci/cleanup-binary-tags.py |
import os
import subprocess
import re
import semver
def tag_to_version(tag):
version = re.sub(r'binary-', '', tag)
version = re.sub(r'-[x86|i686].*', '', version)
return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
import os
import subprocess
import re
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
| Improve git tag to version conversion | Improve git tag to version conversion
There is also aarch64 arch.
| Python | mit | autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim |
import os
import subprocess
import re
import semver
def tag_to_version(tag):
+ return tag.split('-')[1].lstrip('v')
- version = re.sub(r'binary-', '', tag)
- version = re.sub(r'-[x86|i686].*', '', version)
- return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
| Improve git tag to version conversion | ## Code Before:
import os
import subprocess
import re
import semver
def tag_to_version(tag):
version = re.sub(r'binary-', '', tag)
version = re.sub(r'-[x86|i686].*', '', version)
return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
## Instruction:
Improve git tag to version conversion
## Code After:
import os
import subprocess
import re
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
import os
import subprocess
import re
import semver
def tag_to_version(tag):
+ return tag.split('-')[1].lstrip('v')
- version = re.sub(r'binary-', '', tag)
- version = re.sub(r'-[x86|i686].*', '', version)
- return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True) |
140e75fb3d96de3784c4ccc7272bbfa0e6b67d39 | pinax/invitations/__init__.py | pinax/invitations/__init__.py | import pkg_resources
__version__ = pkg_resources.get_distribution("pinax-invitations").version
| import pkg_resources
__version__ = pkg_resources.get_distribution("pinax-invitations").version
default_app_config = "pinax.invitations.apps.AppConfig"
| Set default_app_config to point to the correct AppConfig | Set default_app_config to point to the correct AppConfig
| Python | unknown | pinax/pinax-invitations,jacobwegner/pinax-invitations,eldarion/kaleo,rizumu/pinax-invitations | import pkg_resources
__version__ = pkg_resources.get_distribution("pinax-invitations").version
+ default_app_config = "pinax.invitations.apps.AppConfig"
| Set default_app_config to point to the correct AppConfig | ## Code Before:
import pkg_resources
__version__ = pkg_resources.get_distribution("pinax-invitations").version
## Instruction:
Set default_app_config to point to the correct AppConfig
## Code After:
import pkg_resources
__version__ = pkg_resources.get_distribution("pinax-invitations").version
default_app_config = "pinax.invitations.apps.AppConfig"
| import pkg_resources
__version__ = pkg_resources.get_distribution("pinax-invitations").version
+ default_app_config = "pinax.invitations.apps.AppConfig" |
7048366af948773b6badfb1f3611f9e4c694e810 | code/dataplot.py | code/dataplot.py | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
| import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
clampVal = 1;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,clampVal*np.ones(data.shape))
data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
| Create commandline options for the clampval | Create commandline options for the clampval
| Python | mit | TAdeJong/plasma-analysis,TAdeJong/plasma-analysis | import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
- #
+ clampVal = 1;
+ if (len(sys.argv) < 2) :
+ print("Usage: \n dataplot.py path_to_binfile [clamp value]")
+ sys.exit()
+ elif (len(sys.argv) > 2) :
+ clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
- data = np.minimum(data,1*np.ones(data.shape))
+ data = np.minimum(data,clampVal*np.ones(data.shape))
- data = np.maximum(data,-1*np.ones(data.shape))
+ data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
| Create commandline options for the clampval | ## Code Before:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
#
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,1*np.ones(data.shape))
data = np.maximum(data,-1*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
## Instruction:
Create commandline options for the clampval
## Code After:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
clampVal = 1;
if (len(sys.argv) < 2) :
print("Usage: \n dataplot.py path_to_binfile [clamp value]")
sys.exit()
elif (len(sys.argv) > 2) :
clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
data = np.minimum(data,clampVal*np.ones(data.shape))
data = np.maximum(data,-1*clampVal*np.ones(data.shape))
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
| import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
def loadCudaStream(name):
"""
reads the file specified by name into a numpy array (and removes
the superfluous fourth bit from cuda's float4)
np.shape(data)=(N,3) where N is the length of a streamline
"""
data=np.fromfile(name, dtype="float32")
data=data.reshape(int(len(data)/4), 4)
data=np.delete(data,3,1)
return data
- #
+ clampVal = 1;
+ if (len(sys.argv) < 2) :
+ print("Usage: \n dataplot.py path_to_binfile [clamp value]")
+ sys.exit()
+ elif (len(sys.argv) > 2) :
+ clampVal = int(sys.argv[2])
binfile = sys.argv[1]
data=np.fromfile(binfile, dtype="float32")
datasize = np.sqrt(data.shape[0])
data=data.reshape(datasize, datasize)
- data = np.minimum(data,1*np.ones(data.shape))
? ^
+ data = np.minimum(data,clampVal*np.ones(data.shape))
? ^^^^^^^^
- data = np.maximum(data,-1*np.ones(data.shape))
+ data = np.maximum(data,-1*clampVal*np.ones(data.shape))
? +++++++++
img = plt.imshow(data)
#img.set_cmap('hot')
plt.colorbar()
plt.show()
|
e2b382a69473dcfa6d93442f3ad3bc21ee6c90a0 | examples/tic_ql_tabular_selfplay_all.py | examples/tic_ql_tabular_selfplay_all.py | '''
In this example the Q-learning algorithm is used via self-play
to learn the state-action values for all Tic-Tac-Toe positions.
'''
from capstone.game.games import TicTacToe
from capstone.game.utils import tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
from capstone.rl.value_functions import TabularF
game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=1000, random_state=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
value = qlearning.qf[(game, move)]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
| '''
The Q-learning algorithm is used to learn the state-action values for all
Tic-Tac-Toe positions by playing games against itself (self-play).
'''
from capstone.game.games import TicTacToe
from capstone.game.players import GreedyQF, RandPlayer
from capstone.game.utils import play_series, tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=100000, verbose=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
value = qlearning.qf[game, move]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
players = [GreedyQF(qlearning.qf), RandPlayer()]
play_series(TicTacToe(), players, n_matches=10000)
# show number of unvisited state?
| Fix Tic-Tac-Toe Q-learning tabular self-play example | Fix Tic-Tac-Toe Q-learning tabular self-play example
| Python | mit | davidrobles/mlnd-capstone-code | '''
- In this example the Q-learning algorithm is used via self-play
- to learn the state-action values for all Tic-Tac-Toe positions.
+ The Q-learning algorithm is used to learn the state-action values for all
+ Tic-Tac-Toe positions by playing games against itself (self-play).
'''
from capstone.game.games import TicTacToe
+ from capstone.game.players import GreedyQF, RandPlayer
- from capstone.game.utils import tic2pdf
+ from capstone.game.utils import play_series, tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
- from capstone.rl.value_functions import TabularF
game = TicTacToe()
env = Environment(GameMDP(game))
- qlearning = QLearningSelfPlay(env, n_episodes=1000, random_state=0)
+ qlearning = QLearningSelfPlay(env, n_episodes=100000, verbose=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
- value = qlearning.qf[(game, move)]
+ value = qlearning.qf[game, move]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
+ players = [GreedyQF(qlearning.qf), RandPlayer()]
+ play_series(TicTacToe(), players, n_matches=10000)
+
+ # show number of unvisited state?
+ | Fix Tic-Tac-Toe Q-learning tabular self-play example | ## Code Before:
'''
In this example the Q-learning algorithm is used via self-play
to learn the state-action values for all Tic-Tac-Toe positions.
'''
from capstone.game.games import TicTacToe
from capstone.game.utils import tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
from capstone.rl.value_functions import TabularF
game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=1000, random_state=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
value = qlearning.qf[(game, move)]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
## Instruction:
Fix Tic-Tac-Toe Q-learning tabular self-play example
## Code After:
'''
The Q-learning algorithm is used to learn the state-action values for all
Tic-Tac-Toe positions by playing games against itself (self-play).
'''
from capstone.game.games import TicTacToe
from capstone.game.players import GreedyQF, RandPlayer
from capstone.game.utils import play_series, tic2pdf
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
game = TicTacToe()
env = Environment(GameMDP(game))
qlearning = QLearningSelfPlay(env, n_episodes=100000, verbose=0)
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
value = qlearning.qf[game, move]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
players = [GreedyQF(qlearning.qf), RandPlayer()]
play_series(TicTacToe(), players, n_matches=10000)
# show number of unvisited state?
| '''
- In this example the Q-learning algorithm is used via self-play
- to learn the state-action values for all Tic-Tac-Toe positions.
+ The Q-learning algorithm is used to learn the state-action values for all
+ Tic-Tac-Toe positions by playing games against itself (self-play).
'''
from capstone.game.games import TicTacToe
+ from capstone.game.players import GreedyQF, RandPlayer
- from capstone.game.utils import tic2pdf
+ from capstone.game.utils import play_series, tic2pdf
? +++++++++++++
from capstone.rl import Environment, GameMDP
from capstone.rl.learners import QLearningSelfPlay
- from capstone.rl.value_functions import TabularF
game = TicTacToe()
env = Environment(GameMDP(game))
- qlearning = QLearningSelfPlay(env, n_episodes=1000, random_state=0)
? ^^^ -- ---
+ qlearning = QLearningSelfPlay(env, n_episodes=100000, verbose=0)
? ++ ++ ^
qlearning.learn()
for move in game.legal_moves():
print('-' * 80)
- value = qlearning.qf[(game, move)]
? - -
+ value = qlearning.qf[game, move]
new_game = game.copy().make_move(move)
print(value)
print(new_game)
+
+ players = [GreedyQF(qlearning.qf), RandPlayer()]
+ play_series(TicTacToe(), players, n_matches=10000)
+
+ # show number of unvisited state? |
52d32849f4cd38ca7a0fcfc0418e9e9580dd426a | kimochiconsumer/views.py | kimochiconsumer/views.py | from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
| from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
| Use the gallery_image method for required information | Use the gallery_image method for required information
| Python | mit | matslindh/kimochi-consumer | from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
- data = request.kimochi.gallery(request.matchdict['gallery_id'])
+ data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
| Use the gallery_image method for required information | ## Code Before:
from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
## Instruction:
Use the gallery_image method for required information
## Code After:
from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
| from pyramid.view import view_config
from pyramid.httpexceptions import (
HTTPNotFound,
)
@view_config(route_name='page', renderer='templates/page.mako')
@view_config(route_name='page_view', renderer='templates/page.mako')
def page_view(request):
if 'page_id' in request.matchdict:
data = request.kimochi.page(request.matchdict['page_id'])
else:
data = request.kimochi.page('1')
return data
@view_config(route_name='gallery_view', renderer='templates/gallery.mako')
def gallery_view(request):
data = request.kimochi.gallery(request.matchdict['gallery_id'])
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data
@view_config(route_name='gallery_image_view', renderer='templates/gallery_image.mako')
def gallery_image_view(request):
- data = request.kimochi.gallery(request.matchdict['gallery_id'])
+ data = request.kimochi.gallery_image(request.matchdict['gallery_id'], request.matchdict['image_id'])
? ++++++ +++++++++++++++++++++++++++++++
if 'gallery' not in data or not data['gallery']:
raise HTTPNotFound
return data |
313aee17c8e2e1c86b96b40017ac4618c66df463 | __init__.py | __init__.py | ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CURRENCY = u"DT"
# Some variables needed by the test case graph widget
# REVENUES_CATEGORIES
XAXIS_PROPERTIES = { 'sali': {
'name' : 'sal',
'typ_tot' : {'salsuperbrut' : 'Salaire super brut',
'salbrut': 'Salaire brut',
'sal': 'Salaire imposable',
'salnet': 'Salaire net'},
'typ_tot_default' : 'sal'},
}
# Some variables used by other plugins
| ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CURRENCY = u"DT"
# Some variables needed by the test case graph widget
REVENUES_CATEGORIES = {'imposable' : ['sal',]}
XAXIS_PROPERTIES = { 'sali': {
'name' : 'sal',
'typ_tot' : {'salsuperbrut' : 'Salaire super brut',
'salbrut': 'Salaire brut',
'sal': 'Salaire imposable',
'salnet': 'Salaire net'},
'typ_tot_default' : 'sal'},
}
# Some variables used by other plugins
| Generalize graph and some new example scripts | Generalize graph and some new example scripts
| Python | agpl-3.0 | openfisca/openfisca-tunisia,openfisca/openfisca-tunisia | ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CURRENCY = u"DT"
# Some variables needed by the test case graph widget
- # REVENUES_CATEGORIES
+
+
+ REVENUES_CATEGORIES = {'imposable' : ['sal',]}
+
XAXIS_PROPERTIES = { 'sali': {
'name' : 'sal',
'typ_tot' : {'salsuperbrut' : 'Salaire super brut',
'salbrut': 'Salaire brut',
'sal': 'Salaire imposable',
'salnet': 'Salaire net'},
'typ_tot_default' : 'sal'},
}
# Some variables used by other plugins
| Generalize graph and some new example scripts | ## Code Before:
ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CURRENCY = u"DT"
# Some variables needed by the test case graph widget
# REVENUES_CATEGORIES
XAXIS_PROPERTIES = { 'sali': {
'name' : 'sal',
'typ_tot' : {'salsuperbrut' : 'Salaire super brut',
'salbrut': 'Salaire brut',
'sal': 'Salaire imposable',
'salnet': 'Salaire net'},
'typ_tot_default' : 'sal'},
}
# Some variables used by other plugins
## Instruction:
Generalize graph and some new example scripts
## Code After:
ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CURRENCY = u"DT"
# Some variables needed by the test case graph widget
REVENUES_CATEGORIES = {'imposable' : ['sal',]}
XAXIS_PROPERTIES = { 'sali': {
'name' : 'sal',
'typ_tot' : {'salsuperbrut' : 'Salaire super brut',
'salbrut': 'Salaire brut',
'sal': 'Salaire imposable',
'salnet': 'Salaire net'},
'typ_tot_default' : 'sal'},
}
# Some variables used by other plugins
| ENTITIES_INDEX = ['men', 'foy']
# Some variables needed by the test case plugins
CURRENCY = u"DT"
# Some variables needed by the test case graph widget
- # REVENUES_CATEGORIES
+
+
+ REVENUES_CATEGORIES = {'imposable' : ['sal',]}
+
XAXIS_PROPERTIES = { 'sali': {
'name' : 'sal',
'typ_tot' : {'salsuperbrut' : 'Salaire super brut',
'salbrut': 'Salaire brut',
'sal': 'Salaire imposable',
'salnet': 'Salaire net'},
'typ_tot_default' : 'sal'},
}
# Some variables used by other plugins |
32e066988a902f19d171225891f0a52a13945526 | frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py | frappe/patches/v12_0/move_form_attachments_to_attachments_folder.py | import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
''')
| import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
AND folder = 'Home'
''')
| Move files only from Home folder | fix(patch): Move files only from Home folder | Python | mit | mhbu50/frappe,frappe/frappe,vjFaLk/frappe,adityahase/frappe,adityahase/frappe,mhbu50/frappe,mhbu50/frappe,vjFaLk/frappe,vjFaLk/frappe,StrellaGroup/frappe,yashodhank/frappe,yashodhank/frappe,frappe/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,yashodhank/frappe,vjFaLk/frappe,saurabh6790/frappe,mhbu50/frappe,adityahase/frappe,saurabh6790/frappe,almeidapaulopt/frappe,adityahase/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,saurabh6790/frappe,frappe/frappe,StrellaGroup/frappe,saurabh6790/frappe | import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
+ AND folder = 'Home'
''')
| Move files only from Home folder | ## Code Before:
import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
''')
## Instruction:
Move files only from Home folder
## Code After:
import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
AND folder = 'Home'
''')
| import frappe
def execute():
frappe.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
+ AND folder = 'Home'
''') |
b5e4af74bfc12eb3ae9ca14ab4cebc49daf05fdc | api/wb/urls.py | api/wb/urls.py | from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^(?P<node_id>\w+)/copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| Add node id to url. | Add node id to url.
| Python | apache-2.0 | baylee-d/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,caseyrollins/osf.io,erinspace/osf.io,pattisdr/osf.io,erinspace/osf.io,icereval/osf.io,adlius/osf.io,erinspace/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,adlius/osf.io,felliott/osf.io,Johnetordoff/osf.io,felliott/osf.io,felliott/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,adlius/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,aaxelb/osf.io,aaxelb/osf.io,saradbowman/osf.io,icereval/osf.io,saradbowman/osf.io,cslzchen/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,caseyrollins/osf.io,aaxelb/osf.io,mfraezz/osf.io,sloria/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,mfraezz/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,icereval/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,pattisdr/osf.io,sloria/osf.io,caseyrollins/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,felliott/osf.io,mattclark/osf.io,Johnetordoff/osf.io,cslzchen/osf.io | from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
- url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
+ url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
- url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
+ url(r'^(?P<node_id>\w+)/copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| Add node id to url. | ## Code Before:
from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
## Instruction:
Add node id to url.
## Code After:
from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
url(r'^(?P<node_id>\w+)/copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
]
| from django.conf.urls import url
from api.wb import views
app_name = 'osf'
urlpatterns = [
- url(r'^move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
+ url(r'^(?P<node_id>\w+)/move/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
? +++++++++++++++++
- url(r'^copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
+ url(r'^(?P<node_id>\w+)/copy/', views.MoveFile.as_view(), name=views.MoveFile.view_name),
? +++++++++++++++++
] |
17c90fd954441c2623495e50a2f89790e1ff5489 | projects/tests/test_tools.py | projects/tests/test_tools.py | from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mixin case"""
def setUp(self):
self._orig_can_access = Project.can_access
Project.can_access = MagicMock()
self._orig_update = Project.objects.update_user_projects
Project.objects.update_user_projects = MagicMock()
self.mixin = ProjectAccessMixin()
self.project = factories.ProjectFactory()
self.mixin.get_project = MagicMock(return_value=self.project)
self.user = UserFactory()
def tearDown(self):
Project.can_access = self._orig_can_access
Project.objects.update_user_projects = self._orig_update
def test_can_access(self):
"""Test can access"""
Project.can_access.return_value = True
self.assertIsNone(self.mixin.check_can_access(
MagicMock(user=self.user),
))
def test_call_update_if_organization(self):
"""Test call update if organization"""
Project.can_access.return_value = False
with self.assertRaises(PermissionDenied):
self.mixin.check_can_access(MagicMock(user=self.user))
Project.objects.update_user_projects.asset_called_once_with(
self.user,
)
| import sure
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mixin case"""
def setUp(self):
self._orig_can_access = Project.can_access
Project.can_access = MagicMock()
self._orig_update = Project.objects.update_user_projects
Project.objects.update_user_projects = MagicMock()
self.mixin = ProjectAccessMixin()
self.project = factories.ProjectFactory()
self.mixin.get_project = MagicMock(return_value=self.project)
self.user = UserFactory()
def tearDown(self):
Project.can_access = self._orig_can_access
Project.objects.update_user_projects = self._orig_update
def test_can_access(self):
"""Test can access"""
Project.can_access.return_value = True
self.mixin.check_can_access(
MagicMock(user=self.user),
).should.be.none
def test_call_update_if_organization(self):
"""Test call update if organization"""
Project.can_access.return_value = False
self.mixin.check_can_access.when\
.called_with(MagicMock(user=self.user))\
.should.throw(PermissionDenied)
Project.objects.update_user_projects.asset_called_once_with(
self.user,
)
| Use sure in project tools cases | Use sure in project tools cases
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | + import sure
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mixin case"""
def setUp(self):
self._orig_can_access = Project.can_access
Project.can_access = MagicMock()
self._orig_update = Project.objects.update_user_projects
Project.objects.update_user_projects = MagicMock()
self.mixin = ProjectAccessMixin()
self.project = factories.ProjectFactory()
self.mixin.get_project = MagicMock(return_value=self.project)
self.user = UserFactory()
def tearDown(self):
Project.can_access = self._orig_can_access
Project.objects.update_user_projects = self._orig_update
def test_can_access(self):
"""Test can access"""
Project.can_access.return_value = True
- self.assertIsNone(self.mixin.check_can_access(
+ self.mixin.check_can_access(
MagicMock(user=self.user),
- ))
+ ).should.be.none
def test_call_update_if_organization(self):
"""Test call update if organization"""
Project.can_access.return_value = False
- with self.assertRaises(PermissionDenied):
- self.mixin.check_can_access(MagicMock(user=self.user))
+ self.mixin.check_can_access.when\
+ .called_with(MagicMock(user=self.user))\
+ .should.throw(PermissionDenied)
Project.objects.update_user_projects.asset_called_once_with(
self.user,
)
| Use sure in project tools cases | ## Code Before:
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mixin case"""
def setUp(self):
self._orig_can_access = Project.can_access
Project.can_access = MagicMock()
self._orig_update = Project.objects.update_user_projects
Project.objects.update_user_projects = MagicMock()
self.mixin = ProjectAccessMixin()
self.project = factories.ProjectFactory()
self.mixin.get_project = MagicMock(return_value=self.project)
self.user = UserFactory()
def tearDown(self):
Project.can_access = self._orig_can_access
Project.objects.update_user_projects = self._orig_update
def test_can_access(self):
"""Test can access"""
Project.can_access.return_value = True
self.assertIsNone(self.mixin.check_can_access(
MagicMock(user=self.user),
))
def test_call_update_if_organization(self):
"""Test call update if organization"""
Project.can_access.return_value = False
with self.assertRaises(PermissionDenied):
self.mixin.check_can_access(MagicMock(user=self.user))
Project.objects.update_user_projects.asset_called_once_with(
self.user,
)
## Instruction:
Use sure in project tools cases
## Code After:
import sure
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mixin case"""
def setUp(self):
self._orig_can_access = Project.can_access
Project.can_access = MagicMock()
self._orig_update = Project.objects.update_user_projects
Project.objects.update_user_projects = MagicMock()
self.mixin = ProjectAccessMixin()
self.project = factories.ProjectFactory()
self.mixin.get_project = MagicMock(return_value=self.project)
self.user = UserFactory()
def tearDown(self):
Project.can_access = self._orig_can_access
Project.objects.update_user_projects = self._orig_update
def test_can_access(self):
"""Test can access"""
Project.can_access.return_value = True
self.mixin.check_can_access(
MagicMock(user=self.user),
).should.be.none
def test_call_update_if_organization(self):
"""Test call update if organization"""
Project.can_access.return_value = False
self.mixin.check_can_access.when\
.called_with(MagicMock(user=self.user))\
.should.throw(PermissionDenied)
Project.objects.update_user_projects.asset_called_once_with(
self.user,
)
| + import sure
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mixin case"""
def setUp(self):
self._orig_can_access = Project.can_access
Project.can_access = MagicMock()
self._orig_update = Project.objects.update_user_projects
Project.objects.update_user_projects = MagicMock()
self.mixin = ProjectAccessMixin()
self.project = factories.ProjectFactory()
self.mixin.get_project = MagicMock(return_value=self.project)
self.user = UserFactory()
def tearDown(self):
Project.can_access = self._orig_can_access
Project.objects.update_user_projects = self._orig_update
def test_can_access(self):
"""Test can access"""
Project.can_access.return_value = True
- self.assertIsNone(self.mixin.check_can_access(
? ------------------
+ self.mixin.check_can_access(
MagicMock(user=self.user),
- ))
+ ).should.be.none
def test_call_update_if_organization(self):
"""Test call update if organization"""
Project.can_access.return_value = False
- with self.assertRaises(PermissionDenied):
- self.mixin.check_can_access(MagicMock(user=self.user))
+ self.mixin.check_can_access.when\
+ .called_with(MagicMock(user=self.user))\
+ .should.throw(PermissionDenied)
Project.objects.update_user_projects.asset_called_once_with(
self.user,
) |
e96e39bc3b5c540dc2cdcee26c6562c358745f93 | citrination_client/base/tests/test_base_client.py | citrination_client/base/tests/test_base_client.py | from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_zero_length_api_key():
"""
Tests that a zero length API key will cause the client to throw
an error on instantiation
"""
try:
client = BaseClient("", "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_version():
"""
Tests that the version is extracted
"""
client = BaseClient("asdf", "mycitrinationsite")
ver = client.version()
print("Version:"+ver)
assert ver[0].isdigit()
| from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
from citrination_client import __version__
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_zero_length_api_key():
"""
Tests that a zero length API key will cause the client to throw
an error on instantiation
"""
try:
client = BaseClient("", "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_version():
"""
Tests that the version is extracted
"""
ver = __version__
print("Version:" + ver)
assert ver[0].isdigit()
| Update test to use new version location | Update test to use new version location
| Python | apache-2.0 | CitrineInformatics/python-citrination-client | from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
+ from citrination_client import __version__
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_zero_length_api_key():
"""
Tests that a zero length API key will cause the client to throw
an error on instantiation
"""
try:
client = BaseClient("", "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_version():
"""
Tests that the version is extracted
"""
+ ver = __version__
- client = BaseClient("asdf", "mycitrinationsite")
- ver = client.version()
- print("Version:"+ver)
+ print("Version:" + ver)
assert ver[0].isdigit()
| Update test to use new version location | ## Code Before:
from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_zero_length_api_key():
"""
Tests that a zero length API key will cause the client to throw
an error on instantiation
"""
try:
client = BaseClient("", "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_version():
"""
Tests that the version is extracted
"""
client = BaseClient("asdf", "mycitrinationsite")
ver = client.version()
print("Version:"+ver)
assert ver[0].isdigit()
## Instruction:
Update test to use new version location
## Code After:
from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
from citrination_client import __version__
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_zero_length_api_key():
"""
Tests that a zero length API key will cause the client to throw
an error on instantiation
"""
try:
client = BaseClient("", "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_version():
"""
Tests that the version is extracted
"""
ver = __version__
print("Version:" + ver)
assert ver[0].isdigit()
| from citrination_client.base import BaseClient
from citrination_client.base.errors import CitrinationClientError
+ from citrination_client import __version__
def test_none_api_key():
"""
Ensures that an error is thrown if a client is instantiated
without an API key
"""
try:
client = BaseClient(None, "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_zero_length_api_key():
"""
Tests that a zero length API key will cause the client to throw
an error on instantiation
"""
try:
client = BaseClient("", "mycitrinationsite")
assert False
except CitrinationClientError:
assert True
def test_version():
"""
Tests that the version is extracted
"""
+ ver = __version__
- client = BaseClient("asdf", "mycitrinationsite")
- ver = client.version()
- print("Version:"+ver)
+ print("Version:" + ver)
? + +
assert ver[0].isdigit()
|
35d84021736f5509dc37f12ca92a05693cff5d47 | twython/helpers.py | twython/helpers.py | from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring):
params[k] = v
else:
continue
return params, files
| from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring) or isinstance(v, int):
params[k] = v
else:
continue
return params, files
| Include ints in params too | Include ints in params too
Oops ;P
| Python | mit | vivek8943/twython,ping/twython,akarambir/twython,Fueled/twython,fibears/twython,Hasimir/twython,Devyani-Divs/twython,Oire/twython,joebos/twython,ryanmcgrath/twython | from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
- elif isinstance(v, basestring):
+ elif isinstance(v, basestring) or isinstance(v, int):
params[k] = v
else:
continue
return params, files
| Include ints in params too | ## Code Before:
from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring):
params[k] = v
else:
continue
return params, files
## Instruction:
Include ints in params too
## Code After:
from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
elif isinstance(v, basestring) or isinstance(v, int):
params[k] = v
else:
continue
return params, files
| from .compat import basestring
def _transparent_params(_params):
params = {}
files = {}
for k, v in _params.items():
if hasattr(v, 'read') and callable(v.read):
files[k] = v
elif isinstance(v, bool):
if v:
params[k] = 'true'
else:
params[k] = 'false'
- elif isinstance(v, basestring):
+ elif isinstance(v, basestring) or isinstance(v, int):
? ++++++++++++++++++++++
params[k] = v
else:
continue
return params, files |
c1330851105df14367bec5ed87fc3c45b71932fd | project_euler/solutions/problem_35.py | project_euler/solutions/problem_35.py | from typing import List
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
for i in range(len(str(n))):
if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve):
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
return sum(1 for prime in range(bound) if is_circular_prime(prime, sieve))
| from typing import List
from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
rep_n = number_to_list(n)
for i in range(len(rep_n)):
if not is_prime(list_to_number(rep_n[i:] + rep_n[:i]), sieve):
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
return sum(1 for prime in range(1, bound)
if is_circular_prime(prime, sieve))
| Make 35 use number_to_list and inverse | Make 35 use number_to_list and inverse
| Python | mit | cryvate/project-euler,cryvate/project-euler | from typing import List
-
+ from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
+ rep_n = number_to_list(n)
+
- for i in range(len(str(n))):
+ for i in range(len(rep_n)):
- if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve):
+ if not is_prime(list_to_number(rep_n[i:] + rep_n[:i]), sieve):
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
- return sum(1 for prime in range(bound) if is_circular_prime(prime, sieve))
+ return sum(1 for prime in range(1, bound)
+ if is_circular_prime(prime, sieve))
| Make 35 use number_to_list and inverse | ## Code Before:
from typing import List
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
for i in range(len(str(n))):
if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve):
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
return sum(1 for prime in range(bound) if is_circular_prime(prime, sieve))
## Instruction:
Make 35 use number_to_list and inverse
## Code After:
from typing import List
from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
rep_n = number_to_list(n)
for i in range(len(rep_n)):
if not is_prime(list_to_number(rep_n[i:] + rep_n[:i]), sieve):
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
return sum(1 for prime in range(1, bound)
if is_circular_prime(prime, sieve))
| from typing import List
-
+ from ..library.base import number_to_list, list_to_number
from ..library.sqrt import fsqrt
from ..library.number_theory.primes import is_prime, prime_sieve
def is_circular_prime(n: int, sieve: List[int]) -> bool:
+ rep_n = number_to_list(n)
+
- for i in range(len(str(n))):
? -- ^ -
+ for i in range(len(rep_n)):
? ^^^
- if not is_prime(int(str(n)[i:] + str(n)[:i]), sieve):
? --- - -- ^ -
+ if not is_prime(list_to_number(rep_n[i:] + rep_n[:i]), sieve):
? + +++++++++ ++++ ^^^
return False
print(n)
return True
def solve(digits: int=6) -> int:
bound = 10 ** digits
sieve = prime_sieve(fsqrt(bound))
- return sum(1 for prime in range(bound) if is_circular_prime(prime, sieve))
+ return sum(1 for prime in range(1, bound)
+ if is_circular_prime(prime, sieve)) |
d5b068b2efc5fca30014ac7b4d58123461bfbdc1 | djedi/utils/templates.py | djedi/utils/templates.py | import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("admin:djedi:cms"),
"exclude_json_nodes": True,
}
)
output = render(request, "djedi/cms/embed.html", context)
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
"include djedi.rest.urls within the djedi namespace."
)
else:
context.update(
{
"cms_url": reverse("admin:djedi:cms"),
"exclude_json_nodes": False,
"json_nodes": json.dumps(nodes).replace("</", "\\x3C/"),
}
)
output = render_to_string("djedi/cms/embed.html", context)
return output
| import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("admin:djedi:cms"),
"exclude_json_nodes": True,
}
)
output = render(request, "djedi/cms/embed.html", context)
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
"enable django admin or include "
"djedi.urls within the admin namespace."
)
else:
context.update(
{
"cms_url": reverse("admin:djedi:cms"),
"exclude_json_nodes": False,
"json_nodes": json.dumps(nodes).replace("</", "\\x3C/"),
}
)
output = render_to_string("djedi/cms/embed.html", context)
return output
| Update rest api url config error message | Update rest api url config error message
| Python | bsd-3-clause | 5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms | import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("admin:djedi:cms"),
"exclude_json_nodes": True,
}
)
output = render(request, "djedi/cms/embed.html", context)
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
+ "enable django admin or include "
- "include djedi.rest.urls within the djedi namespace."
+ "djedi.urls within the admin namespace."
)
else:
context.update(
{
"cms_url": reverse("admin:djedi:cms"),
"exclude_json_nodes": False,
"json_nodes": json.dumps(nodes).replace("</", "\\x3C/"),
}
)
output = render_to_string("djedi/cms/embed.html", context)
return output
| Update rest api url config error message | ## Code Before:
import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("admin:djedi:cms"),
"exclude_json_nodes": True,
}
)
output = render(request, "djedi/cms/embed.html", context)
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
"include djedi.rest.urls within the djedi namespace."
)
else:
context.update(
{
"cms_url": reverse("admin:djedi:cms"),
"exclude_json_nodes": False,
"json_nodes": json.dumps(nodes).replace("</", "\\x3C/"),
}
)
output = render_to_string("djedi/cms/embed.html", context)
return output
## Instruction:
Update rest api url config error message
## Code After:
import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("admin:djedi:cms"),
"exclude_json_nodes": True,
}
)
output = render(request, "djedi/cms/embed.html", context)
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
"enable django admin or include "
"djedi.urls within the admin namespace."
)
else:
context.update(
{
"cms_url": reverse("admin:djedi:cms"),
"exclude_json_nodes": False,
"json_nodes": json.dumps(nodes).replace("</", "\\x3C/"),
}
)
output = render_to_string("djedi/cms/embed.html", context)
return output
| import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
context.update(
{
"cms_url": prefix + reverse("admin:djedi:cms"),
"exclude_json_nodes": True,
}
)
output = render(request, "djedi/cms/embed.html", context)
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
+ "enable django admin or include "
- "include djedi.rest.urls within the djedi namespace."
? -------- ----- ^^^
+ "djedi.urls within the admin namespace."
? + ^ +
)
else:
context.update(
{
"cms_url": reverse("admin:djedi:cms"),
"exclude_json_nodes": False,
"json_nodes": json.dumps(nodes).replace("</", "\\x3C/"),
}
)
output = render_to_string("djedi/cms/embed.html", context)
return output |
0c6480390f7984b2a85649bb539e7d6231506ef9 | oneflow/base/templatetags/base_utils.py | oneflow/base/templatetags/base_utils.py |
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, vars, variable_name=None):
self.vars = vars
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
return ''
@register.tag(name="firstofas")
def do_firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name)
|
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, args, variable_name=None):
self.vars = args
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
print('FOUND %s: %s' % (self.variable_name, value))
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
return ''
@register.tag
def firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name)
| Fix the `firstofas` template tag returning '' too early. | Fix the `firstofas` template tag returning '' too early. | Python | agpl-3.0 | WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,1flow/1flow,1flow/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow |
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
- def __init__(self, vars, variable_name=None):
+ def __init__(self, args, variable_name=None):
- self.vars = vars
+ self.vars = args
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
+ print('FOUND %s: %s' % (self.variable_name, value))
+
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
- return ''
+ return ''
- @register.tag(name="firstofas")
+ @register.tag
- def do_firstofas(parser, token):
+ def firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name)
| Fix the `firstofas` template tag returning '' too early. | ## Code Before:
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, vars, variable_name=None):
self.vars = vars
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
return ''
@register.tag(name="firstofas")
def do_firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name)
## Instruction:
Fix the `firstofas` template tag returning '' too early.
## Code After:
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
def __init__(self, args, variable_name=None):
self.vars = args
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
print('FOUND %s: %s' % (self.variable_name, value))
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
return ''
@register.tag
def firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name)
|
from django import template
from django.template.base import Node, TemplateSyntaxError
from django.utils.encoding import smart_text
register = template.Library()
class FirstOfAsNode(Node):
- def __init__(self, vars, variable_name=None):
? -
+ def __init__(self, args, variable_name=None):
? +
- self.vars = vars
? -
+ self.vars = args
? +
self.variable_name = variable_name
def render(self, context):
for var in self.vars:
value = var.resolve(context, True)
if value:
+ print('FOUND %s: %s' % (self.variable_name, value))
+
if self.variable_name:
context[self.variable_name] = value
break
else:
return smart_text(value)
- return ''
? ----
+ return ''
- @register.tag(name="firstofas")
+ @register.tag
- def do_firstofas(parser, token):
? ---
+ def firstofas(parser, token):
""" Original idea: https://code.djangoproject.com/ticket/12199 """
bits = token.split_contents()[1:]
variable_name = None
expecting_save_as = bits[-2] == 'as'
if expecting_save_as:
variable_name = bits.pop(-1)
bits = bits[:-1]
if len(bits) < 1:
raise TemplateSyntaxError(
"'firstofas' statement requires at least one argument")
return FirstOfAsNode([parser.compile_filter(bit) for bit in bits],
variable_name) |
9d35218506368702ac33d78be197ee3151d24ed9 | ledger_type.py | ledger_type.py | from openerp.osv import fields, osv
from openerp.tools.translate import _
_enum_ledger_type = [
('ledger_a', _('Ledger A')),
('ledger_b', _('Ledger B')),
('ledger_c', _('Ledger C')),
('ledger_d', _('Ledger D')),
('ledger_e', _('Ledger E')),
]
class ledger_type(osv.Model):
_name = 'alternate_ledger.ledger_type'
_columns = {
'name': fields.char(
_('Name'), size=256, required=True),
'type': fields.selection(
_enum_ledger_type, _('Ledger Type'), required=True),
}
_sql_constraint = [
('name', "UNIQUE('name')", 'Name has to be unique !'),
]
| from openerp.osv import fields, osv
from openerp.tools.translate import _
_enum_ledger_type = [
('ledger_a', _('Ledger A')),
('ledger_b', _('Ledger B')),
('ledger_c', _('Ledger C')),
('ledger_d', _('Ledger D')),
('ledger_e', _('Ledger E')),
]
class ledger_type(osv.Model):
_name = 'alternate_ledger.ledger_type'
_columns = {
'name': fields.char(
_('Name'), size=256, required=True),
'type': fields.selection(
_enum_ledger_type, _('Ledger Type'), required=True),
}
_order = 'name'
_sql_constraint = [
('name', "UNIQUE('name')", 'Name has to be unique !'),
]
| Order by ledger types by name | Order by ledger types by name
| Python | agpl-3.0 | xcgd/alternate_ledger,xcgd/alternate_ledger | from openerp.osv import fields, osv
from openerp.tools.translate import _
_enum_ledger_type = [
('ledger_a', _('Ledger A')),
('ledger_b', _('Ledger B')),
('ledger_c', _('Ledger C')),
('ledger_d', _('Ledger D')),
('ledger_e', _('Ledger E')),
]
class ledger_type(osv.Model):
_name = 'alternate_ledger.ledger_type'
-
+
_columns = {
'name': fields.char(
_('Name'), size=256, required=True),
'type': fields.selection(
_enum_ledger_type, _('Ledger Type'), required=True),
}
+ _order = 'name'
+
_sql_constraint = [
('name', "UNIQUE('name')", 'Name has to be unique !'),
]
| Order by ledger types by name | ## Code Before:
from openerp.osv import fields, osv
from openerp.tools.translate import _
_enum_ledger_type = [
('ledger_a', _('Ledger A')),
('ledger_b', _('Ledger B')),
('ledger_c', _('Ledger C')),
('ledger_d', _('Ledger D')),
('ledger_e', _('Ledger E')),
]
class ledger_type(osv.Model):
_name = 'alternate_ledger.ledger_type'
_columns = {
'name': fields.char(
_('Name'), size=256, required=True),
'type': fields.selection(
_enum_ledger_type, _('Ledger Type'), required=True),
}
_sql_constraint = [
('name', "UNIQUE('name')", 'Name has to be unique !'),
]
## Instruction:
Order by ledger types by name
## Code After:
from openerp.osv import fields, osv
from openerp.tools.translate import _
_enum_ledger_type = [
('ledger_a', _('Ledger A')),
('ledger_b', _('Ledger B')),
('ledger_c', _('Ledger C')),
('ledger_d', _('Ledger D')),
('ledger_e', _('Ledger E')),
]
class ledger_type(osv.Model):
_name = 'alternate_ledger.ledger_type'
_columns = {
'name': fields.char(
_('Name'), size=256, required=True),
'type': fields.selection(
_enum_ledger_type, _('Ledger Type'), required=True),
}
_order = 'name'
_sql_constraint = [
('name', "UNIQUE('name')", 'Name has to be unique !'),
]
| from openerp.osv import fields, osv
from openerp.tools.translate import _
_enum_ledger_type = [
('ledger_a', _('Ledger A')),
('ledger_b', _('Ledger B')),
('ledger_c', _('Ledger C')),
('ledger_d', _('Ledger D')),
('ledger_e', _('Ledger E')),
]
class ledger_type(osv.Model):
_name = 'alternate_ledger.ledger_type'
-
+
_columns = {
'name': fields.char(
_('Name'), size=256, required=True),
'type': fields.selection(
_enum_ledger_type, _('Ledger Type'), required=True),
}
+ _order = 'name'
+
_sql_constraint = [
('name', "UNIQUE('name')", 'Name has to be unique !'),
] |
31eae0aee3a6ae9fa7abea312ff1ea843a98e853 | graphene/contrib/django/tests/models.py | graphene/contrib/django/tests/models.py | from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',)
| from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
lang = models.CharField(max_length=2, help_text='Language', choices=[
('es', 'Spanish'),
('en', 'English')
], default='es')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',)
| Improve Django field conversion real-life tests | Improve Django field conversion real-life tests
| Python | mit | graphql-python/graphene,sjhewitt/graphene,Globegitter/graphene,sjhewitt/graphene,Globegitter/graphene,graphql-python/graphene | from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
+ lang = models.CharField(max_length=2, help_text='Language', choices=[
+ ('es', 'Spanish'),
+ ('en', 'English')
+ ], default='es')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',)
| Improve Django field conversion real-life tests | ## Code Before:
from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',)
## Instruction:
Improve Django field conversion real-life tests
## Code After:
from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
lang = models.CharField(max_length=2, help_text='Language', choices=[
('es', 'Spanish'),
('en', 'English')
], default='es')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',)
| from __future__ import absolute_import
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=30)
class Film(models.Model):
reporters = models.ManyToManyField('Reporter',
related_name='films')
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
pets = models.ManyToManyField('self')
def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, related_name='articles')
+ lang = models.CharField(max_length=2, help_text='Language', choices=[
+ ('es', 'Spanish'),
+ ('en', 'English')
+ ], default='es')
def __str__(self): # __unicode__ on Python 2
return self.headline
class Meta:
ordering = ('headline',) |
504bd5d8bb7ec63747318d16f90d24930e640fc6 | ipython_notebook_config.py | ipython_notebook_config.py | c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import yaml
with open('/import/conf.yaml','r') as handle:
conf = yaml.load(handle)
c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
| c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import os
import yaml
config_file_path = '/import/conf.yaml'
# In case this Notebook was launched from Galaxy a config file exists in /import/
# For standalone usage we fall back to a port-less URL
if os.path.exists( config_file_path ):
with open( config_file_path ,'r') as handle:
conf = yaml.load(handle)
c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
else:
c.NotebookApp.base_url = '/ipython/'
c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}
| Implement fallback mode to make the image unsable without Galaxy | Implement fallback mode to make the image unsable without Galaxy
| Python | mit | bgruening/docker-jupyter-notebook,bgruening/docker-jupyter-notebook,bgruening/docker-ipython-notebook,bgruening/docker-ipython-notebook,bgruening/docker-jupyter-notebook,bgruening/docker-ipython-notebook | c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
+
+ import os
import yaml
- with open('/import/conf.yaml','r') as handle:
- conf = yaml.load(handle)
- c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
- c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
+ config_file_path = '/import/conf.yaml'
+ # In case this Notebook was launched from Galaxy a config file exists in /import/
+ # For standalone usage we fall back to a port-less URL
+ if os.path.exists( config_file_path ):
+ with open( config_file_path ,'r') as handle:
+ conf = yaml.load(handle)
+ c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
+ c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
+ else:
+ c.NotebookApp.base_url = '/ipython/'
+ c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}
+ | Implement fallback mode to make the image unsable without Galaxy | ## Code Before:
c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import yaml
with open('/import/conf.yaml','r') as handle:
conf = yaml.load(handle)
c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
## Instruction:
Implement fallback mode to make the image unsable without Galaxy
## Code After:
c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
import os
import yaml
config_file_path = '/import/conf.yaml'
# In case this Notebook was launched from Galaxy a config file exists in /import/
# For standalone usage we fall back to a port-less URL
if os.path.exists( config_file_path ):
with open( config_file_path ,'r') as handle:
conf = yaml.load(handle)
c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
else:
c.NotebookApp.base_url = '/ipython/'
c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'}
| c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 6789
c.NotebookApp.open_browser = False
c.NotebookApp.profile = u'default'
+
+ import os
import yaml
- with open('/import/conf.yaml','r') as handle:
+
+ config_file_path = '/import/conf.yaml'
+ # In case this Notebook was launched from Galaxy a config file exists in /import/
+ # For standalone usage we fall back to a port-less URL
+ if os.path.exists( config_file_path ):
+ with open( config_file_path ,'r') as handle:
- conf = yaml.load(handle)
+ conf = yaml.load(handle)
? ++++
- c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
+ c.NotebookApp.base_url = '/ipython/%d/' % conf['docker_port']
? ++++
- c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
+ c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/%d/static/' % conf['docker_port']}
? ++++
+ else:
+ c.NotebookApp.base_url = '/ipython/'
+ c.NotebookApp.webapp_settings = {'static_url_prefix':'/ipython/static/'} |
53dd7c112d3f1781e8b7c662ba52c805a6afa568 | scripts/3-create-database.py | scripts/3-create-database.py | import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False)
| import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
df = df.sort_values("keplerid")
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False)
| Sort the final table by keplerid | Sort the final table by keplerid
| Python | mit | barentsen/K2metadata,KeplerGO/K2metadata,barentsen/k2-target-index | import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
+ df = df.sort_values("keplerid")
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False)
| Sort the final table by keplerid | ## Code Before:
import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False)
## Instruction:
Sort the final table by keplerid
## Code After:
import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
df = df.sort_values("keplerid")
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False)
| import glob
import logging
import sqlite3
import pandas as pd
log = logging.getLogger(__name__)
log.setLevel("INFO")
CSV_FILENAME = "../k2-target-pixel-files.csv"
SQLITE_FILENAME = "../k2-target-pixel-files.db"
if __name__ == "__main__":
log.info("Reading the data")
df = pd.concat([pd.read_csv(fn)
for fn
in glob.glob("intermediate-data/*metadata.csv")])
+ df = df.sort_values("keplerid")
# Write to the CSV file
log.info("Writing {}".format(CSV_FILENAME))
df.to_csv(CSV_FILENAME, index=False)
# Write the SQLite table
log.info("Writing {}".format(SQLITE_FILENAME))
con = sqlite3.connect(SQLITE_FILENAME)
df.to_sql(name='tpf', con=con, if_exists='replace', index=False) |
10db5e8b893a84e765162535f64e1ede81d48b47 | empty_check.py | empty_check.py | from django.core.exceptions import ValidationError
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| from django.core.exceptions import ValidationError
# Usage example in a custom form
# firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| Add comment to show usage example | Add comment to show usage example | Python | mit | vishalsodani/django-empty-check-validator | from django.core.exceptions import ValidationError
+ # Usage example in a custom form
+ # firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| Add comment to show usage example | ## Code Before:
from django.core.exceptions import ValidationError
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
## Instruction:
Add comment to show usage example
## Code After:
from django.core.exceptions import ValidationError
# Usage example in a custom form
# firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| from django.core.exceptions import ValidationError
+ # Usage example in a custom form
+ # firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty") |
05c057b44460eea6f6fe4a3dd891038d65e6d781 | naxos/naxos/settings/secretKeyGen.py | naxos/naxos/settings/secretKeyGen.py | try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
| try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
with open(SECRET_FILE) as f:
SECRET_KEY = f.read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
| Fix not closed file warning | fix: Fix not closed file warning
| Python | apache-2.0 | maur1th/naxos,maur1th/naxos,maur1th/naxos,maur1th/naxos | try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
+ with open(SECRET_FILE) as f:
- SECRET_KEY = open(SECRET_FILE).read().strip()
+ SECRET_KEY = f.read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
| Fix not closed file warning | ## Code Before:
try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
SECRET_KEY = open(SECRET_FILE).read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
## Instruction:
Fix not closed file warning
## Code After:
try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
with open(SECRET_FILE) as f:
SECRET_KEY = f.read().strip()
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE))
| try:
SECRET_KEY
except NameError:
from os.path import join
from .base import BASE_DIR
SECRET_FILE = join(BASE_DIR, 'secret.txt')
try:
+ with open(SECRET_FILE) as f:
- SECRET_KEY = open(SECRET_FILE).read().strip()
? ^^^^^^^^^^^^^^^^^
+ SECRET_KEY = f.read().strip()
? ++++ ^
except IOError:
try:
import random
SECRET_KEY = ''.join([random.SystemRandom().choice(
'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)')
for i in range(50)])
secret = open(SECRET_FILE, 'w')
secret.write(SECRET_KEY)
secret.close()
except IOError:
Exception('Please create a {:s} file with random characters \
to generate your secret key!'.format(SECRET_FILE)) |
388c938c0604bbf432921ad46be8325b1e74fa4a | direct/src/showbase/TkGlobal.py | direct/src/showbase/TkGlobal.py | """ This module is now vestigial. """
import sys, Pmw
# This is required by the ihooks.py module used by Squeeze (used by
# pandaSqueezer.py) so that Pmw initializes properly
if '_Pmw' in sys.modules:
sys.modules['_Pmw'].__name__ = '_Pmw'
def spawnTkLoop():
base.spawnTkLoop()
| """ This module is now vestigial. """
from Tkinter import *
import sys, Pmw
# This is required by the ihooks.py module used by Squeeze (used by
# pandaSqueezer.py) so that Pmw initializes properly
if '_Pmw' in sys.modules:
sys.modules['_Pmw'].__name__ = '_Pmw'
def spawnTkLoop():
base.spawnTkLoop()
| Add import for backward compatibility | Add import for backward compatibility
| Python | bsd-3-clause | ee08b397/panda3d,hj3938/panda3d,mgracer48/panda3d,chandler14362/panda3d,grimfang/panda3d,mgracer48/panda3d,chandler14362/panda3d,brakhane/panda3d,chandler14362/panda3d,cc272309126/panda3d,grimfang/panda3d,matthiascy/panda3d,mgracer48/panda3d,chandler14362/panda3d,Wilee999/panda3d,ee08b397/panda3d,jjkoletar/panda3d,jjkoletar/panda3d,hj3938/panda3d,Wilee999/panda3d,ee08b397/panda3d,cc272309126/panda3d,grimfang/panda3d,jjkoletar/panda3d,ee08b397/panda3d,hj3938/panda3d,grimfang/panda3d,Wilee999/panda3d,Wilee999/panda3d,chandler14362/panda3d,tobspr/panda3d,cc272309126/panda3d,mgracer48/panda3d,Wilee999/panda3d,brakhane/panda3d,grimfang/panda3d,matthiascy/panda3d,grimfang/panda3d,brakhane/panda3d,tobspr/panda3d,brakhane/panda3d,tobspr/panda3d,jjkoletar/panda3d,chandler14362/panda3d,grimfang/panda3d,mgracer48/panda3d,brakhane/panda3d,jjkoletar/panda3d,cc272309126/panda3d,brakhane/panda3d,hj3938/panda3d,grimfang/panda3d,hj3938/panda3d,mgracer48/panda3d,chandler14362/panda3d,matthiascy/panda3d,mgracer48/panda3d,tobspr/panda3d,tobspr/panda3d,ee08b397/panda3d,hj3938/panda3d,grimfang/panda3d,chandler14362/panda3d,Wilee999/panda3d,grimfang/panda3d,brakhane/panda3d,jjkoletar/panda3d,cc272309126/panda3d,tobspr/panda3d,tobspr/panda3d,matthiascy/panda3d,mgracer48/panda3d,matthiascy/panda3d,brakhane/panda3d,ee08b397/panda3d,ee08b397/panda3d,ee08b397/panda3d,cc272309126/panda3d,chandler14362/panda3d,Wilee999/panda3d,matthiascy/panda3d,Wilee999/panda3d,jjkoletar/panda3d,cc272309126/panda3d,matthiascy/panda3d,tobspr/panda3d,ee08b397/panda3d,tobspr/panda3d,hj3938/panda3d,hj3938/panda3d,mgracer48/panda3d,Wilee999/panda3d,cc272309126/panda3d,tobspr/panda3d,cc272309126/panda3d,chandler14362/panda3d,brakhane/panda3d,hj3938/panda3d,matthiascy/panda3d,matthiascy/panda3d,jjkoletar/panda3d,jjkoletar/panda3d | """ This module is now vestigial. """
+ from Tkinter import *
import sys, Pmw
# This is required by the ihooks.py module used by Squeeze (used by
# pandaSqueezer.py) so that Pmw initializes properly
if '_Pmw' in sys.modules:
sys.modules['_Pmw'].__name__ = '_Pmw'
def spawnTkLoop():
base.spawnTkLoop()
| Add import for backward compatibility | ## Code Before:
""" This module is now vestigial. """
import sys, Pmw
# This is required by the ihooks.py module used by Squeeze (used by
# pandaSqueezer.py) so that Pmw initializes properly
if '_Pmw' in sys.modules:
sys.modules['_Pmw'].__name__ = '_Pmw'
def spawnTkLoop():
base.spawnTkLoop()
## Instruction:
Add import for backward compatibility
## Code After:
""" This module is now vestigial. """
from Tkinter import *
import sys, Pmw
# This is required by the ihooks.py module used by Squeeze (used by
# pandaSqueezer.py) so that Pmw initializes properly
if '_Pmw' in sys.modules:
sys.modules['_Pmw'].__name__ = '_Pmw'
def spawnTkLoop():
base.spawnTkLoop()
| """ This module is now vestigial. """
+ from Tkinter import *
import sys, Pmw
# This is required by the ihooks.py module used by Squeeze (used by
# pandaSqueezer.py) so that Pmw initializes properly
if '_Pmw' in sys.modules:
sys.modules['_Pmw'].__name__ = '_Pmw'
def spawnTkLoop():
base.spawnTkLoop() |
94d4cb6a5c5d0c43e056bec73584d798f88ff70e | bnw_handlers/command_login.py | bnw_handlers/command_login.py |
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
def cmd_passlogin(request,user,password):
""" Логин паролем """
if not (user and password):
defer.returnValue(dict(ok=False,desc='Credentials cannot be empty'))
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
|
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
def cmd_passlogin(request,user=None,password=None):
""" Логин паролем """
if not (user and password):
defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.'))
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
| Fix 500 error on empty passlogin values | Fix 500 error on empty passlogin values
| Python | bsd-2-clause | stiletto/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,stiletto/bnw,ojab/bnw,un-def/bnw,stiletto/bnw,ojab/bnw,un-def/bnw,ojab/bnw,un-def/bnw |
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
- def cmd_passlogin(request,user,password):
+ def cmd_passlogin(request,user=None,password=None):
""" Логин паролем """
if not (user and password):
- defer.returnValue(dict(ok=False,desc='Credentials cannot be empty'))
+ defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.'))
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
| Fix 500 error on empty passlogin values | ## Code Before:
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
def cmd_passlogin(request,user,password):
""" Логин паролем """
if not (user and password):
defer.returnValue(dict(ok=False,desc='Credentials cannot be empty'))
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
## Instruction:
Fix 500 error on empty passlogin values
## Code After:
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
def cmd_passlogin(request,user=None,password=None):
""" Логин паролем """
if not (user and password):
defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.'))
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
|
from base import *
from bnw_core.base import get_webui_base
import bnw_core.bnw_objects as objs
from twisted.internet import defer
@require_auth
def cmd_login(request):
""" Логин-ссылка """
return dict(
ok=True,
desc='%s/login?key=%s' % (
get_webui_base(request.user),
request.user.get('login_key', '')))
@defer.inlineCallbacks
- def cmd_passlogin(request,user,password):
+ def cmd_passlogin(request,user=None,password=None):
? +++++ +++++
""" Логин паролем """
if not (user and password):
- defer.returnValue(dict(ok=False,desc='Credentials cannot be empty'))
+ defer.returnValue(dict(ok=False,desc='Credentials cannot be empty.'))
? +
u = yield objs.User.find_one({'name':user,'settings.password':password})
if u:
defer.returnValue(dict(ok=True,
desc=u.get('login_key','Successful, but no login key.')))
else:
defer.returnValue(dict(ok=False,
desc='Sorry, Dave.'))
|
2963909063e434936ba095ba9532782e7e3fd518 | tests/QtDeclarative/qdeclarativeview_test.py | tests/QtDeclarative/qdeclarativeview_test.py | '''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl, QStringList, QVariant
from PySide.QtGui import QPushButton
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
dataList = QStringList(["Item 1", "Item 2", "Item 3", "Item 4"])
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
| '''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
dataList = ["Item 1", "Item 2", "Item 3", "Item 4"]
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
| Remove use of deprecated types. | Remove use of deprecated types.
Reviewer: Hugo Parente Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org>,
Luciano Wolf <luciano.wolf@openbossa.org>
| Python | lgpl-2.1 | RobinD42/pyside,pankajp/pyside,RobinD42/pyside,BadSingleton/pyside2,IronManMark20/pyside2,M4rtinK/pyside-android,enthought/pyside,PySide/PySide,PySide/PySide,PySide/PySide,pankajp/pyside,PySide/PySide,M4rtinK/pyside-bb10,M4rtinK/pyside-android,M4rtinK/pyside-bb10,M4rtinK/pyside-bb10,RobinD42/pyside,IronManMark20/pyside2,M4rtinK/pyside-bb10,gbaty/pyside2,M4rtinK/pyside-android,IronManMark20/pyside2,qtproject/pyside-pyside,enthought/pyside,gbaty/pyside2,pankajp/pyside,gbaty/pyside2,RobinD42/pyside,pankajp/pyside,enthought/pyside,M4rtinK/pyside-bb10,RobinD42/pyside,enthought/pyside,IronManMark20/pyside2,RobinD42/pyside,RobinD42/pyside,qtproject/pyside-pyside,qtproject/pyside-pyside,M4rtinK/pyside-android,BadSingleton/pyside2,enthought/pyside,BadSingleton/pyside2,M4rtinK/pyside-android,gbaty/pyside2,BadSingleton/pyside2,enthought/pyside,PySide/PySide,M4rtinK/pyside-android,qtproject/pyside-pyside,M4rtinK/pyside-bb10,qtproject/pyside-pyside,gbaty/pyside2,pankajp/pyside,IronManMark20/pyside2,BadSingleton/pyside2,enthought/pyside | '''Test cases for QDeclarativeView'''
import unittest
+ from PySide.QtCore import QUrl
- from PySide.QtCore import QUrl, QStringList, QVariant
- from PySide.QtGui import QPushButton
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
- dataList = QStringList(["Item 1", "Item 2", "Item 3", "Item 4"])
+ dataList = ["Item 1", "Item 2", "Item 3", "Item 4"]
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
| Remove use of deprecated types. | ## Code Before:
'''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl, QStringList, QVariant
from PySide.QtGui import QPushButton
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
dataList = QStringList(["Item 1", "Item 2", "Item 3", "Item 4"])
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
## Instruction:
Remove use of deprecated types.
## Code After:
'''Test cases for QDeclarativeView'''
import unittest
from PySide.QtCore import QUrl
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
dataList = ["Item 1", "Item 2", "Item 3", "Item 4"]
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main()
| '''Test cases for QDeclarativeView'''
import unittest
+ from PySide.QtCore import QUrl
- from PySide.QtCore import QUrl, QStringList, QVariant
- from PySide.QtGui import QPushButton
from PySide.QtDeclarative import QDeclarativeView
from helper import adjust_filename, TimedQApplication
class TestQDeclarativeView(TimedQApplication):
def testQDeclarativeViewList(self):
view = QDeclarativeView()
- dataList = QStringList(["Item 1", "Item 2", "Item 3", "Item 4"])
? ------------ -
+ dataList = ["Item 1", "Item 2", "Item 3", "Item 4"]
ctxt = view.rootContext()
ctxt.setContextProperty("myModel", dataList)
url = QUrl.fromLocalFile(adjust_filename('view.qml', __file__))
view.setSource(url)
view.show()
self.assertEqual(view.status(), QDeclarativeView.Ready)
self.app.exec_()
if __name__ == '__main__':
unittest.main() |
2c43a04e5027a5f8cc2739ea93ab24057a07838f | tests/common.py | tests/common.py |
import os
import unittest
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target)
|
import os
import unittest
import platform
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
if platform.system() != "Darwin":
raise Exception("%s: This test suite must be run on OS X" % cls.__name__)
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target)
| Raise an exception when DtraceTestCase (and subclasses) is used on non-darwin machines | Raise an exception when DtraceTestCase (and subclasses) is used on non-darwin machines
| Python | mit | cuckoobox/cuckoo,rodionovd/cuckoo-osx-analyzer,cuckoobox/cuckoo,cuckoobox/cuckoo,cuckoobox/cuckoo,rodionovd/cuckoo-osx-analyzer,cuckoobox/cuckoo,rodionovd/cuckoo-osx-analyzer |
import os
import unittest
+ import platform
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ if platform.system() != "Darwin":
+ raise Exception("%s: This test suite must be run on OS X" % cls.__name__)
+
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target)
| Raise an exception when DtraceTestCase (and subclasses) is used on non-darwin machines | ## Code Before:
import os
import unittest
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target)
## Instruction:
Raise an exception when DtraceTestCase (and subclasses) is used on non-darwin machines
## Code After:
import os
import unittest
import platform
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
if platform.system() != "Darwin":
raise Exception("%s: This test suite must be run on OS X" % cls.__name__)
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target)
|
import os
import unittest
+ import platform
import subprocess
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
class DtraceTestCase(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ if platform.system() != "Darwin":
+ raise Exception("%s: This test suite must be run on OS X" % cls.__name__)
+
def setUp(self):
build_target(self._testMethodName)
def tearDown(self):
cleanup_target(self._testMethodName)
def current_target(self):
return TESTS_DIR + "/assets/" + self._testMethodName
def build_target(target):
# clang -arch x86_64 -o $target_name $target_name.c
output = executable_name_for_target(target)
source = sourcefile_name_for_target(target)
subprocess.check_call(["clang", "-arch", "x86_64", "-O0", "-o", output, source])
def cleanup_target(target):
os.remove(executable_name_for_target(target))
def sourcefile_name_for_target(target):
return "%s/assets/%s.c" % (TESTS_DIR, target)
def executable_name_for_target(target):
return "%s/assets/%s" % (TESTS_DIR, target) |
5e3be1d123063495f21d0c0068c7132d43fd9724 | account/models.py | account/models.py | from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
from course.models import Term
class Profile(models.Model):
user = models.OneToOneField(User)
student_id = models.CharField(max_length=10, null=True)
default_term = models.ForeignKey(Term, null=True)
facebook_id = models.CharField(max_length=50, null=True)
def create_profile(sender, instance, created, **kwargs):
profile = Profile.objects.get(user=instance)
if not profile:
Profile(user=instance).save()
signals.post_save.connect(create_profile, sender=User)
| from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
from course.models import Term
class Profile(models.Model):
user = models.OneToOneField(User)
student_id = models.CharField(max_length=10, null=True)
default_term = models.ForeignKey(Term, null=True)
facebook_id = models.CharField(max_length=50, null=True)
def create_profile(sender, instance, created, **kwargs):
try:
profile = Profile.objects.get(user=instance)
except Profile.DoesNotExist:
Profile(user=instance).save()
signals.post_save.connect(create_profile, sender=User)
| Fix login error for new accounts where a profile doesn't exist | Fix login error for new accounts where a profile doesn't exist
| Python | apache-2.0 | OpenCourseProject/OpenCourse,gravitylow/OpenCourse,gravitylow/OpenCourse,gravitylow/OpenCourse,OpenCourseProject/OpenCourse,OpenCourseProject/OpenCourse | from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
from course.models import Term
class Profile(models.Model):
user = models.OneToOneField(User)
student_id = models.CharField(max_length=10, null=True)
default_term = models.ForeignKey(Term, null=True)
facebook_id = models.CharField(max_length=50, null=True)
def create_profile(sender, instance, created, **kwargs):
+ try:
- profile = Profile.objects.get(user=instance)
+ profile = Profile.objects.get(user=instance)
- if not profile:
+ except Profile.DoesNotExist:
Profile(user=instance).save()
signals.post_save.connect(create_profile, sender=User)
| Fix login error for new accounts where a profile doesn't exist | ## Code Before:
from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
from course.models import Term
class Profile(models.Model):
user = models.OneToOneField(User)
student_id = models.CharField(max_length=10, null=True)
default_term = models.ForeignKey(Term, null=True)
facebook_id = models.CharField(max_length=50, null=True)
def create_profile(sender, instance, created, **kwargs):
profile = Profile.objects.get(user=instance)
if not profile:
Profile(user=instance).save()
signals.post_save.connect(create_profile, sender=User)
## Instruction:
Fix login error for new accounts where a profile doesn't exist
## Code After:
from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
from course.models import Term
class Profile(models.Model):
user = models.OneToOneField(User)
student_id = models.CharField(max_length=10, null=True)
default_term = models.ForeignKey(Term, null=True)
facebook_id = models.CharField(max_length=50, null=True)
def create_profile(sender, instance, created, **kwargs):
try:
profile = Profile.objects.get(user=instance)
except Profile.DoesNotExist:
Profile(user=instance).save()
signals.post_save.connect(create_profile, sender=User)
| from django.db import models
from django.db.models import signals
from django.contrib.auth.models import User
from course.models import Term
class Profile(models.Model):
user = models.OneToOneField(User)
student_id = models.CharField(max_length=10, null=True)
default_term = models.ForeignKey(Term, null=True)
facebook_id = models.CharField(max_length=50, null=True)
def create_profile(sender, instance, created, **kwargs):
+ try:
- profile = Profile.objects.get(user=instance)
+ profile = Profile.objects.get(user=instance)
? ++++
- if not profile:
+ except Profile.DoesNotExist:
Profile(user=instance).save()
signals.post_save.connect(create_profile, sender=User) |
f863f37a05855180dce40181a27e7925f0662647 | djangoautoconf/management/commands/dump_settings.py | djangoautoconf/management/commands/dump_settings.py | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict, bool):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
| import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict, bool, int, float):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
| Fix int float setting issue. | Fix int float setting issue.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
- if type(value) in (list, tuple, dict, bool):
+ if type(value) in (list, tuple, dict, bool, int, float):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
| Fix int float setting issue. | ## Code Before:
import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict, bool):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
## Instruction:
Fix int float setting issue.
## Code After:
import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
if type(value) in (list, tuple, dict, bool, int, float):
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
| import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Create command cache for environment where os.listdir is not working'
def handle(self, *args, **options):
try:
os.remove("local/total_settings.py")
except:
pass
with open("local/total_settings.py", "w") as f:
for key, value in dump_attrs(settings):
if value is None:
continue
- if type(value) in (list, tuple, dict, bool):
+ if type(value) in (list, tuple, dict, bool, int, float):
? ++++++++++++
print >>f, key, "=", value
elif type(value) in (str, ):
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
else:
print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"' |
955fd5b8525e7edd6477d5f74d7cbe7b743a127c | wind_model.py | wind_model.py |
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
|
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
self.H = 150
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
| Set depth for Lake Superior | Set depth for Lake Superior
| Python | bsd-3-clause | kjordahl/swm |
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
+ self.H = 150
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
| Set depth for Lake Superior | ## Code Before:
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
## Instruction:
Set depth for Lake Superior
## Code After:
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
self.H = 150
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main()
|
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import Int
class WindDrivenModel(ShallowWaterModel):
"""Class for wind driven model
Set flat initial conditions on Lake Superior
"""
def __init__(self):
self.nx = 151
self.ny = 151
self.Lbump = 0.0
self.Lx = 600e3
self.Ly = 600e3
self.lat = 43 # Latitude of Lake Superior
+ self.H = 150
super(WindDrivenModel, self).__init__()
def set_mask(self):
n = netcdf_file('superior_mask.grd', 'r')
z = n.variables['z']
self.msk = z.data
def main():
swm = WindDrivenModel()
plot = OceanPlot(swm)
swm.set_plot(plot)
import enaml
with enaml.imports():
from wind_view import WindView
view = WindView(model=swm, plot=plot)
view.show()
if __name__ == '__main__':
main() |
54d67ce544e95ecb58a62062ffe50fcd95db6f09 | sso/apps.py | sso/apps.py | from django.apps import AppConfig
class SsoConfig(AppConfig):
name = 'sso'
github_client_id = '844189c44c56ff04e727'
github_client_secret = '0bfecee7a78ee0e800b6bff85b08c140b91be4cc'
| import json
import os.path
from django.apps import AppConfig
from fmproject import settings
class SsoConfig(AppConfig):
base_config = json.load(
open(os.path.join(settings.BASE_DIR, 'fmproject', 'config.json'))
)
name = 'sso'
github_client_id = base_config['github']['client_id']
github_client_secret = base_config['github']['client_secret']
| Load github config from external file | Load github config from external file
| Python | mit | favoritemedium/sso-prototype,favoritemedium/sso-prototype | + import json
+ import os.path
from django.apps import AppConfig
+ from fmproject import settings
class SsoConfig(AppConfig):
+ base_config = json.load(
+ open(os.path.join(settings.BASE_DIR, 'fmproject', 'config.json'))
+ )
name = 'sso'
- github_client_id = '844189c44c56ff04e727'
- github_client_secret = '0bfecee7a78ee0e800b6bff85b08c140b91be4cc'
+ github_client_id = base_config['github']['client_id']
+ github_client_secret = base_config['github']['client_secret']
+ | Load github config from external file | ## Code Before:
from django.apps import AppConfig
class SsoConfig(AppConfig):
name = 'sso'
github_client_id = '844189c44c56ff04e727'
github_client_secret = '0bfecee7a78ee0e800b6bff85b08c140b91be4cc'
## Instruction:
Load github config from external file
## Code After:
import json
import os.path
from django.apps import AppConfig
from fmproject import settings
class SsoConfig(AppConfig):
base_config = json.load(
open(os.path.join(settings.BASE_DIR, 'fmproject', 'config.json'))
)
name = 'sso'
github_client_id = base_config['github']['client_id']
github_client_secret = base_config['github']['client_secret']
| + import json
+ import os.path
from django.apps import AppConfig
+ from fmproject import settings
class SsoConfig(AppConfig):
+ base_config = json.load(
+ open(os.path.join(settings.BASE_DIR, 'fmproject', 'config.json'))
+ )
name = 'sso'
- github_client_id = '844189c44c56ff04e727'
- github_client_secret = '0bfecee7a78ee0e800b6bff85b08c140b91be4cc'
+ github_client_id = base_config['github']['client_id']
+ github_client_secret = base_config['github']['client_secret']
+ |
5631276591cf2c4e3c83920da32857e47286d9c9 | wanikani/django.py | wanikani/django.py | from __future__ import absolute_import
import os
import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
with open(CONFIG_PATH) as fp:
API_KEY = fp.read()
logger = logging.getLogger(__name__)
class WaniKaniView(View):
def get(self, request, *args, **kwargs):
client = WaniKani(API_KEY)
level = client.profile()['level']
queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])
cal = Calendar()
cal.add('prodid', '-//My calendar product//mxm.dk//')
cal.add('version', '2.0')
for ts in sorted(queue):
if not len(queue[ts]):
continue
counts = {
Radical: 0,
Kanji: 0,
}
for obj in queue[ts]:
counts[obj.__class__] += 1
event = Event()
event.add('summary', 'R: {0} K: {1}'.format(
counts[Radical], counts[Kanji]
))
event.add('dtstart', ts)
event.add('dtend', ts)
event['uid'] = str(ts)
cal.add_component(event)
return HttpResponse(
content=cal.to_ical(),
content_type='text/plain; charset=utf-8'
)
|
from __future__ import absolute_import
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
class WaniKaniView(View):
def get(self, request, **kwargs):
client = WaniKani(kwargs['api_key'])
level = client.profile()['level']
queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])
cal = Calendar()
cal.add('prodid', '-//Wanikani Blockers//github.com/kfdm/wanikani//')
cal.add('version', '2.0')
for ts in sorted(queue):
if not len(queue[ts]):
continue
counts = {
Radical: 0,
Kanji: 0,
}
for obj in queue[ts]:
counts[obj.__class__] += 1
event = Event()
event.add('summary', 'R: {0} K: {1}'.format(
counts[Radical], counts[Kanji]
))
event.add('dtstart', ts)
event.add('dtend', ts)
event['uid'] = str(ts)
cal.add_component(event)
return HttpResponse(
content=cal.to_ical(),
content_type='text/plain; charset=utf-8'
)
| Switch to getting the API key from the URL instead of a config file. | Switch to getting the API key from the URL instead of a config file.
Allows other people to get their anki calendar if they want. | Python | mit | kfdm/wanikani,kfdm/wanikani | +
from __future__ import absolute_import
-
- import os
- import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
- CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
-
- with open(CONFIG_PATH) as fp:
- API_KEY = fp.read()
-
- logger = logging.getLogger(__name__)
-
class WaniKaniView(View):
- def get(self, request, *args, **kwargs):
+ def get(self, request, **kwargs):
- client = WaniKani(API_KEY)
+ client = WaniKani(kwargs['api_key'])
level = client.profile()['level']
queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])
cal = Calendar()
- cal.add('prodid', '-//My calendar product//mxm.dk//')
+ cal.add('prodid', '-//Wanikani Blockers//github.com/kfdm/wanikani//')
cal.add('version', '2.0')
for ts in sorted(queue):
if not len(queue[ts]):
continue
counts = {
Radical: 0,
Kanji: 0,
}
for obj in queue[ts]:
counts[obj.__class__] += 1
event = Event()
event.add('summary', 'R: {0} K: {1}'.format(
counts[Radical], counts[Kanji]
))
event.add('dtstart', ts)
event.add('dtend', ts)
event['uid'] = str(ts)
cal.add_component(event)
return HttpResponse(
content=cal.to_ical(),
content_type='text/plain; charset=utf-8'
)
| Switch to getting the API key from the URL instead of a config file. | ## Code Before:
from __future__ import absolute_import
import os
import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
with open(CONFIG_PATH) as fp:
API_KEY = fp.read()
logger = logging.getLogger(__name__)
class WaniKaniView(View):
def get(self, request, *args, **kwargs):
client = WaniKani(API_KEY)
level = client.profile()['level']
queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])
cal = Calendar()
cal.add('prodid', '-//My calendar product//mxm.dk//')
cal.add('version', '2.0')
for ts in sorted(queue):
if not len(queue[ts]):
continue
counts = {
Radical: 0,
Kanji: 0,
}
for obj in queue[ts]:
counts[obj.__class__] += 1
event = Event()
event.add('summary', 'R: {0} K: {1}'.format(
counts[Radical], counts[Kanji]
))
event.add('dtstart', ts)
event.add('dtend', ts)
event['uid'] = str(ts)
cal.add_component(event)
return HttpResponse(
content=cal.to_ical(),
content_type='text/plain; charset=utf-8'
)
## Instruction:
Switch to getting the API key from the URL instead of a config file.
## Code After:
from __future__ import absolute_import
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
class WaniKaniView(View):
def get(self, request, **kwargs):
client = WaniKani(kwargs['api_key'])
level = client.profile()['level']
queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])
cal = Calendar()
cal.add('prodid', '-//Wanikani Blockers//github.com/kfdm/wanikani//')
cal.add('version', '2.0')
for ts in sorted(queue):
if not len(queue[ts]):
continue
counts = {
Radical: 0,
Kanji: 0,
}
for obj in queue[ts]:
counts[obj.__class__] += 1
event = Event()
event.add('summary', 'R: {0} K: {1}'.format(
counts[Radical], counts[Kanji]
))
event.add('dtstart', ts)
event.add('dtend', ts)
event['uid'] = str(ts)
cal.add_component(event)
return HttpResponse(
content=cal.to_ical(),
content_type='text/plain; charset=utf-8'
)
| +
from __future__ import absolute_import
-
- import os
- import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
- CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
-
- with open(CONFIG_PATH) as fp:
- API_KEY = fp.read()
-
- logger = logging.getLogger(__name__)
-
class WaniKaniView(View):
- def get(self, request, *args, **kwargs):
? -------
+ def get(self, request, **kwargs):
- client = WaniKani(API_KEY)
+ client = WaniKani(kwargs['api_key'])
level = client.profile()['level']
queue = client.query(level, items=[Radical, Kanji], include=[u'apprentice'])
cal = Calendar()
- cal.add('prodid', '-//My calendar product//mxm.dk//')
+ cal.add('prodid', '-//Wanikani Blockers//github.com/kfdm/wanikani//')
cal.add('version', '2.0')
for ts in sorted(queue):
if not len(queue[ts]):
continue
counts = {
Radical: 0,
Kanji: 0,
}
for obj in queue[ts]:
counts[obj.__class__] += 1
event = Event()
event.add('summary', 'R: {0} K: {1}'.format(
counts[Radical], counts[Kanji]
))
event.add('dtstart', ts)
event.add('dtend', ts)
event['uid'] = str(ts)
cal.add_component(event)
return HttpResponse(
content=cal.to_ical(),
content_type='text/plain; charset=utf-8'
) |
fa4e6e849eaff2611a5d978c7f7727a16a8c301e | daedalus/attacks/sample_attack.py | daedalus/attacks/sample_attack.py | def attack(input={}, errors=[], results={}):
return {'errors': errors, 'results': results} | def attack(input={}):
return {'errors': errors, 'results': results}
| Remove extra parameters to "attack()" | Remove extra parameters to "attack()"
The `results` and `errors` structures aren't needed as input parameters.
All we need to ensure is that these are returned by `attack()`. | Python | mit | IEEE-NITK/Daedalus,IEEE-NITK/Daedalus,chinmaydd/NITK_IEEE_SaS,IEEE-NITK/Daedalus | - def attack(input={}, errors=[], results={}):
+ def attack(input={}):
return {'errors': errors, 'results': results}
+ | Remove extra parameters to "attack()" | ## Code Before:
def attack(input={}, errors=[], results={}):
return {'errors': errors, 'results': results}
## Instruction:
Remove extra parameters to "attack()"
## Code After:
def attack(input={}):
return {'errors': errors, 'results': results}
| - def attack(input={}, errors=[], results={}):
+ def attack(input={}):
return {'errors': errors, 'results': results} |
a0e432b0ac31ed74256197b1d5df8b6f8a0987db | product/models.py | product/models.py | from django.db import models
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from satchless.util.models import Subtyped
from satchless.item import ItemRange
from mptt.models import MPTTModel
class Category(MPTTModel):
name = models.CharField(_('Category field', 'name'), max_length=128)
slug = models.SlugField(_('Category field', 'slug'), max_length=50,
unique=True)
description = models.TextField(_('Category field', 'description'),
blank=True)
parent = models.ForeignKey('self', null=True, related_name='children',
blank=True,
verbose_name=_('Category field', 'parent'))
def __unicode__(self):
return self.name
class Product(Subtyped, ItemRange):
name = models.CharField(_('Product field', 'name'), max_length=128)
slug = models.SlugField(_('Product field', 'slug'), max_length=50,
unique=True)
price = PriceField(_('Product field', 'price'), currency='USD',
max_digits=12, decimal_places=4)
category = models.ForeignKey(Category,
verbose_name=_('Product field', 'category'))
def __unicode__(self):
return self.name
| from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from mptt.models import MPTTModel
from satchless.item import ItemRange
from satchless.util.models import Subtyped
from unidecode import unidecode
import re
class Category(MPTTModel):
name = models.CharField(_('Category field', 'name'), max_length=128)
slug = models.SlugField(_('Category field', 'slug'), max_length=50,
unique=True)
description = models.TextField(_('Category field', 'description'),
blank=True)
parent = models.ForeignKey('self', null=True, related_name='children',
blank=True,
verbose_name=_('Category field', 'parent'))
def __unicode__(self):
return self.name
class Product(Subtyped, ItemRange):
name = models.CharField(_('Product field', 'name'), max_length=128)
price = PriceField(_('Product field', 'price'), currency='USD',
max_digits=12, decimal_places=4)
category = models.ForeignKey(Category,
verbose_name=_('Product field', 'category'))
def __unicode__(self):
return self.name
def get_slug(self):
value = unidecode(self.name)
value = re.sub('[^\w\s-]', '', value).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value))
@models.permalink
def get_absolute_url(self):
return ('product:details', [self.get_slug(), self.id])
| Replace slug field with get_slug function | Replace slug field with get_slug function
| Python | bsd-3-clause | laosunhust/saleor,mociepka/saleor,paweltin/saleor,mociepka/saleor,jreigel/saleor,taedori81/saleor,UITools/saleor,UITools/saleor,spartonia/saleor,car3oon/saleor,Drekscott/Motlaesaleor,UITools/saleor,HyperManTT/ECommerceSaleor,paweltin/saleor,maferelo/saleor,dashmug/saleor,rodrigozn/CW-Shop,laosunhust/saleor,avorio/saleor,hongquan/saleor,taedori81/saleor,paweltin/saleor,tfroehlich82/saleor,rodrigozn/CW-Shop,car3oon/saleor,arth-co/saleor,HyperManTT/ECommerceSaleor,mociepka/saleor,tfroehlich82/saleor,josesanch/saleor,arth-co/saleor,avorio/saleor,itbabu/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,arth-co/saleor,Drekscott/Motlaesaleor,rodrigozn/CW-Shop,jreigel/saleor,rchav/vinerack,taedori81/saleor,taedori81/saleor,avorio/saleor,spartonia/saleor,itbabu/saleor,avorio/saleor,paweltin/saleor,jreigel/saleor,KenMutemi/saleor,laosunhust/saleor,josesanch/saleor,UITools/saleor,dashmug/saleor,rchav/vinerack,KenMutemi/saleor,arth-co/saleor,KenMutemi/saleor,UITools/saleor,Drekscott/Motlaesaleor,maferelo/saleor,spartonia/saleor,car3oon/saleor,hongquan/saleor,laosunhust/saleor,Drekscott/Motlaesaleor,dashmug/saleor,rchav/vinerack,maferelo/saleor,josesanch/saleor,hongquan/saleor,tfroehlich82/saleor,spartonia/saleor | from django.db import models
+ from django.utils.safestring import mark_safe
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
+ from mptt.models import MPTTModel
+ from satchless.item import ItemRange
from satchless.util.models import Subtyped
- from satchless.item import ItemRange
- from mptt.models import MPTTModel
+ from unidecode import unidecode
+ import re
class Category(MPTTModel):
name = models.CharField(_('Category field', 'name'), max_length=128)
slug = models.SlugField(_('Category field', 'slug'), max_length=50,
unique=True)
description = models.TextField(_('Category field', 'description'),
blank=True)
parent = models.ForeignKey('self', null=True, related_name='children',
blank=True,
verbose_name=_('Category field', 'parent'))
def __unicode__(self):
return self.name
class Product(Subtyped, ItemRange):
name = models.CharField(_('Product field', 'name'), max_length=128)
- slug = models.SlugField(_('Product field', 'slug'), max_length=50,
- unique=True)
price = PriceField(_('Product field', 'price'), currency='USD',
max_digits=12, decimal_places=4)
category = models.ForeignKey(Category,
verbose_name=_('Product field', 'category'))
def __unicode__(self):
return self.name
+ def get_slug(self):
+ value = unidecode(self.name)
+ value = re.sub('[^\w\s-]', '', value).strip().lower()
+
+ return mark_safe(re.sub('[-\s]+', '-', value))
+
+ @models.permalink
+ def get_absolute_url(self):
+ return ('product:details', [self.get_slug(), self.id])
+ | Replace slug field with get_slug function | ## Code Before:
from django.db import models
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from satchless.util.models import Subtyped
from satchless.item import ItemRange
from mptt.models import MPTTModel
class Category(MPTTModel):
name = models.CharField(_('Category field', 'name'), max_length=128)
slug = models.SlugField(_('Category field', 'slug'), max_length=50,
unique=True)
description = models.TextField(_('Category field', 'description'),
blank=True)
parent = models.ForeignKey('self', null=True, related_name='children',
blank=True,
verbose_name=_('Category field', 'parent'))
def __unicode__(self):
return self.name
class Product(Subtyped, ItemRange):
name = models.CharField(_('Product field', 'name'), max_length=128)
slug = models.SlugField(_('Product field', 'slug'), max_length=50,
unique=True)
price = PriceField(_('Product field', 'price'), currency='USD',
max_digits=12, decimal_places=4)
category = models.ForeignKey(Category,
verbose_name=_('Product field', 'category'))
def __unicode__(self):
return self.name
## Instruction:
Replace slug field with get_slug function
## Code After:
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
from mptt.models import MPTTModel
from satchless.item import ItemRange
from satchless.util.models import Subtyped
from unidecode import unidecode
import re
class Category(MPTTModel):
name = models.CharField(_('Category field', 'name'), max_length=128)
slug = models.SlugField(_('Category field', 'slug'), max_length=50,
unique=True)
description = models.TextField(_('Category field', 'description'),
blank=True)
parent = models.ForeignKey('self', null=True, related_name='children',
blank=True,
verbose_name=_('Category field', 'parent'))
def __unicode__(self):
return self.name
class Product(Subtyped, ItemRange):
name = models.CharField(_('Product field', 'name'), max_length=128)
price = PriceField(_('Product field', 'price'), currency='USD',
max_digits=12, decimal_places=4)
category = models.ForeignKey(Category,
verbose_name=_('Product field', 'category'))
def __unicode__(self):
return self.name
def get_slug(self):
value = unidecode(self.name)
value = re.sub('[^\w\s-]', '', value).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value))
@models.permalink
def get_absolute_url(self):
return ('product:details', [self.get_slug(), self.id])
| from django.db import models
+ from django.utils.safestring import mark_safe
from django.utils.translation import pgettext as _
from django_prices.models import PriceField
+ from mptt.models import MPTTModel
+ from satchless.item import ItemRange
from satchless.util.models import Subtyped
- from satchless.item import ItemRange
- from mptt.models import MPTTModel
+ from unidecode import unidecode
+ import re
class Category(MPTTModel):
name = models.CharField(_('Category field', 'name'), max_length=128)
slug = models.SlugField(_('Category field', 'slug'), max_length=50,
unique=True)
description = models.TextField(_('Category field', 'description'),
blank=True)
parent = models.ForeignKey('self', null=True, related_name='children',
blank=True,
verbose_name=_('Category field', 'parent'))
def __unicode__(self):
return self.name
class Product(Subtyped, ItemRange):
name = models.CharField(_('Product field', 'name'), max_length=128)
- slug = models.SlugField(_('Product field', 'slug'), max_length=50,
- unique=True)
price = PriceField(_('Product field', 'price'), currency='USD',
max_digits=12, decimal_places=4)
category = models.ForeignKey(Category,
verbose_name=_('Product field', 'category'))
def __unicode__(self):
return self.name
+
+ def get_slug(self):
+ value = unidecode(self.name)
+ value = re.sub('[^\w\s-]', '', value).strip().lower()
+
+ return mark_safe(re.sub('[-\s]+', '-', value))
+
+ @models.permalink
+ def get_absolute_url(self):
+ return ('product:details', [self.get_slug(), self.id]) |
fc08fb4086b3438cbe84042903b855c6fb55c30e | sshuttle/assembler.py | sshuttle/assembler.py | import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
% (name, nbytes))
content = z.decompress(sys.stdin.read(nbytes))
module = imp.new_module(name)
parents = name.rsplit(".", 1)
if len(parents) == 2:
parent, parent_name = parents
setattr(sys.modules[parent], parent_name, module)
code = compile(content, name, "exec")
exec(code, module.__dict__) # nosec
sys.modules[name] = module
else:
break
sys.stderr.flush()
sys.stdout.flush()
import sshuttle.helpers
sshuttle.helpers.verbose = verbosity
import sshuttle.cmdline_options as options
from sshuttle.server import main
main(options.latency_control, options.auto_hosts, options.to_nameserver)
| import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
global verbosity
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
% (name, nbytes))
content = z.decompress(sys.stdin.read(nbytes))
module = imp.new_module(name)
parents = name.rsplit(".", 1)
if len(parents) == 2:
parent, parent_name = parents
setattr(sys.modules[parent], parent_name, module)
code = compile(content, name, "exec")
exec(code, module.__dict__) # nosec
sys.modules[name] = module
else:
break
sys.stderr.flush()
sys.stdout.flush()
import sshuttle.helpers
sshuttle.helpers.verbose = verbosity
import sshuttle.cmdline_options as options
from sshuttle.server import main
main(options.latency_control, options.auto_hosts, options.to_nameserver)
| Declare 'verbosity' as global variable to placate linters | Declare 'verbosity' as global variable to placate linters | Python | lgpl-2.1 | sshuttle/sshuttle,sshuttle/sshuttle | import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
+ global verbosity
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
% (name, nbytes))
content = z.decompress(sys.stdin.read(nbytes))
module = imp.new_module(name)
parents = name.rsplit(".", 1)
if len(parents) == 2:
parent, parent_name = parents
setattr(sys.modules[parent], parent_name, module)
code = compile(content, name, "exec")
exec(code, module.__dict__) # nosec
sys.modules[name] = module
else:
break
sys.stderr.flush()
sys.stdout.flush()
import sshuttle.helpers
sshuttle.helpers.verbose = verbosity
import sshuttle.cmdline_options as options
from sshuttle.server import main
main(options.latency_control, options.auto_hosts, options.to_nameserver)
| Declare 'verbosity' as global variable to placate linters | ## Code Before:
import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
% (name, nbytes))
content = z.decompress(sys.stdin.read(nbytes))
module = imp.new_module(name)
parents = name.rsplit(".", 1)
if len(parents) == 2:
parent, parent_name = parents
setattr(sys.modules[parent], parent_name, module)
code = compile(content, name, "exec")
exec(code, module.__dict__) # nosec
sys.modules[name] = module
else:
break
sys.stderr.flush()
sys.stdout.flush()
import sshuttle.helpers
sshuttle.helpers.verbose = verbosity
import sshuttle.cmdline_options as options
from sshuttle.server import main
main(options.latency_control, options.auto_hosts, options.to_nameserver)
## Instruction:
Declare 'verbosity' as global variable to placate linters
## Code After:
import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
global verbosity
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
% (name, nbytes))
content = z.decompress(sys.stdin.read(nbytes))
module = imp.new_module(name)
parents = name.rsplit(".", 1)
if len(parents) == 2:
parent, parent_name = parents
setattr(sys.modules[parent], parent_name, module)
code = compile(content, name, "exec")
exec(code, module.__dict__) # nosec
sys.modules[name] = module
else:
break
sys.stderr.flush()
sys.stdout.flush()
import sshuttle.helpers
sshuttle.helpers.verbose = verbosity
import sshuttle.cmdline_options as options
from sshuttle.server import main
main(options.latency_control, options.auto_hosts, options.to_nameserver)
| import sys
import zlib
import imp
z = zlib.decompressobj()
while 1:
+ global verbosity
name = sys.stdin.readline().strip()
if name:
name = name.decode("ASCII")
nbytes = int(sys.stdin.readline())
if verbosity >= 2:
sys.stderr.write('server: assembling %r (%d bytes)\n'
% (name, nbytes))
content = z.decompress(sys.stdin.read(nbytes))
module = imp.new_module(name)
parents = name.rsplit(".", 1)
if len(parents) == 2:
parent, parent_name = parents
setattr(sys.modules[parent], parent_name, module)
code = compile(content, name, "exec")
exec(code, module.__dict__) # nosec
sys.modules[name] = module
else:
break
sys.stderr.flush()
sys.stdout.flush()
import sshuttle.helpers
sshuttle.helpers.verbose = verbosity
import sshuttle.cmdline_options as options
from sshuttle.server import main
main(options.latency_control, options.auto_hosts, options.to_nameserver) |
09d33da8657ec4c86855032f5ae16566c12fc2a5 | l10n_br_coa/models/l10n_br_account_tax_template.py | l10n_br_coa/models/l10n_br_account_tax_template.py |
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create_account_tax_templates(self, chart_template_id):
self.ensure_one()
account_tax_template_data = {'chart_template_id': chart_template_id}
account_tax_template_data.update({
field: self[field]
for field in self._fields if self[field] is not False})
self.env['account.tax.template'].create(account_tax_template_data)
|
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create_account_tax_templates(self, chart_template_id):
self.ensure_one()
chart = self.env['account.chart.template'].browse(chart_template_id)
module = chart.get_external_id()[chart_template_id].split('.')[0]
xmlid = '.'.join(
[module, self.get_external_id()[self.id].split('.')[1]])
tax_template_data = self.copy_data()[0]
tax_template_data.update({'chart_template_id': chart_template_id})
data = dict(xml_id=xmlid, values=tax_template_data, noupdate=True)
self.env['account.tax.template']._load_records([data])
| Create account.tax.template with external ids | [ADD] Create account.tax.template with external ids
| Python | agpl-3.0 | akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil |
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create_account_tax_templates(self, chart_template_id):
self.ensure_one()
+ chart = self.env['account.chart.template'].browse(chart_template_id)
+ module = chart.get_external_id()[chart_template_id].split('.')[0]
+ xmlid = '.'.join(
+ [module, self.get_external_id()[self.id].split('.')[1]])
+ tax_template_data = self.copy_data()[0]
- account_tax_template_data = {'chart_template_id': chart_template_id}
+ tax_template_data.update({'chart_template_id': chart_template_id})
+ data = dict(xml_id=xmlid, values=tax_template_data, noupdate=True)
+ self.env['account.tax.template']._load_records([data])
- account_tax_template_data.update({
- field: self[field]
- for field in self._fields if self[field] is not False})
- self.env['account.tax.template'].create(account_tax_template_data)
| Create account.tax.template with external ids | ## Code Before:
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create_account_tax_templates(self, chart_template_id):
self.ensure_one()
account_tax_template_data = {'chart_template_id': chart_template_id}
account_tax_template_data.update({
field: self[field]
for field in self._fields if self[field] is not False})
self.env['account.tax.template'].create(account_tax_template_data)
## Instruction:
Create account.tax.template with external ids
## Code After:
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create_account_tax_templates(self, chart_template_id):
self.ensure_one()
chart = self.env['account.chart.template'].browse(chart_template_id)
module = chart.get_external_id()[chart_template_id].split('.')[0]
xmlid = '.'.join(
[module, self.get_external_id()[self.id].split('.')[1]])
tax_template_data = self.copy_data()[0]
tax_template_data.update({'chart_template_id': chart_template_id})
data = dict(xml_id=xmlid, values=tax_template_data, noupdate=True)
self.env['account.tax.template']._load_records([data])
|
from odoo import fields, models
class L10nBrAccountTaxTemplate(models.Model):
_name = 'l10n_br_account.tax.template'
_inherit = 'account.tax.template'
chart_template_id = fields.Many2one(required=False)
def create_account_tax_templates(self, chart_template_id):
self.ensure_one()
+ chart = self.env['account.chart.template'].browse(chart_template_id)
+ module = chart.get_external_id()[chart_template_id].split('.')[0]
+ xmlid = '.'.join(
+ [module, self.get_external_id()[self.id].split('.')[1]])
+ tax_template_data = self.copy_data()[0]
- account_tax_template_data = {'chart_template_id': chart_template_id}
? -------- ^^^
+ tax_template_data.update({'chart_template_id': chart_template_id})
? ^^^^^^^^ +
+ data = dict(xml_id=xmlid, values=tax_template_data, noupdate=True)
+ self.env['account.tax.template']._load_records([data])
- account_tax_template_data.update({
- field: self[field]
- for field in self._fields if self[field] is not False})
- self.env['account.tax.template'].create(account_tax_template_data) |
8d5ac7efd98426394040fb01f0096f35a804b1b7 | tests/plugins/test_generic.py | tests/plugins/test_generic.py | import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from .utils import create_har_entry
class TestGenericPlugin(object):
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize('plugin_name,indicator,name', [
(
'wordpress_generic',
{'url': 'http://domain.tld/wp-content/plugins/example/'},
'example',
)
])
def test_real_generic_plugin(self, plugin_name, indicator, name, plugins):
plugin = plugins.get(plugin_name)
matcher_type = [k for k in indicator.keys()][0]
har_entry = create_har_entry(indicator, matcher_type)
matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators')
# Call presence method in related matcher class
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.check_presence(har_entry, *matchers_in_plugin)
assert plugin.get_information(har_entry)['name'] == name
| import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from tests import create_pm
from .utils import create_har_entry
class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize(
'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
'url',
'http://domain.tld/wp-content/plugins/example/',
'example',
)]
)
def test_real_generic_plugin(
self, plugin_name, matcher_type, har_content, name, plugins
):
plugin = plugins.get(plugin_name)
har_entry = create_har_entry(matcher_type, value=har_content)
# Verify presence using matcher class
matchers = plugin.get_matchers(matcher_type)
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.get_info(
har_entry,
*matchers,
) == create_pm(presence=True)
assert plugin.get_information(har_entry)['name'] == name
| Fix test for generic plugins | Fix test for generic plugins
| Python | mit | spectresearch/detectem | import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
+ from tests import create_pm
from .utils import create_har_entry
- class TestGenericPlugin(object):
+ class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
- @pytest.mark.parametrize('plugin_name,indicator,name', [
- (
+ @pytest.mark.parametrize(
+ 'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
+ 'url',
- {'url': 'http://domain.tld/wp-content/plugins/example/'},
+ 'http://domain.tld/wp-content/plugins/example/',
'example',
- )
+ )]
- ])
+ )
- def test_real_generic_plugin(self, plugin_name, indicator, name, plugins):
+ def test_real_generic_plugin(
+ self, plugin_name, matcher_type, har_content, name, plugins
+ ):
plugin = plugins.get(plugin_name)
- matcher_type = [k for k in indicator.keys()][0]
+ har_entry = create_har_entry(matcher_type, value=har_content)
- har_entry = create_har_entry(indicator, matcher_type)
+ # Verify presence using matcher class
- matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators')
+ matchers = plugin.get_matchers(matcher_type)
+ matcher_instance = MATCHERS[matcher_type]
- # Call presence method in related matcher class
- matcher_instance = MATCHERS[matcher_type]
- assert matcher_instance.check_presence(har_entry, *matchers_in_plugin)
+ assert matcher_instance.get_info(
+ har_entry,
+ *matchers,
+ ) == create_pm(presence=True)
assert plugin.get_information(har_entry)['name'] == name
| Fix test for generic plugins | ## Code Before:
import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from .utils import create_har_entry
class TestGenericPlugin(object):
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize('plugin_name,indicator,name', [
(
'wordpress_generic',
{'url': 'http://domain.tld/wp-content/plugins/example/'},
'example',
)
])
def test_real_generic_plugin(self, plugin_name, indicator, name, plugins):
plugin = plugins.get(plugin_name)
matcher_type = [k for k in indicator.keys()][0]
har_entry = create_har_entry(indicator, matcher_type)
matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators')
# Call presence method in related matcher class
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.check_presence(har_entry, *matchers_in_plugin)
assert plugin.get_information(har_entry)['name'] == name
## Instruction:
Fix test for generic plugins
## Code After:
import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
from tests import create_pm
from .utils import create_har_entry
class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
@pytest.mark.parametrize(
'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
'url',
'http://domain.tld/wp-content/plugins/example/',
'example',
)]
)
def test_real_generic_plugin(
self, plugin_name, matcher_type, har_content, name, plugins
):
plugin = plugins.get(plugin_name)
har_entry = create_har_entry(matcher_type, value=har_content)
# Verify presence using matcher class
matchers = plugin.get_matchers(matcher_type)
matcher_instance = MATCHERS[matcher_type]
assert matcher_instance.get_info(
har_entry,
*matchers,
) == create_pm(presence=True)
assert plugin.get_information(har_entry)['name'] == name
| import pytest
from detectem.core import MATCHERS
from detectem.plugin import load_plugins, GenericPlugin
+ from tests import create_pm
from .utils import create_har_entry
- class TestGenericPlugin(object):
? --------
+ class TestGenericPlugin:
@pytest.fixture
def plugins(self):
return load_plugins()
def test_generic_plugin(self):
class MyGenericPlugin(GenericPlugin):
pass
x = MyGenericPlugin()
with pytest.raises(NotImplementedError):
x.get_information(entry=None)
assert x.ptype == 'generic'
- @pytest.mark.parametrize('plugin_name,indicator,name', [
- (
+ @pytest.mark.parametrize(
+ 'plugin_name,matcher_type,har_content,name', [(
'wordpress_generic',
+ 'url',
- {'url': 'http://domain.tld/wp-content/plugins/example/'},
? -------- -
+ 'http://domain.tld/wp-content/plugins/example/',
'example',
- )
+ )]
? +
- ])
? -
+ )
- def test_real_generic_plugin(self, plugin_name, indicator, name, plugins):
+ def test_real_generic_plugin(
+ self, plugin_name, matcher_type, har_content, name, plugins
+ ):
plugin = plugins.get(plugin_name)
- matcher_type = [k for k in indicator.keys()][0]
+ har_entry = create_har_entry(matcher_type, value=har_content)
- har_entry = create_har_entry(indicator, matcher_type)
+ # Verify presence using matcher class
- matchers_in_plugin = plugin._get_matchers(matcher_type, 'indicators')
? ---------- - --------------
+ matchers = plugin.get_matchers(matcher_type)
+ matcher_instance = MATCHERS[matcher_type]
- # Call presence method in related matcher class
- matcher_instance = MATCHERS[matcher_type]
- assert matcher_instance.check_presence(har_entry, *matchers_in_plugin)
+ assert matcher_instance.get_info(
+ har_entry,
+ *matchers,
+ ) == create_pm(presence=True)
assert plugin.get_information(har_entry)['name'] == name |
474eda82f332a645193c1806dbaf840b8d506a65 | sigma_core/serializers/cluster.py | sigma_core/serializers/cluster.py | from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
exclude = ('resp_group',
'req_rank_invite',
'req_rank_kick',
'req_rank_accept_join_requests',
'req_rank_promote',
'req_rank_demote',
'req_rank_modify_group_infos',
'default_member_rank',
'protected',
'private')
from sigma_core.serializers.user import UserWithPermsSerializer
class ClusterSerializer(BasicClusterSerializer):
"""
Serialize Cluster model with memberships.
"""
class Meta(BasicClusterSerializer.Meta):
pass
users = UserWithPermsSerializer(read_only=True, many=True)
| from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
exclude = ('resp_group',
'req_rank_invite',
'req_rank_kick',
'req_rank_accept_join_requests',
'req_rank_promote',
'req_rank_demote',
'req_rank_modify_group_infos',
'default_member_rank',
'protected',
'private')
class ClusterSerializer(BasicClusterSerializer):
"""
Serialize Cluster model with memberships.
"""
class Meta(BasicClusterSerializer.Meta):
pass
users_ids = serializers.PrimaryKeyRelatedField(read_only=True, many=True, source='users')
| Use only foreign keys in Cluster serialisation and add _id suffixes | Use only foreign keys in Cluster serialisation and add _id suffixes
| Python | agpl-3.0 | ProjetSigma/backend,ProjetSigma/backend | from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
exclude = ('resp_group',
'req_rank_invite',
'req_rank_kick',
'req_rank_accept_join_requests',
'req_rank_promote',
'req_rank_demote',
'req_rank_modify_group_infos',
'default_member_rank',
'protected',
'private')
- from sigma_core.serializers.user import UserWithPermsSerializer
class ClusterSerializer(BasicClusterSerializer):
"""
Serialize Cluster model with memberships.
"""
class Meta(BasicClusterSerializer.Meta):
pass
- users = UserWithPermsSerializer(read_only=True, many=True)
+ users_ids = serializers.PrimaryKeyRelatedField(read_only=True, many=True, source='users')
| Use only foreign keys in Cluster serialisation and add _id suffixes | ## Code Before:
from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
exclude = ('resp_group',
'req_rank_invite',
'req_rank_kick',
'req_rank_accept_join_requests',
'req_rank_promote',
'req_rank_demote',
'req_rank_modify_group_infos',
'default_member_rank',
'protected',
'private')
from sigma_core.serializers.user import UserWithPermsSerializer
class ClusterSerializer(BasicClusterSerializer):
"""
Serialize Cluster model with memberships.
"""
class Meta(BasicClusterSerializer.Meta):
pass
users = UserWithPermsSerializer(read_only=True, many=True)
## Instruction:
Use only foreign keys in Cluster serialisation and add _id suffixes
## Code After:
from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
exclude = ('resp_group',
'req_rank_invite',
'req_rank_kick',
'req_rank_accept_join_requests',
'req_rank_promote',
'req_rank_demote',
'req_rank_modify_group_infos',
'default_member_rank',
'protected',
'private')
class ClusterSerializer(BasicClusterSerializer):
"""
Serialize Cluster model with memberships.
"""
class Meta(BasicClusterSerializer.Meta):
pass
users_ids = serializers.PrimaryKeyRelatedField(read_only=True, many=True, source='users')
| from rest_framework import serializers
from sigma_core.models.cluster import Cluster
from sigma_core.serializers.group import GroupSerializer
class BasicClusterSerializer(serializers.ModelSerializer):
"""
Serialize Cluster model without memberships.
"""
class Meta:
model = Cluster
exclude = ('resp_group',
'req_rank_invite',
'req_rank_kick',
'req_rank_accept_join_requests',
'req_rank_promote',
'req_rank_demote',
'req_rank_modify_group_infos',
'default_member_rank',
'protected',
'private')
- from sigma_core.serializers.user import UserWithPermsSerializer
class ClusterSerializer(BasicClusterSerializer):
"""
Serialize Cluster model with memberships.
"""
class Meta(BasicClusterSerializer.Meta):
pass
- users = UserWithPermsSerializer(read_only=True, many=True)
+ users_ids = serializers.PrimaryKeyRelatedField(read_only=True, many=True, source='users') |
cb08d25f49b8b4c5177c8afdd9a69330992ee854 | tests/replay/test_replay.py | tests/replay/test_replay.py |
import pytest
from cookiecutter import replay, main, exceptions
def test_get_replay_file_name():
"""Make sure that replay.get_file_name generates a valid json file path."""
assert replay.get_file_name('foo', 'bar') == 'foo/bar.json'
@pytest.fixture(params=[
{'no_input': True},
{'extra_context': {}},
{'no_input': True, 'extra_context': {}},
])
def invalid_kwargs(request):
return request.param
def test_raise_on_invalid_mode(invalid_kwargs):
with pytest.raises(exceptions.InvalidModeException):
main.cookiecutter('foo', replay=True, **invalid_kwargs)
|
import pytest
from cookiecutter import replay, main, exceptions
def test_get_replay_file_name():
"""Make sure that replay.get_file_name generates a valid json file path."""
assert replay.get_file_name('foo', 'bar') == 'foo/bar.json'
@pytest.fixture(params=[
{'no_input': True},
{'extra_context': {}},
{'no_input': True, 'extra_context': {}},
])
def invalid_kwargs(request):
return request.param
def test_raise_on_invalid_mode(invalid_kwargs):
with pytest.raises(exceptions.InvalidModeException):
main.cookiecutter('foo', replay=True, **invalid_kwargs)
def test_main_does_not_invoke_dump_but_load(mocker):
mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
mock_replay_dump = mocker.patch('cookiecutter.main.dump')
mock_replay_load = mocker.patch('cookiecutter.main.load')
main.cookiecutter('foobar', replay=True)
assert not mock_prompt.called
assert not mock_gen_context.called
assert not mock_replay_dump.called
assert mock_replay_load.called
assert mock_gen_files.called
def test_main_does_not_invoke_load_but_dump(mocker):
mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
mock_replay_dump = mocker.patch('cookiecutter.main.dump')
mock_replay_load = mocker.patch('cookiecutter.main.load')
main.cookiecutter('foobar', replay=False)
assert mock_prompt.called
assert mock_gen_context.called
assert mock_replay_dump.called
assert not mock_replay_load.called
assert mock_gen_files.called
| Add tests for a correct behaviour in cookiecutter.main for replay | Add tests for a correct behaviour in cookiecutter.main for replay
| Python | bsd-3-clause | christabor/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,cguardia/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,michaeljoseph/cookiecutter,moi65/cookiecutter,terryjbates/cookiecutter,takeflight/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,agconti/cookiecutter,cguardia/cookiecutter,christabor/cookiecutter,audreyr/cookiecutter,stevepiercy/cookiecutter,willingc/cookiecutter,venumech/cookiecutter,stevepiercy/cookiecutter,takeflight/cookiecutter,pjbull/cookiecutter,benthomasson/cookiecutter,agconti/cookiecutter,benthomasson/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,audreyr/cookiecutter,moi65/cookiecutter,dajose/cookiecutter,hackebrot/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,ramiroluz/cookiecutter,venumech/cookiecutter,willingc/cookiecutter |
import pytest
from cookiecutter import replay, main, exceptions
def test_get_replay_file_name():
"""Make sure that replay.get_file_name generates a valid json file path."""
assert replay.get_file_name('foo', 'bar') == 'foo/bar.json'
@pytest.fixture(params=[
{'no_input': True},
{'extra_context': {}},
{'no_input': True, 'extra_context': {}},
])
def invalid_kwargs(request):
return request.param
def test_raise_on_invalid_mode(invalid_kwargs):
with pytest.raises(exceptions.InvalidModeException):
main.cookiecutter('foo', replay=True, **invalid_kwargs)
+
+ def test_main_does_not_invoke_dump_but_load(mocker):
+ mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
+ mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
+ mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
+ mock_replay_dump = mocker.patch('cookiecutter.main.dump')
+ mock_replay_load = mocker.patch('cookiecutter.main.load')
+
+ main.cookiecutter('foobar', replay=True)
+
+ assert not mock_prompt.called
+ assert not mock_gen_context.called
+ assert not mock_replay_dump.called
+ assert mock_replay_load.called
+ assert mock_gen_files.called
+
+
+ def test_main_does_not_invoke_load_but_dump(mocker):
+ mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
+ mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
+ mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
+ mock_replay_dump = mocker.patch('cookiecutter.main.dump')
+ mock_replay_load = mocker.patch('cookiecutter.main.load')
+
+ main.cookiecutter('foobar', replay=False)
+
+ assert mock_prompt.called
+ assert mock_gen_context.called
+ assert mock_replay_dump.called
+ assert not mock_replay_load.called
+ assert mock_gen_files.called
+ | Add tests for a correct behaviour in cookiecutter.main for replay | ## Code Before:
import pytest
from cookiecutter import replay, main, exceptions
def test_get_replay_file_name():
"""Make sure that replay.get_file_name generates a valid json file path."""
assert replay.get_file_name('foo', 'bar') == 'foo/bar.json'
@pytest.fixture(params=[
{'no_input': True},
{'extra_context': {}},
{'no_input': True, 'extra_context': {}},
])
def invalid_kwargs(request):
return request.param
def test_raise_on_invalid_mode(invalid_kwargs):
with pytest.raises(exceptions.InvalidModeException):
main.cookiecutter('foo', replay=True, **invalid_kwargs)
## Instruction:
Add tests for a correct behaviour in cookiecutter.main for replay
## Code After:
import pytest
from cookiecutter import replay, main, exceptions
def test_get_replay_file_name():
"""Make sure that replay.get_file_name generates a valid json file path."""
assert replay.get_file_name('foo', 'bar') == 'foo/bar.json'
@pytest.fixture(params=[
{'no_input': True},
{'extra_context': {}},
{'no_input': True, 'extra_context': {}},
])
def invalid_kwargs(request):
return request.param
def test_raise_on_invalid_mode(invalid_kwargs):
with pytest.raises(exceptions.InvalidModeException):
main.cookiecutter('foo', replay=True, **invalid_kwargs)
def test_main_does_not_invoke_dump_but_load(mocker):
mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
mock_replay_dump = mocker.patch('cookiecutter.main.dump')
mock_replay_load = mocker.patch('cookiecutter.main.load')
main.cookiecutter('foobar', replay=True)
assert not mock_prompt.called
assert not mock_gen_context.called
assert not mock_replay_dump.called
assert mock_replay_load.called
assert mock_gen_files.called
def test_main_does_not_invoke_load_but_dump(mocker):
mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
mock_replay_dump = mocker.patch('cookiecutter.main.dump')
mock_replay_load = mocker.patch('cookiecutter.main.load')
main.cookiecutter('foobar', replay=False)
assert mock_prompt.called
assert mock_gen_context.called
assert mock_replay_dump.called
assert not mock_replay_load.called
assert mock_gen_files.called
|
import pytest
from cookiecutter import replay, main, exceptions
def test_get_replay_file_name():
"""Make sure that replay.get_file_name generates a valid json file path."""
assert replay.get_file_name('foo', 'bar') == 'foo/bar.json'
@pytest.fixture(params=[
{'no_input': True},
{'extra_context': {}},
{'no_input': True, 'extra_context': {}},
])
def invalid_kwargs(request):
return request.param
def test_raise_on_invalid_mode(invalid_kwargs):
with pytest.raises(exceptions.InvalidModeException):
main.cookiecutter('foo', replay=True, **invalid_kwargs)
+
+
+ def test_main_does_not_invoke_dump_but_load(mocker):
+ mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
+ mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
+ mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
+ mock_replay_dump = mocker.patch('cookiecutter.main.dump')
+ mock_replay_load = mocker.patch('cookiecutter.main.load')
+
+ main.cookiecutter('foobar', replay=True)
+
+ assert not mock_prompt.called
+ assert not mock_gen_context.called
+ assert not mock_replay_dump.called
+ assert mock_replay_load.called
+ assert mock_gen_files.called
+
+
+ def test_main_does_not_invoke_load_but_dump(mocker):
+ mock_prompt = mocker.patch('cookiecutter.main.prompt_for_config')
+ mock_gen_context = mocker.patch('cookiecutter.main.generate_context')
+ mock_gen_files = mocker.patch('cookiecutter.main.generate_files')
+ mock_replay_dump = mocker.patch('cookiecutter.main.dump')
+ mock_replay_load = mocker.patch('cookiecutter.main.load')
+
+ main.cookiecutter('foobar', replay=False)
+
+ assert mock_prompt.called
+ assert mock_gen_context.called
+ assert mock_replay_dump.called
+ assert not mock_replay_load.called
+ assert mock_gen_files.called |
a708645581542822985be2e8778b60f0008d75a6 | Lib/whichdb.py | Lib/whichdb.py | """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
if magic == 0x061561:
return "dbhash"
# Unknown
return ""
| """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
if magic in (0x00061561, 0x61150600):
return "dbhash"
# Unknown
return ""
| Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer. | Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
- if magic == 0x061561:
+ if magic in (0x00061561, 0x61150600):
return "dbhash"
# Unknown
return ""
| Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer. | ## Code Before:
"""Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
if magic == 0x061561:
return "dbhash"
# Unknown
return ""
## Instruction:
Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.
## Code After:
"""Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
if magic in (0x00061561, 0x61150600):
return "dbhash"
# Unknown
return ""
| """Guess which db package to use to open a db file."""
import struct
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or "gdbm") if recognized.
Importing the given module may still fail, and opening the
database using that module may still fail.
"""
# Check for dbm first -- this has a .pag and a .dir file
try:
f = open(filename + ".pag", "rb")
f.close()
f = open(filename + ".dir", "rb")
f.close()
return "dbm"
except IOError:
pass
# See if the file exists, return None if not
try:
f = open(filename, "rb")
except IOError:
return None
# Read the first 4 bytes of the file -- the magic number
s = f.read(4)
f.close()
# Return "" if not at least 4 bytes
if len(s) != 4:
return ""
# Convert to 4-byte int in native byte order -- return "" if impossible
try:
(magic,) = struct.unpack("=l", s)
except struct.error:
return ""
# Check for GNU dbm
if magic == 0x13579ace:
return "gdbm"
# Check for BSD hash
- if magic == 0x061561:
+ if magic in (0x00061561, 0x61150600):
return "dbhash"
# Unknown
return "" |
4636c9394138534fc39cc5bdac373b97919ffd01 | server/info/services.py | server/info/services.py | """info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
queryset = Article.objects.filter(column__uid=uid).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
queryset = Column.objects.all().order_by('-id')
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id')
| """info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
queryset = Article.objects.filter(
column__uid=uid
).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
queryset = Column.objects.all().only('uid', 'name').order_by('-id')
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id')
| Modify django orm filter, add only | Modify django orm filter, add only
| Python | mit | istommao/codingcatweb,istommao/codingcatweb,istommao/codingcatweb | """info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
- queryset = Article.objects.filter(column__uid=uid).order_by('id')
+ queryset = Article.objects.filter(
+ column__uid=uid
+ ).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
- queryset = Column.objects.all().order_by('-id')
+ queryset = Column.objects.all().only('uid', 'name').order_by('-id')
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id')
| Modify django orm filter, add only | ## Code Before:
"""info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
queryset = Article.objects.filter(column__uid=uid).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
queryset = Column.objects.all().order_by('-id')
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id')
## Instruction:
Modify django orm filter, add only
## Code After:
"""info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
queryset = Article.objects.filter(
column__uid=uid
).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
queryset = Column.objects.all().only('uid', 'name').order_by('-id')
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id')
| """info services."""
from info.models import Article, News, Column
def get_column_object(uid):
"""Get column object."""
try:
obj = Column.objects.get(uid=uid)
except Column.DoesNotExist:
obj = None
return obj
def get_articles_by_column(uid):
"""Get_articles_by_column."""
- queryset = Article.objects.filter(column__uid=uid).order_by('id')
+ queryset = Article.objects.filter(
+ column__uid=uid
+ ).order_by('id')
return queryset
def get_columns_queryset():
"""Get_columns_queryset."""
- queryset = Column.objects.all().order_by('-id')
+ queryset = Column.objects.all().only('uid', 'name').order_by('-id')
? ++++++++++++++++++++
return queryset
def get_article_queryset():
"""Get article queryset."""
queryset = Article.objects.all().order_by('-id')
return queryset
def get_article_object(uid):
"""Get article object."""
return Article.objects.get(uid=uid)
def get_news_queryset():
"""Get news queryset."""
return News.objects.all().order_by('-id') |
49749403321d16f14ecf0f6f95d5511e5429d7a2 | actstream/__init__.py | actstream/__init__.py | try:
from actstream.signals import action
except:
pass
import django
__version__ = '1.4.0'
__author__ = 'Asif Saif Uddin, Justin Quick <justquick@gmail.com>'
if django.VERSION < (3, 2):
default_app_config = 'actstream.apps.ActstreamConfig'
| try:
from actstream.signals import action
except:
pass
import django
__version__ = '1.4.0'
__author__ = 'Asif Saif Uddin, Justin Quick <justquick@gmail.com>'
if django.VERSION >= (3, 2):
# The declaration is only needed for older Django versions
pass
else:
default_app_config = 'actstream.apps.ActstreamConfig'
| Fix django app config default | Fix django app config default
| Python | bsd-3-clause | justquick/django-activity-stream,pombredanne/django-activity-stream,pombredanne/django-activity-stream,justquick/django-activity-stream | try:
from actstream.signals import action
except:
pass
import django
__version__ = '1.4.0'
__author__ = 'Asif Saif Uddin, Justin Quick <justquick@gmail.com>'
- if django.VERSION < (3, 2):
+ if django.VERSION >= (3, 2):
+ # The declaration is only needed for older Django versions
+ pass
+ else:
default_app_config = 'actstream.apps.ActstreamConfig'
| Fix django app config default | ## Code Before:
try:
from actstream.signals import action
except:
pass
import django
__version__ = '1.4.0'
__author__ = 'Asif Saif Uddin, Justin Quick <justquick@gmail.com>'
if django.VERSION < (3, 2):
default_app_config = 'actstream.apps.ActstreamConfig'
## Instruction:
Fix django app config default
## Code After:
try:
from actstream.signals import action
except:
pass
import django
__version__ = '1.4.0'
__author__ = 'Asif Saif Uddin, Justin Quick <justquick@gmail.com>'
if django.VERSION >= (3, 2):
# The declaration is only needed for older Django versions
pass
else:
default_app_config = 'actstream.apps.ActstreamConfig'
| try:
from actstream.signals import action
except:
pass
import django
__version__ = '1.4.0'
__author__ = 'Asif Saif Uddin, Justin Quick <justquick@gmail.com>'
- if django.VERSION < (3, 2):
? ^
+ if django.VERSION >= (3, 2):
? ^^
+ # The declaration is only needed for older Django versions
+ pass
+ else:
default_app_config = 'actstream.apps.ActstreamConfig' |
faf067ec4f5189a7a0b12fc78b62373a8f997ac8 | scripts/migration/migrate_index_for_existing_files.py | scripts/migration/migrate_index_for_existing_files.py | import sys
import logging
from website.app import init_app
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Current files will now be updated to be indexed if necessary')
if dry_run:
logger.warn('Dry_run mode')
for file_ in OsfStorageFile.find():
logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name))
if not dry_run:
file_.save()
if __name__ == '__main__':
main()
| import sys
import logging
from website.app import init_app
from website.search import search
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Current files will now be updated to be indexed if necessary')
if dry_run:
logger.warn('Dry_run mode')
for file_ in OsfStorageFile.find():
logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name))
if not dry_run:
search.update_file(file_)
if __name__ == '__main__':
main()
| Change migration to update_file rather than save it | Change migration to update_file rather than save it
| Python | apache-2.0 | billyhunt/osf.io,brianjgeiger/osf.io,zachjanicki/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,abought/osf.io,caseyrygt/osf.io,crcresearch/osf.io,mluo613/osf.io,caneruguz/osf.io,zamattiac/osf.io,danielneis/osf.io,leb2dg/osf.io,kwierman/osf.io,SSJohns/osf.io,aaxelb/osf.io,haoyuchen1992/osf.io,HalcyonChimera/osf.io,amyshi188/osf.io,rdhyee/osf.io,felliott/osf.io,saradbowman/osf.io,chennan47/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,leb2dg/osf.io,mattclark/osf.io,felliott/osf.io,leb2dg/osf.io,binoculars/osf.io,binoculars/osf.io,kch8qx/osf.io,KAsante95/osf.io,alexschiller/osf.io,samchrisinger/osf.io,CenterForOpenScience/osf.io,GageGaskins/osf.io,cslzchen/osf.io,caseyrollins/osf.io,mluke93/osf.io,alexschiller/osf.io,zachjanicki/osf.io,KAsante95/osf.io,danielneis/osf.io,emetsger/osf.io,mluke93/osf.io,haoyuchen1992/osf.io,emetsger/osf.io,jnayak1/osf.io,laurenrevere/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,acshi/osf.io,brandonPurvis/osf.io,HalcyonChimera/osf.io,jnayak1/osf.io,samchrisinger/osf.io,kch8qx/osf.io,mluo613/osf.io,samanehsan/osf.io,wearpants/osf.io,DanielSBrown/osf.io,hmoco/osf.io,caneruguz/osf.io,asanfilippo7/osf.io,baylee-d/osf.io,adlius/osf.io,Johnetordoff/osf.io,acshi/osf.io,Nesiehr/osf.io,alexschiller/osf.io,caseyrygt/osf.io,chrisseto/osf.io,abought/osf.io,aaxelb/osf.io,doublebits/osf.io,DanielSBrown/osf.io,caneruguz/osf.io,SSJohns/osf.io,GageGaskins/osf.io,emetsger/osf.io,felliott/osf.io,kch8qx/osf.io,TomHeatwole/osf.io,rdhyee/osf.io,Ghalko/osf.io,brandonPurvis/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,doublebits/osf.io,ZobairAlijan/osf.io,Johnetordoff/osf.io,Ghalko/osf.io,acshi/osf.io,Johnetordoff/osf.io,brandonPurvis/osf.io,monikagrabowska/osf.io,crcresearch/osf.io,samanehsan/osf.io,laurenrevere/osf.io,wearpants/osf.io,samanehsan/osf.io,laurenrevere/osf.io,SSJohns/osf.io,pattisdr/osf.io,acshi/osf.io,felliott/osf.io,TomHeatwole/osf.io,danielneis/osf.io,monikagrabowska/osf.io,doublebits/osf.io,TomHeatwole/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,caseyrygt/osf.io,SSJohns/osf.io,ZobairAlijan/osf.io,ticklemepierce/osf.io,crcresearch/osf.io,brandonPurvis/osf.io,zamattiac/osf.io,mattclark/osf.io,asanfilippo7/osf.io,amyshi188/osf.io,emetsger/osf.io,mfraezz/osf.io,zachjanicki/osf.io,billyhunt/osf.io,jnayak1/osf.io,mluo613/osf.io,abought/osf.io,GageGaskins/osf.io,kch8qx/osf.io,erinspace/osf.io,doublebits/osf.io,hmoco/osf.io,monikagrabowska/osf.io,adlius/osf.io,KAsante95/osf.io,RomanZWang/osf.io,mluo613/osf.io,asanfilippo7/osf.io,icereval/osf.io,danielneis/osf.io,caseyrygt/osf.io,DanielSBrown/osf.io,sloria/osf.io,ZobairAlijan/osf.io,aaxelb/osf.io,cwisecarver/osf.io,chrisseto/osf.io,samanehsan/osf.io,chennan47/osf.io,zachjanicki/osf.io,adlius/osf.io,chrisseto/osf.io,doublebits/osf.io,RomanZWang/osf.io,abought/osf.io,cslzchen/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,KAsante95/osf.io,cwisecarver/osf.io,amyshi188/osf.io,Nesiehr/osf.io,ticklemepierce/osf.io,mattclark/osf.io,CenterForOpenScience/osf.io,amyshi188/osf.io,chennan47/osf.io,TomBaxter/osf.io,jnayak1/osf.io,ticklemepierce/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,brianjgeiger/osf.io,samchrisinger/osf.io,ZobairAlijan/osf.io,saradbowman/osf.io,wearpants/osf.io,cslzchen/osf.io,adlius/osf.io,billyhunt/osf.io,alexschiller/osf.io,rdhyee/osf.io,zamattiac/osf.io,CenterForOpenScience/osf.io,mluke93/osf.io,pattisdr/osf.io,alexschiller/osf.io,erinspace/osf.io,rdhyee/osf.io,RomanZWang/osf.io,GageGaskins/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,RomanZWang/osf.io,mfraezz/osf.io,icereval/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,binoculars/osf.io,KAsante95/osf.io,Ghalko/osf.io,Ghalko/osf.io,Nesiehr/osf.io,billyhunt/osf.io,ticklemepierce/osf.io,TomBaxter/osf.io,hmoco/osf.io,asanfilippo7/osf.io,cwisecarver/osf.io,baylee-d/osf.io,icereval/osf.io,haoyuchen1992/osf.io,kwierman/osf.io,DanielSBrown/osf.io,brianjgeiger/osf.io,TomHeatwole/osf.io,sloria/osf.io,mfraezz/osf.io,cslzchen/osf.io,hmoco/osf.io,zamattiac/osf.io,erinspace/osf.io,wearpants/osf.io,aaxelb/osf.io,mluke93/osf.io,sloria/osf.io,acshi/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,kwierman/osf.io,caneruguz/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,billyhunt/osf.io | import sys
import logging
from website.app import init_app
+ from website.search import search
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Current files will now be updated to be indexed if necessary')
if dry_run:
logger.warn('Dry_run mode')
for file_ in OsfStorageFile.find():
logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name))
if not dry_run:
- file_.save()
+ search.update_file(file_)
if __name__ == '__main__':
main()
| Change migration to update_file rather than save it | ## Code Before:
import sys
import logging
from website.app import init_app
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Current files will now be updated to be indexed if necessary')
if dry_run:
logger.warn('Dry_run mode')
for file_ in OsfStorageFile.find():
logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name))
if not dry_run:
file_.save()
if __name__ == '__main__':
main()
## Instruction:
Change migration to update_file rather than save it
## Code After:
import sys
import logging
from website.app import init_app
from website.search import search
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Current files will now be updated to be indexed if necessary')
if dry_run:
logger.warn('Dry_run mode')
for file_ in OsfStorageFile.find():
logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name))
if not dry_run:
search.update_file(file_)
if __name__ == '__main__':
main()
| import sys
import logging
from website.app import init_app
+ from website.search import search
from website.files.models.osfstorage import OsfStorageFile
logger = logging.getLogger(__name__)
def main():
init_app(routes=False)
dry_run = 'dry' in sys.argv
logger.warn('Current files will now be updated to be indexed if necessary')
if dry_run:
logger.warn('Dry_run mode')
for file_ in OsfStorageFile.find():
logger.info('File with _id {0} and name {1} has been saved.'.format(file_._id, file_.name))
if not dry_run:
- file_.save()
+ search.update_file(file_)
if __name__ == '__main__':
main() |
4631a2192b24675f61f4eec5ab68e273ea47cca8 | sklearn/svm/sparse/base.py | sklearn/svm/sparse/base.py | import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
return super(SparseBaseLibSVM, self).fit(X, y, sample_weight)
| import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
return super(SparseBaseLibSVM, self).fit(X, y,
sample_weight=sample_weight)
| FIX sparse OneClassSVM was using the wrong parameter | FIX sparse OneClassSVM was using the wrong parameter
| Python | bsd-3-clause | rishikksh20/scikit-learn,kmike/scikit-learn,JPFrancoia/scikit-learn,B3AU/waveTree,themrmax/scikit-learn,vybstat/scikit-learn,kaichogami/scikit-learn,IndraVikas/scikit-learn,walterreade/scikit-learn,tosolveit/scikit-learn,macks22/scikit-learn,AlexRobson/scikit-learn,heli522/scikit-learn,robbymeals/scikit-learn,xuewei4d/scikit-learn,zhenv5/scikit-learn,theoryno3/scikit-learn,themrmax/scikit-learn,alexsavio/scikit-learn,Srisai85/scikit-learn,wanggang3333/scikit-learn,walterreade/scikit-learn,rohanp/scikit-learn,loli/semisupervisedforests,luo66/scikit-learn,eg-zhang/scikit-learn,mjudsp/Tsallis,adamgreenhall/scikit-learn,jlegendary/scikit-learn,saiwing-yeung/scikit-learn,liangz0707/scikit-learn,hlin117/scikit-learn,shangwuhencc/scikit-learn,xubenben/scikit-learn,sergeyf/scikit-learn,dingocuster/scikit-learn,billy-inn/scikit-learn,IssamLaradji/scikit-learn,dsullivan7/scikit-learn,moutai/scikit-learn,toastedcornflakes/scikit-learn,xwolf12/scikit-learn,smartscheduling/scikit-learn-categorical-tree,NunoEdgarGub1/scikit-learn,kagayakidan/scikit-learn,phdowling/scikit-learn,fredhusser/scikit-learn,wzbozon/scikit-learn,xubenben/scikit-learn,jereze/scikit-learn,DonBeo/scikit-learn,bnaul/scikit-learn,jmschrei/scikit-learn,Garrett-R/scikit-learn,sumspr/scikit-learn,zaxtax/scikit-learn,CforED/Machine-Learning,Adai0808/scikit-learn,costypetrisor/scikit-learn,appapantula/scikit-learn,arabenjamin/scikit-learn,Adai0808/scikit-learn,alexsavio/scikit-learn,nrhine1/scikit-learn,nhejazi/scikit-learn,samuel1208/scikit-learn,plissonf/scikit-learn,ClimbsRocks/scikit-learn,q1ang/scikit-learn,hlin117/scikit-learn,vivekmishra1991/scikit-learn,IssamLaradji/scikit-learn,DonBeo/scikit-learn,spallavolu/scikit-learn,xwolf12/scikit-learn,fyffyt/scikit-learn,macks22/scikit-learn,vshtanko/scikit-learn,gclenaghan/scikit-learn,herilalaina/scikit-learn,Myasuka/scikit-learn,hsuantien/scikit-learn,hdmetor/scikit-learn,ilyes14/scikit-learn,stylianos-kampakis/scikit-learn,ngoix/OCRF,marcocaccin/scikit-learn,fbagirov/scikit-learn,sanketloke/scikit-learn,0x0all/scikit-learn,ningchi/scikit-learn,alexeyum/scikit-learn,PatrickChrist/scikit-learn,ilo10/scikit-learn,LiaoPan/scikit-learn,yyjiang/scikit-learn,YinongLong/scikit-learn,justincassidy/scikit-learn,pv/scikit-learn,carrillo/scikit-learn,abhishekkrthakur/scikit-learn,chrsrds/scikit-learn,shikhardb/scikit-learn,hainm/scikit-learn,xiaoxiamii/scikit-learn,djgagne/scikit-learn,devanshdalal/scikit-learn,mwv/scikit-learn,rrohan/scikit-learn,jkarnows/scikit-learn,jorge2703/scikit-learn,xwolf12/scikit-learn,thientu/scikit-learn,ilo10/scikit-learn,vibhorag/scikit-learn,Barmaley-exe/scikit-learn,amueller/scikit-learn,ndingwall/scikit-learn,jmschrei/scikit-learn,ngoix/OCRF,ogrisel/scikit-learn,chrisburr/scikit-learn,abimannans/scikit-learn,ky822/scikit-learn,nmayorov/scikit-learn,aetilley/scikit-learn,ankurankan/scikit-learn,shyamalschandra/scikit-learn,Srisai85/scikit-learn,treycausey/scikit-learn,fabianp/scikit-learn,vortex-ape/scikit-learn,RomainBrault/scikit-learn,fzalkow/scikit-learn,terkkila/scikit-learn,madjelan/scikit-learn,rishikksh20/scikit-learn,Jimmy-Morzaria/scikit-learn,frank-tancf/scikit-learn,devanshdalal/scikit-learn,JPFrancoia/scikit-learn,terkkila/scikit-learn,olologin/scikit-learn,loli/sklearn-ensembletrees,aewhatley/scikit-learn,Djabbz/scikit-learn,hsiaoyi0504/scikit-learn,shyamalschandra/scikit-learn,MartinSavc/scikit-learn,mjgrav2001/scikit-learn,xavierwu/scikit-learn,pythonvietnam/scikit-learn,raghavrv/scikit-learn,michigraber/scikit-learn,khkaminska/scikit-learn,wlamond/scikit-learn,procoder317/scikit-learn,YinongLong/scikit-learn,abimannans/scikit-learn,mwv/scikit-learn,IshankGulati/scikit-learn,lucidfrontier45/scikit-learn,mattgiguere/scikit-learn,olologin/scikit-learn,Djabbz/scikit-learn,xuewei4d/scikit-learn,wanggang3333/scikit-learn,Aasmi/scikit-learn,rsivapr/scikit-learn,liberatorqjw/scikit-learn,vermouthmjl/scikit-learn,quheng/scikit-learn,mlyundin/scikit-learn,rvraghav93/scikit-learn,rohanp/scikit-learn,ChanderG/scikit-learn,pkruskal/scikit-learn,466152112/scikit-learn,ldirer/scikit-learn,alexsavio/scikit-learn,Barmaley-exe/scikit-learn,chrsrds/scikit-learn,mlyundin/scikit-learn,thilbern/scikit-learn,victorbergelin/scikit-learn,jaidevd/scikit-learn,scikit-learn/scikit-learn,ishanic/scikit-learn,harshaneelhg/scikit-learn,yask123/scikit-learn,gotomypc/scikit-learn,potash/scikit-learn,meduz/scikit-learn,glemaitre/scikit-learn,xubenben/scikit-learn,hlin117/scikit-learn,murali-munna/scikit-learn,PrashntS/scikit-learn,mfjb/scikit-learn,vinayak-mehta/scikit-learn,simon-pepin/scikit-learn,ephes/scikit-learn,liberatorqjw/scikit-learn,lenovor/scikit-learn,stylianos-kampakis/scikit-learn,hugobowne/scikit-learn,eg-zhang/scikit-learn,Sentient07/scikit-learn,Lawrence-Liu/scikit-learn,samuel1208/scikit-learn,nomadcube/scikit-learn,espg/scikit-learn,Achuth17/scikit-learn,abimannans/scikit-learn,huzq/scikit-learn,jmschrei/scikit-learn,AlexandreAbraham/scikit-learn,lucidfrontier45/scikit-learn,vybstat/scikit-learn,3manuek/scikit-learn,huzq/scikit-learn,arjoly/scikit-learn,alexeyum/scikit-learn,murali-munna/scikit-learn,AlexRobson/scikit-learn,aabadie/scikit-learn,jayflo/scikit-learn,f3r/scikit-learn,PatrickOReilly/scikit-learn,aflaxman/scikit-learn,q1ang/scikit-learn,russel1237/scikit-learn,Obus/scikit-learn,btabibian/scikit-learn,altairpearl/scikit-learn,fabioticconi/scikit-learn,MechCoder/scikit-learn,CVML/scikit-learn,appapantula/scikit-learn,anurag313/scikit-learn,h2educ/scikit-learn,raghavrv/scikit-learn,krez13/scikit-learn,pv/scikit-learn,3manuek/scikit-learn,ephes/scikit-learn,pianomania/scikit-learn,DSLituiev/scikit-learn,sonnyhu/scikit-learn,Garrett-R/scikit-learn,petosegan/scikit-learn,ndingwall/scikit-learn,q1ang/scikit-learn,btabibian/scikit-learn,pkruskal/scikit-learn,rrohan/scikit-learn,billy-inn/scikit-learn,NelisVerhoef/scikit-learn,shusenl/scikit-learn,3manuek/scikit-learn,ltiao/scikit-learn,trankmichael/scikit-learn,manashmndl/scikit-learn,evgchz/scikit-learn,RayMick/scikit-learn,jjx02230808/project0223,Barmaley-exe/scikit-learn,jzt5132/scikit-learn,rajat1994/scikit-learn,victorbergelin/scikit-learn,anurag313/scikit-learn,ssaeger/scikit-learn,mwv/scikit-learn,qifeigit/scikit-learn,joernhees/scikit-learn,yask123/scikit-learn,ycaihua/scikit-learn,yunfeilu/scikit-learn,siutanwong/scikit-learn,fzalkow/scikit-learn,dhruv13J/scikit-learn,glennq/scikit-learn,dsullivan7/scikit-learn,rsivapr/scikit-learn,xyguo/scikit-learn,larsmans/scikit-learn,mojoboss/scikit-learn,mhdella/scikit-learn,procoder317/scikit-learn,tawsifkhan/scikit-learn,JsNoNo/scikit-learn,ChanChiChoi/scikit-learn,dsquareindia/scikit-learn,cainiaocome/scikit-learn,cauchycui/scikit-learn,shyamalschandra/scikit-learn,Akshay0724/scikit-learn,chrisburr/scikit-learn,smartscheduling/scikit-learn-categorical-tree,Barmaley-exe/scikit-learn,kylerbrown/scikit-learn,robin-lai/scikit-learn,rahul-c1/scikit-learn,jayflo/scikit-learn,rsivapr/scikit-learn,clemkoa/scikit-learn,pnedunuri/scikit-learn,xuewei4d/scikit-learn,beepee14/scikit-learn,elkingtonmcb/scikit-learn,cwu2011/scikit-learn,Vimos/scikit-learn,MatthieuBizien/scikit-learn,cl4rke/scikit-learn,jzt5132/scikit-learn,rexshihaoren/scikit-learn,procoder317/scikit-learn,kaichogami/scikit-learn,davidgbe/scikit-learn,jjx02230808/project0223,ivannz/scikit-learn,jpautom/scikit-learn,Achuth17/scikit-learn,akionakamura/scikit-learn,mayblue9/scikit-learn,belltailjp/scikit-learn,nhejazi/scikit-learn,frank-tancf/scikit-learn,yanlend/scikit-learn,CVML/scikit-learn,rrohan/scikit-learn,RPGOne/scikit-learn,herilalaina/scikit-learn,pratapvardhan/scikit-learn,abhishekgahlot/scikit-learn,manhhomienbienthuy/scikit-learn,aabadie/scikit-learn,bthirion/scikit-learn,mehdidc/scikit-learn,giorgiop/scikit-learn,eickenberg/scikit-learn,nelson-liu/scikit-learn,justincassidy/scikit-learn,CVML/scikit-learn,jakirkham/scikit-learn,sonnyhu/scikit-learn,samuel1208/scikit-learn,wazeerzulfikar/scikit-learn,loli/sklearn-ensembletrees,samzhang111/scikit-learn,anurag313/scikit-learn,madjelan/scikit-learn,MartinDelzant/scikit-learn,q1ang/scikit-learn,macks22/scikit-learn,imaculate/scikit-learn,JosmanPS/scikit-learn,mattgiguere/scikit-learn,CforED/Machine-Learning,CforED/Machine-Learning,Windy-Ground/scikit-learn,shahankhatch/scikit-learn,lin-credible/scikit-learn,jlegendary/scikit-learn,carrillo/scikit-learn,ltiao/scikit-learn,pianomania/scikit-learn,jorge2703/scikit-learn,Garrett-R/scikit-learn,hsuantien/scikit-learn,henrykironde/scikit-learn,466152112/scikit-learn,deepesch/scikit-learn,siutanwong/scikit-learn,schets/scikit-learn,ashhher3/scikit-learn,depet/scikit-learn,jayflo/scikit-learn,RPGOne/scikit-learn,beepee14/scikit-learn,quheng/scikit-learn,henrykironde/scikit-learn,rexshihaoren/scikit-learn,PrashntS/scikit-learn,mjudsp/Tsallis,robin-lai/scikit-learn,hugobowne/scikit-learn,liberatorqjw/scikit-learn,OshynSong/scikit-learn,justincassidy/scikit-learn,tomlof/scikit-learn,hrjn/scikit-learn,mikebenfield/scikit-learn,ClimbsRocks/scikit-learn,mblondel/scikit-learn,jereze/scikit-learn,vshtanko/scikit-learn,lbishal/scikit-learn,pkruskal/scikit-learn,OshynSong/scikit-learn,hsuantien/scikit-learn,sarahgrogan/scikit-learn,petosegan/scikit-learn,ChanChiChoi/scikit-learn,gotomypc/scikit-learn,treycausey/scikit-learn,jblackburne/scikit-learn,Jimmy-Morzaria/scikit-learn,ishanic/scikit-learn,spallavolu/scikit-learn,ky822/scikit-learn,aetilley/scikit-learn,gclenaghan/scikit-learn,themrmax/scikit-learn,B3AU/waveTree,Clyde-fare/scikit-learn,tmhm/scikit-learn,yonglehou/scikit-learn,hdmetor/scikit-learn,mugizico/scikit-learn,appapantula/scikit-learn,vibhorag/scikit-learn,vivekmishra1991/scikit-learn,anntzer/scikit-learn,NelisVerhoef/scikit-learn,voxlol/scikit-learn,plissonf/scikit-learn,466152112/scikit-learn,vshtanko/scikit-learn,cl4rke/scikit-learn,aabadie/scikit-learn,lbishal/scikit-learn,trungnt13/scikit-learn,abhishekgahlot/scikit-learn,chrisburr/scikit-learn,henrykironde/scikit-learn,NelisVerhoef/scikit-learn,mhue/scikit-learn,loli/sklearn-ensembletrees,djgagne/scikit-learn,zorroblue/scikit-learn,sarahgrogan/scikit-learn,zorojean/scikit-learn,zuku1985/scikit-learn,hsiaoyi0504/scikit-learn,yyjiang/scikit-learn,altairpearl/scikit-learn,icdishb/scikit-learn,xzh86/scikit-learn,ilyes14/scikit-learn,akionakamura/scikit-learn,tawsifkhan/scikit-learn,rohanp/scikit-learn,sinhrks/scikit-learn,roxyboy/scikit-learn,yask123/scikit-learn,mxjl620/scikit-learn,AIML/scikit-learn,ogrisel/scikit-learn,lesteve/scikit-learn,vigilv/scikit-learn,nikitasingh981/scikit-learn,shahankhatch/scikit-learn,eickenberg/scikit-learn,DSLituiev/scikit-learn,arahuja/scikit-learn,Sentient07/scikit-learn,RomainBrault/scikit-learn,khkaminska/scikit-learn,rishikksh20/scikit-learn,yyjiang/scikit-learn,mjgrav2001/scikit-learn,ldirer/scikit-learn,zaxtax/scikit-learn,mayblue9/scikit-learn,meduz/scikit-learn,PatrickChrist/scikit-learn,icdishb/scikit-learn,massmutual/scikit-learn,pianomania/scikit-learn,ChanderG/scikit-learn,Myasuka/scikit-learn,chrsrds/scikit-learn,madjelan/scikit-learn,sergeyf/scikit-learn,fabianp/scikit-learn,IndraVikas/scikit-learn,iismd17/scikit-learn,iismd17/scikit-learn,harshaneelhg/scikit-learn,terkkila/scikit-learn,scikit-learn/scikit-learn,vinayak-mehta/scikit-learn,mugizico/scikit-learn,rexshihaoren/scikit-learn,xuewei4d/scikit-learn,poryfly/scikit-learn,phdowling/scikit-learn,elkingtonmcb/scikit-learn,bigdataelephants/scikit-learn,kylerbrown/scikit-learn,arjoly/scikit-learn,potash/scikit-learn,MatthieuBizien/scikit-learn,ngoix/OCRF,pompiduskus/scikit-learn,bhargav/scikit-learn,lin-credible/scikit-learn,joshloyal/scikit-learn,ElDeveloper/scikit-learn,ZENGXH/scikit-learn,adamgreenhall/scikit-learn,fbagirov/scikit-learn,clemkoa/scikit-learn,PrashntS/scikit-learn,rohanp/scikit-learn,adamgreenhall/scikit-learn,RomainBrault/scikit-learn,joernhees/scikit-learn,petosegan/scikit-learn,vybstat/scikit-learn,gclenaghan/scikit-learn,espg/scikit-learn,jmetzen/scikit-learn,xiaoxiamii/scikit-learn,cwu2011/scikit-learn,cainiaocome/scikit-learn,aetilley/scikit-learn,mblondel/scikit-learn,wlamond/scikit-learn,IshankGulati/scikit-learn,ngoix/OCRF,liberatorqjw/scikit-learn,costypetrisor/scikit-learn,alvarofierroclavero/scikit-learn,MatthieuBizien/scikit-learn,sumspr/scikit-learn,mattilyra/scikit-learn,ilyes14/scikit-learn,RayMick/scikit-learn,equialgo/scikit-learn,mrshu/scikit-learn,mayblue9/scikit-learn,victorbergelin/scikit-learn,rajat1994/scikit-learn,fyffyt/scikit-learn,akionakamura/scikit-learn,kevin-intel/scikit-learn,toastedcornflakes/scikit-learn,xyguo/scikit-learn,mattilyra/scikit-learn,mugizico/scikit-learn,loli/semisupervisedforests,kashif/scikit-learn,jmschrei/scikit-learn,hugobowne/scikit-learn,nomadcube/scikit-learn,ogrisel/scikit-learn,mattilyra/scikit-learn,jblackburne/scikit-learn,jzt5132/scikit-learn,jzt5132/scikit-learn,nvoron23/scikit-learn,khkaminska/scikit-learn,sinhrks/scikit-learn,jm-begon/scikit-learn,ElDeveloper/scikit-learn,RayMick/scikit-learn,ky822/scikit-learn,michigraber/scikit-learn,hrjn/scikit-learn,TomDLT/scikit-learn,0asa/scikit-learn,ChanderG/scikit-learn,AlexandreAbraham/scikit-learn,h2educ/scikit-learn,xavierwu/scikit-learn,lbishal/scikit-learn,meduz/scikit-learn,Garrett-R/scikit-learn,xzh86/scikit-learn,r-mart/scikit-learn,robbymeals/scikit-learn,massmutual/scikit-learn,siutanwong/scikit-learn,waterponey/scikit-learn,Nyker510/scikit-learn,Akshay0724/scikit-learn,simon-pepin/scikit-learn,DonBeo/scikit-learn,sarahgrogan/scikit-learn,cybernet14/scikit-learn,zaxtax/scikit-learn,toastedcornflakes/scikit-learn,jorik041/scikit-learn,evgchz/scikit-learn,arahuja/scikit-learn,Akshay0724/scikit-learn,imaculate/scikit-learn,pnedunuri/scikit-learn,kaichogami/scikit-learn,nikitasingh981/scikit-learn,poryfly/scikit-learn,ycaihua/scikit-learn,gotomypc/scikit-learn,ycaihua/scikit-learn,kylerbrown/scikit-learn,fengzhyuan/scikit-learn,AnasGhrab/scikit-learn,pnedunuri/scikit-learn,rexshihaoren/scikit-learn,0x0all/scikit-learn,AlexRobson/scikit-learn,nvoron23/scikit-learn,TomDLT/scikit-learn,voxlol/scikit-learn,AlexanderFabisch/scikit-learn,UNR-AERIAL/scikit-learn,beepee14/scikit-learn,cwu2011/scikit-learn,mojoboss/scikit-learn,Achuth17/scikit-learn,bthirion/scikit-learn,bthirion/scikit-learn,jkarnows/scikit-learn,liyu1990/sklearn,anirudhjayaraman/scikit-learn,bikong2/scikit-learn,0asa/scikit-learn,xzh86/scikit-learn,vinayak-mehta/scikit-learn,dingocuster/scikit-learn,jlegendary/scikit-learn,wazeerzulfikar/scikit-learn,anntzer/scikit-learn,abhishekgahlot/scikit-learn,bigdataelephants/scikit-learn,IssamLaradji/scikit-learn,Aasmi/scikit-learn,huzq/scikit-learn,untom/scikit-learn,ssaeger/scikit-learn,jjx02230808/project0223,mattilyra/scikit-learn,Obus/scikit-learn,etkirsch/scikit-learn,rajat1994/scikit-learn,jseabold/scikit-learn,MechCoder/scikit-learn,PatrickOReilly/scikit-learn,themrmax/scikit-learn,Srisai85/scikit-learn,AlexanderFabisch/scikit-learn,larsmans/scikit-learn,hitszxp/scikit-learn,altairpearl/scikit-learn,depet/scikit-learn,mhue/scikit-learn,lucidfrontier45/scikit-learn,untom/scikit-learn,Windy-Ground/scikit-learn,ishanic/scikit-learn,kevin-intel/scikit-learn,MartinSavc/scikit-learn,xavierwu/scikit-learn,glouppe/scikit-learn,larsmans/scikit-learn,dsullivan7/scikit-learn,PatrickOReilly/scikit-learn,trungnt13/scikit-learn,alexeyum/scikit-learn,zorojean/scikit-learn,marcocaccin/scikit-learn,yonglehou/scikit-learn,vortex-ape/scikit-learn,shangwuhencc/scikit-learn,rsivapr/scikit-learn,equialgo/scikit-learn,shenzebang/scikit-learn,shusenl/scikit-learn,waterponey/scikit-learn,fabioticconi/scikit-learn,mehdidc/scikit-learn,hitszxp/scikit-learn,nesterione/scikit-learn,aminert/scikit-learn,jm-begon/scikit-learn,jakirkham/scikit-learn,Nyker510/scikit-learn,poryfly/scikit-learn,ZENGXH/scikit-learn,PatrickChrist/scikit-learn,shusenl/scikit-learn,joernhees/scikit-learn,rahul-c1/scikit-learn,eickenberg/scikit-learn,liyu1990/sklearn,ZENGXH/scikit-learn,0x0all/scikit-learn,mfjb/scikit-learn,ChanChiChoi/scikit-learn,RachitKansal/scikit-learn,ilyes14/scikit-learn,anirudhjayaraman/scikit-learn,pythonvietnam/scikit-learn,giorgiop/scikit-learn,sumspr/scikit-learn,scikit-learn/scikit-learn,andaag/scikit-learn,nesterione/scikit-learn,xavierwu/scikit-learn,LiaoPan/scikit-learn,plissonf/scikit-learn,chrsrds/scikit-learn,BiaDarkia/scikit-learn,yunfeilu/scikit-learn,jakobworldpeace/scikit-learn,jmetzen/scikit-learn,waterponey/scikit-learn,dingocuster/scikit-learn,nhejazi/scikit-learn,Jimmy-Morzaria/scikit-learn,yyjiang/scikit-learn,CVML/scikit-learn,jseabold/scikit-learn,belltailjp/scikit-learn,imaculate/scikit-learn,ankurankan/scikit-learn,carrillo/scikit-learn,shangwuhencc/scikit-learn,zorroblue/scikit-learn,TomDLT/scikit-learn,fengzhyuan/scikit-learn,cybernet14/scikit-learn,abhishekkrthakur/scikit-learn,yonglehou/scikit-learn,mattilyra/scikit-learn,AIML/scikit-learn,mayblue9/scikit-learn,ephes/scikit-learn,arabenjamin/scikit-learn,dsquareindia/scikit-learn,depet/scikit-learn,manhhomienbienthuy/scikit-learn,kevin-intel/scikit-learn,manashmndl/scikit-learn,nrhine1/scikit-learn,Clyde-fare/scikit-learn,yonglehou/scikit-learn,ashhher3/scikit-learn,mjudsp/Tsallis,deepesch/scikit-learn,kagayakidan/scikit-learn,anirudhjayaraman/scikit-learn,ivannz/scikit-learn,RPGOne/scikit-learn,arabenjamin/scikit-learn,nvoron23/scikit-learn,Clyde-fare/scikit-learn,clemkoa/scikit-learn,pompiduskus/scikit-learn,tomlof/scikit-learn,Vimos/scikit-learn,sarahgrogan/scikit-learn,fzalkow/scikit-learn,MohammedWasim/scikit-learn,eg-zhang/scikit-learn,etkirsch/scikit-learn,mikebenfield/scikit-learn,treycausey/scikit-learn,thilbern/scikit-learn,3manuek/scikit-learn,mxjl620/scikit-learn,mfjb/scikit-learn,qifeigit/scikit-learn,voxlol/scikit-learn,AlexandreAbraham/scikit-learn,kagayakidan/scikit-learn,glemaitre/scikit-learn,maheshakya/scikit-learn,alexsavio/scikit-learn,Clyde-fare/scikit-learn,pypot/scikit-learn,ycaihua/scikit-learn,mojoboss/scikit-learn,huobaowangxi/scikit-learn,ZenDevelopmentSystems/scikit-learn,wzbozon/scikit-learn,B3AU/waveTree,siutanwong/scikit-learn,nesterione/scikit-learn,betatim/scikit-learn,plissonf/scikit-learn,rahul-c1/scikit-learn,zhenv5/scikit-learn,xiaoxiamii/scikit-learn,evgchz/scikit-learn,nelson-liu/scikit-learn,robin-lai/scikit-learn,aflaxman/scikit-learn,iismd17/scikit-learn,glemaitre/scikit-learn,fredhusser/scikit-learn,zuku1985/scikit-learn,idlead/scikit-learn,bthirion/scikit-learn,loli/semisupervisedforests,vortex-ape/scikit-learn,pratapvardhan/scikit-learn,ningchi/scikit-learn,sonnyhu/scikit-learn,jorge2703/scikit-learn,cybernet14/scikit-learn,nikitasingh981/scikit-learn,Windy-Ground/scikit-learn,shikhardb/scikit-learn,appapantula/scikit-learn,abhishekkrthakur/scikit-learn,fabianp/scikit-learn,B3AU/waveTree,DonBeo/scikit-learn,trankmichael/scikit-learn,zorroblue/scikit-learn,JeanKossaifi/scikit-learn,kashif/scikit-learn,spallavolu/scikit-learn,mhdella/scikit-learn,heli522/scikit-learn,ldirer/scikit-learn,AlexRobson/scikit-learn,ashhher3/scikit-learn,michigraber/scikit-learn,ssaeger/scikit-learn,arjoly/scikit-learn,nikitasingh981/scikit-learn,zhenv5/scikit-learn,thientu/scikit-learn,espg/scikit-learn,Djabbz/scikit-learn,AlexandreAbraham/scikit-learn,jaidevd/scikit-learn,mblondel/scikit-learn,lazywei/scikit-learn,ssaeger/scikit-learn,BiaDarkia/scikit-learn,henrykironde/scikit-learn,glemaitre/scikit-learn,djgagne/scikit-learn,qifeigit/scikit-learn,elkingtonmcb/scikit-learn,ZENGXH/scikit-learn,vivekmishra1991/scikit-learn,Aasmi/scikit-learn,fabianp/scikit-learn,lesteve/scikit-learn,LohithBlaze/scikit-learn,belltailjp/scikit-learn,phdowling/scikit-learn,pythonvietnam/scikit-learn,Achuth17/scikit-learn,Jimmy-Morzaria/scikit-learn,HolgerPeters/scikit-learn,sanketloke/scikit-learn,Srisai85/scikit-learn,MechCoder/scikit-learn,jm-begon/scikit-learn,maheshakya/scikit-learn,simon-pepin/scikit-learn,kevin-intel/scikit-learn,manashmndl/scikit-learn,dingocuster/scikit-learn,fengzhyuan/scikit-learn,giorgiop/scikit-learn,vibhorag/scikit-learn,ningchi/scikit-learn,loli/semisupervisedforests,HolgerPeters/scikit-learn,kmike/scikit-learn,jblackburne/scikit-learn,walterreade/scikit-learn,ivannz/scikit-learn,mattgiguere/scikit-learn,lenovor/scikit-learn,Titan-C/scikit-learn,untom/scikit-learn,betatim/scikit-learn,bikong2/scikit-learn,glennq/scikit-learn,hrjn/scikit-learn,voxlol/scikit-learn,shikhardb/scikit-learn,fabioticconi/scikit-learn,schets/scikit-learn,shikhardb/scikit-learn,florian-f/sklearn,amueller/scikit-learn,AlexanderFabisch/scikit-learn,quheng/scikit-learn,Vimos/scikit-learn,Akshay0724/scikit-learn,beepee14/scikit-learn,h2educ/scikit-learn,fredhusser/scikit-learn,h2educ/scikit-learn,robin-lai/scikit-learn,MohammedWasim/scikit-learn,jm-begon/scikit-learn,fzalkow/scikit-learn,henridwyer/scikit-learn,treycausey/scikit-learn,ltiao/scikit-learn,hsiaoyi0504/scikit-learn,rishikksh20/scikit-learn,costypetrisor/scikit-learn,waterponey/scikit-learn,procoder317/scikit-learn,ilo10/scikit-learn,luo66/scikit-learn,lazywei/scikit-learn,RachitKansal/scikit-learn,Lawrence-Liu/scikit-learn,pianomania/scikit-learn,abimannans/scikit-learn,huobaowangxi/scikit-learn,xzh86/scikit-learn,ChanChiChoi/scikit-learn,yanlend/scikit-learn,wazeerzulfikar/scikit-learn,jakobworldpeace/scikit-learn,AnasGhrab/scikit-learn,abhishekgahlot/scikit-learn,tdhopper/scikit-learn,lucidfrontier45/scikit-learn,tomlof/scikit-learn,anntzer/scikit-learn,sergeyf/scikit-learn,shahankhatch/scikit-learn,0asa/scikit-learn,andaag/scikit-learn,andaag/scikit-learn,krez13/scikit-learn,espg/scikit-learn,JeanKossaifi/scikit-learn,Nyker510/scikit-learn,Fireblend/scikit-learn,qifeigit/scikit-learn,Obus/scikit-learn,bnaul/scikit-learn,jlegendary/scikit-learn,marcocaccin/scikit-learn,MartinSavc/scikit-learn,DSLituiev/scikit-learn,madjelan/scikit-learn,krez13/scikit-learn,zihua/scikit-learn,russel1237/scikit-learn,alexeyum/scikit-learn,ZenDevelopmentSystems/scikit-learn,Garrett-R/scikit-learn,jmetzen/scikit-learn,cl4rke/scikit-learn,bnaul/scikit-learn,pratapvardhan/scikit-learn,nomadcube/scikit-learn,etkirsch/scikit-learn,frank-tancf/scikit-learn,anntzer/scikit-learn,nmayorov/scikit-learn,MohammedWasim/scikit-learn,evgchz/scikit-learn,samuel1208/scikit-learn,massmutual/scikit-learn,glouppe/scikit-learn,akionakamura/scikit-learn,larsmans/scikit-learn,LohithBlaze/scikit-learn,sanketloke/scikit-learn,0x0all/scikit-learn,glouppe/scikit-learn,mikebenfield/scikit-learn,aetilley/scikit-learn,florian-f/sklearn,IshankGulati/scikit-learn,cwu2011/scikit-learn,raghavrv/scikit-learn,MohammedWasim/scikit-learn,wlamond/scikit-learn,mjudsp/Tsallis,aflaxman/scikit-learn,AnasGhrab/scikit-learn,imaculate/scikit-learn,macks22/scikit-learn,rajat1994/scikit-learn,harshaneelhg/scikit-learn,simon-pepin/scikit-learn,cybernet14/scikit-learn,mehdidc/scikit-learn,lin-credible/scikit-learn,vermouthmjl/scikit-learn,hainm/scikit-learn,vinayak-mehta/scikit-learn,xubenben/scikit-learn,luo66/scikit-learn,trungnt13/scikit-learn,henridwyer/scikit-learn,andrewnc/scikit-learn,fbagirov/scikit-learn,lin-credible/scikit-learn,BiaDarkia/scikit-learn,UNR-AERIAL/scikit-learn,jorik041/scikit-learn,Titan-C/scikit-learn,AIML/scikit-learn,B3AU/waveTree,poryfly/scikit-learn,hugobowne/scikit-learn,alvarofierroclavero/scikit-learn,equialgo/scikit-learn,maheshakya/scikit-learn,mwv/scikit-learn,ilo10/scikit-learn,vermouthmjl/scikit-learn,vortex-ape/scikit-learn,dsquareindia/scikit-learn,victorbergelin/scikit-learn,smartscheduling/scikit-learn-categorical-tree,zihua/scikit-learn,mxjl620/scikit-learn,AnasGhrab/scikit-learn,btabibian/scikit-learn,moutai/scikit-learn,davidgbe/scikit-learn,bigdataelephants/scikit-learn,bikong2/scikit-learn,aewhatley/scikit-learn,JosmanPS/scikit-learn,eickenberg/scikit-learn,yask123/scikit-learn,mlyundin/scikit-learn,ndingwall/scikit-learn,Obus/scikit-learn,massmutual/scikit-learn,nrhine1/scikit-learn,Sentient07/scikit-learn,heli522/scikit-learn,kmike/scikit-learn,0x0all/scikit-learn,mattgiguere/scikit-learn,nmayorov/scikit-learn,khkaminska/scikit-learn,JsNoNo/scikit-learn,RPGOne/scikit-learn,MatthieuBizien/scikit-learn,arahuja/scikit-learn,MartinSavc/scikit-learn,pypot/scikit-learn,smartscheduling/scikit-learn-categorical-tree,TomDLT/scikit-learn,henridwyer/scikit-learn,liyu1990/sklearn,CforED/Machine-Learning,tmhm/scikit-learn,yunfeilu/scikit-learn,joshloyal/scikit-learn,vybstat/scikit-learn,betatim/scikit-learn,hitszxp/scikit-learn,zuku1985/scikit-learn,hsiaoyi0504/scikit-learn,gclenaghan/scikit-learn,billy-inn/scikit-learn,lesteve/scikit-learn,vibhorag/scikit-learn,mfjb/scikit-learn,bhargav/scikit-learn,pkruskal/scikit-learn,kjung/scikit-learn,betatim/scikit-learn,thilbern/scikit-learn,JPFrancoia/scikit-learn,ClimbsRocks/scikit-learn,PrashntS/scikit-learn,loli/sklearn-ensembletrees,ahoyosid/scikit-learn,luo66/scikit-learn,0asa/scikit-learn,equialgo/scikit-learn,potash/scikit-learn,pv/scikit-learn,belltailjp/scikit-learn,xwolf12/scikit-learn,bhargav/scikit-learn,pompiduskus/scikit-learn,icdishb/scikit-learn,quheng/scikit-learn,zuku1985/scikit-learn,jblackburne/scikit-learn,maheshakya/scikit-learn,heli522/scikit-learn,Nyker510/scikit-learn,0asa/scikit-learn,hlin117/scikit-learn,jereze/scikit-learn,spallavolu/scikit-learn,henridwyer/scikit-learn,RachitKansal/scikit-learn,f3r/scikit-learn,jereze/scikit-learn,jpautom/scikit-learn,chrisburr/scikit-learn,robbymeals/scikit-learn,IndraVikas/scikit-learn,ankurankan/scikit-learn,dsullivan7/scikit-learn,MartinDelzant/scikit-learn,theoryno3/scikit-learn,bikong2/scikit-learn,anirudhjayaraman/scikit-learn,tawsifkhan/scikit-learn,loli/sklearn-ensembletrees,jakobworldpeace/scikit-learn,lenovor/scikit-learn,NunoEdgarGub1/scikit-learn,lucidfrontier45/scikit-learn,NunoEdgarGub1/scikit-learn,vivekmishra1991/scikit-learn,nesterione/scikit-learn,jkarnows/scikit-learn,murali-munna/scikit-learn,wlamond/scikit-learn,florian-f/sklearn,liangz0707/scikit-learn,alvarofierroclavero/scikit-learn,krez13/scikit-learn,davidgbe/scikit-learn,schets/scikit-learn,fredhusser/scikit-learn,herilalaina/scikit-learn,Myasuka/scikit-learn,walterreade/scikit-learn,tmhm/scikit-learn,vshtanko/scikit-learn,arahuja/scikit-learn,r-mart/scikit-learn,mjudsp/Tsallis,yanlend/scikit-learn,IssamLaradji/scikit-learn,hainm/scikit-learn,meduz/scikit-learn,kjung/scikit-learn,mlyundin/scikit-learn,rvraghav93/scikit-learn,evgchz/scikit-learn,altairpearl/scikit-learn,fabioticconi/scikit-learn,fengzhyuan/scikit-learn,ky822/scikit-learn,glouppe/scikit-learn,wzbozon/scikit-learn,vigilv/scikit-learn,maheshakya/scikit-learn,deepesch/scikit-learn,costypetrisor/scikit-learn,moutai/scikit-learn,adamgreenhall/scikit-learn,zhenv5/scikit-learn,samzhang111/scikit-learn,idlead/scikit-learn,harshaneelhg/scikit-learn,stylianos-kampakis/scikit-learn,OshynSong/scikit-learn,ndingwall/scikit-learn,ClimbsRocks/scikit-learn,Titan-C/scikit-learn,RomainBrault/scikit-learn,Djabbz/scikit-learn,florian-f/sklearn,stylianos-kampakis/scikit-learn,PatrickChrist/scikit-learn,RachitKansal/scikit-learn,bhargav/scikit-learn,roxyboy/scikit-learn,davidgbe/scikit-learn,thilbern/scikit-learn,murali-munna/scikit-learn,olologin/scikit-learn,NunoEdgarGub1/scikit-learn,jjx02230808/project0223,trankmichael/scikit-learn,samzhang111/scikit-learn,zihua/scikit-learn,mrshu/scikit-learn,aminert/scikit-learn,sonnyhu/scikit-learn,liangz0707/scikit-learn,tmhm/scikit-learn,arjoly/scikit-learn,Adai0808/scikit-learn,nomadcube/scikit-learn,xyguo/scikit-learn,kmike/scikit-learn,eg-zhang/scikit-learn,JsNoNo/scikit-learn,hrjn/scikit-learn,Fireblend/scikit-learn,MartinDelzant/scikit-learn,pypot/scikit-learn,r-mart/scikit-learn,aflaxman/scikit-learn,shusenl/scikit-learn,AlexanderFabisch/scikit-learn,RayMick/scikit-learn,shahankhatch/scikit-learn,cainiaocome/scikit-learn,OshynSong/scikit-learn,jaidevd/scikit-learn,russel1237/scikit-learn,carrillo/scikit-learn,JeanKossaifi/scikit-learn,sergeyf/scikit-learn,kylerbrown/scikit-learn,mjgrav2001/scikit-learn,terkkila/scikit-learn,ahoyosid/scikit-learn,cauchycui/scikit-learn,olologin/scikit-learn,JeanKossaifi/scikit-learn,clemkoa/scikit-learn,IndraVikas/scikit-learn,DSLituiev/scikit-learn,shenzebang/scikit-learn,mrshu/scikit-learn,ElDeveloper/scikit-learn,eickenberg/scikit-learn,btabibian/scikit-learn,theoryno3/scikit-learn,JsNoNo/scikit-learn,Sentient07/scikit-learn,wanggang3333/scikit-learn,rahuldhote/scikit-learn,mhdella/scikit-learn,saiwing-yeung/scikit-learn,jakirkham/scikit-learn,etkirsch/scikit-learn,wanggang3333/scikit-learn,sanketloke/scikit-learn,huzq/scikit-learn,shenzebang/scikit-learn,mojoboss/scikit-learn,nmayorov/scikit-learn,schets/scikit-learn,potash/scikit-learn,glennq/scikit-learn,ahoyosid/scikit-learn,alvarofierroclavero/scikit-learn,mblondel/scikit-learn,YinongLong/scikit-learn,lbishal/scikit-learn,toastedcornflakes/scikit-learn,yunfeilu/scikit-learn,depet/scikit-learn,pompiduskus/scikit-learn,IshankGulati/scikit-learn,rrohan/scikit-learn,trungnt13/scikit-learn,ngoix/OCRF,samzhang111/scikit-learn,mrshu/scikit-learn,tdhopper/scikit-learn,ngoix/OCRF,wazeerzulfikar/scikit-learn,Vimos/scikit-learn,hdmetor/scikit-learn,Aasmi/scikit-learn,scikit-learn/scikit-learn,michigraber/scikit-learn,andaag/scikit-learn,cl4rke/scikit-learn,xyguo/scikit-learn,ephes/scikit-learn,ningchi/scikit-learn,mhue/scikit-learn,nvoron23/scikit-learn,rvraghav93/scikit-learn,frank-tancf/scikit-learn,ltiao/scikit-learn,pv/scikit-learn,mjgrav2001/scikit-learn,untom/scikit-learn,ankurankan/scikit-learn,jakobworldpeace/scikit-learn,aminert/scikit-learn,shyamalschandra/scikit-learn,ZenDevelopmentSystems/scikit-learn,hainm/scikit-learn,hdmetor/scikit-learn,JPFrancoia/scikit-learn,ivannz/scikit-learn,LohithBlaze/scikit-learn,kmike/scikit-learn,466152112/scikit-learn,shangwuhencc/scikit-learn,ycaihua/scikit-learn,ChanderG/scikit-learn,amueller/scikit-learn,tawsifkhan/scikit-learn,AIML/scikit-learn,depet/scikit-learn,tosolveit/scikit-learn,manhhomienbienthuy/scikit-learn,zihua/scikit-learn,tosolveit/scikit-learn,Fireblend/scikit-learn,vigilv/scikit-learn,Lawrence-Liu/scikit-learn,LiaoPan/scikit-learn,jorik041/scikit-learn,ishanic/scikit-learn,LiaoPan/scikit-learn,roxyboy/scikit-learn,hsuantien/scikit-learn,bnaul/scikit-learn,jorik041/scikit-learn,iismd17/scikit-learn,kashif/scikit-learn,huobaowangxi/scikit-learn,aabadie/scikit-learn,lazywei/scikit-learn,phdowling/scikit-learn,nhejazi/scikit-learn,abhishekgahlot/scikit-learn,jmetzen/scikit-learn,thientu/scikit-learn,BiaDarkia/scikit-learn,fyffyt/scikit-learn,zorojean/scikit-learn,Windy-Ground/scikit-learn,ashhher3/scikit-learn,tdhopper/scikit-learn,mrshu/scikit-learn,moutai/scikit-learn,kagayakidan/scikit-learn,roxyboy/scikit-learn,rsivapr/scikit-learn,mhue/scikit-learn,joernhees/scikit-learn,sumspr/scikit-learn,xiaoxiamii/scikit-learn,jakirkham/scikit-learn,jorge2703/scikit-learn,kaichogami/scikit-learn,NelisVerhoef/scikit-learn,rahuldhote/scikit-learn,ElDeveloper/scikit-learn,treycausey/scikit-learn,pythonvietnam/scikit-learn,petosegan/scikit-learn,rvraghav93/scikit-learn,fbagirov/scikit-learn,aewhatley/scikit-learn,icdishb/scikit-learn,florian-f/sklearn,Titan-C/scikit-learn,cainiaocome/scikit-learn,HolgerPeters/scikit-learn,dhruv13J/scikit-learn,andrewnc/scikit-learn,zorroblue/scikit-learn,kjung/scikit-learn,cauchycui/scikit-learn,manhhomienbienthuy/scikit-learn,rahuldhote/scikit-learn,mehdidc/scikit-learn,amueller/scikit-learn,jkarnows/scikit-learn,nelson-liu/scikit-learn,idlead/scikit-learn,wzbozon/scikit-learn,ahoyosid/scikit-learn,idlead/scikit-learn,sinhrks/scikit-learn,theoryno3/scikit-learn,mhdella/scikit-learn,abhishekkrthakur/scikit-learn,yanlend/scikit-learn,justincassidy/scikit-learn,aminert/scikit-learn,herilalaina/scikit-learn,jayflo/scikit-learn,f3r/scikit-learn,UNR-AERIAL/scikit-learn,joshloyal/scikit-learn,YinongLong/scikit-learn,huobaowangxi/scikit-learn,MartinDelzant/scikit-learn,dsquareindia/scikit-learn,Myasuka/scikit-learn,HolgerPeters/scikit-learn,anurag313/scikit-learn,giorgiop/scikit-learn,jaidevd/scikit-learn,billy-inn/scikit-learn,russel1237/scikit-learn,kashif/scikit-learn,MechCoder/scikit-learn,deepesch/scikit-learn,robbymeals/scikit-learn,dhruv13J/scikit-learn,hitszxp/scikit-learn,dhruv13J/scikit-learn,Adai0808/scikit-learn,lesteve/scikit-learn,rahul-c1/scikit-learn,ankurankan/scikit-learn,andrewnc/scikit-learn,UNR-AERIAL/scikit-learn,larsmans/scikit-learn,tdhopper/scikit-learn,saiwing-yeung/scikit-learn,jseabold/scikit-learn,mikebenfield/scikit-learn,shenzebang/scikit-learn,hitszxp/scikit-learn,tosolveit/scikit-learn,mugizico/scikit-learn,lazywei/scikit-learn,manashmndl/scikit-learn,lenovor/scikit-learn,Fireblend/scikit-learn,pypot/scikit-learn,fyffyt/scikit-learn,pnedunuri/scikit-learn,jpautom/scikit-learn,mxjl620/scikit-learn,djgagne/scikit-learn,nelson-liu/scikit-learn,elkingtonmcb/scikit-learn,glennq/scikit-learn,vigilv/scikit-learn,kjung/scikit-learn,r-mart/scikit-learn,nrhine1/scikit-learn,arabenjamin/scikit-learn,gotomypc/scikit-learn,sinhrks/scikit-learn,saiwing-yeung/scikit-learn,rahuldhote/scikit-learn,PatrickOReilly/scikit-learn,raghavrv/scikit-learn,f3r/scikit-learn,thientu/scikit-learn,joshloyal/scikit-learn,Lawrence-Liu/scikit-learn,LohithBlaze/scikit-learn,marcocaccin/scikit-learn,liangz0707/scikit-learn,cauchycui/scikit-learn,ZenDevelopmentSystems/scikit-learn,bigdataelephants/scikit-learn,devanshdalal/scikit-learn,JosmanPS/scikit-learn,liyu1990/sklearn,trankmichael/scikit-learn,jseabold/scikit-learn,JosmanPS/scikit-learn,andrewnc/scikit-learn,pratapvardhan/scikit-learn,ogrisel/scikit-learn,zaxtax/scikit-learn,devanshdalal/scikit-learn,vermouthmjl/scikit-learn,aewhatley/scikit-learn,jpautom/scikit-learn,zorojean/scikit-learn,ldirer/scikit-learn,tomlof/scikit-learn | import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
- return super(SparseBaseLibSVM, self).fit(X, y, sample_weight)
+ return super(SparseBaseLibSVM, self).fit(X, y,
+ sample_weight=sample_weight)
| FIX sparse OneClassSVM was using the wrong parameter | ## Code Before:
import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
return super(SparseBaseLibSVM, self).fit(X, y, sample_weight)
## Instruction:
FIX sparse OneClassSVM was using the wrong parameter
## Code After:
import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
return super(SparseBaseLibSVM, self).fit(X, y,
sample_weight=sample_weight)
| import numpy as np
import scipy.sparse
from abc import ABCMeta, abstractmethod
from ..base import BaseLibSVM
class SparseBaseLibSVM(BaseLibSVM):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, impl, kernel, degree, gamma, coef0,
tol, C, nu, epsilon, shrinking, probability, cache_size,
class_weight, verbose):
assert kernel in self._sparse_kernels, \
"kernel should be one of %s, "\
"%s was given." % (self._kernel_types, kernel)
super(SparseBaseLibSVM, self).__init__(impl, kernel, degree, gamma,
coef0, tol, C, nu, epsilon, shrinking, probability, cache_size,
True, class_weight, verbose)
def fit(self, X, y, sample_weight=None):
X = scipy.sparse.csr_matrix(X, dtype=np.float64)
- return super(SparseBaseLibSVM, self).fit(X, y, sample_weight)
? ---------------
+ return super(SparseBaseLibSVM, self).fit(X, y,
+ sample_weight=sample_weight) |
565c95ce9a8ff96d177196c6dbf8d8f88cdfa029 | poyo/exceptions.py | poyo/exceptions.py |
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no parser object at the given level.
"""
class NoTypeException(PoyoException):
"""Raised when the parser is unable to determine the actual type for a
given string.
"""
|
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no parser object at the given level.
"""
class NoTypeException(PoyoException):
"""Raised when the parser is unable to determine the actual type for a
given string.
"""
class IgnoredMatchException(PoyoException):
"""Raised when a match does result in a Python representation such as a
comment or a blank line.
"""
| Add an error class for string data that is ignored by the parser | Add an error class for string data that is ignored by the parser
| Python | mit | hackebrot/poyo |
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no parser object at the given level.
"""
class NoTypeException(PoyoException):
"""Raised when the parser is unable to determine the actual type for a
given string.
"""
+
+ class IgnoredMatchException(PoyoException):
+ """Raised when a match does result in a Python representation such as a
+ comment or a blank line.
+ """
+ | Add an error class for string data that is ignored by the parser | ## Code Before:
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no parser object at the given level.
"""
class NoTypeException(PoyoException):
"""Raised when the parser is unable to determine the actual type for a
given string.
"""
## Instruction:
Add an error class for string data that is ignored by the parser
## Code After:
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no parser object at the given level.
"""
class NoTypeException(PoyoException):
"""Raised when the parser is unable to determine the actual type for a
given string.
"""
class IgnoredMatchException(PoyoException):
"""Raised when a match does result in a Python representation such as a
comment or a blank line.
"""
|
class PoyoException(Exception):
"""Super class for all of Poyo's exceptions."""
class NoMatchException(PoyoException):
"""Raised when the parser cannot find a pattern that matches the given
string.
"""
class NoParentException(PoyoException):
"""Raised when there is no parser object at the given level.
"""
class NoTypeException(PoyoException):
"""Raised when the parser is unable to determine the actual type for a
given string.
"""
+
+
+ class IgnoredMatchException(PoyoException):
+ """Raised when a match does result in a Python representation such as a
+ comment or a blank line.
+ """ |
d5458286244d2ba14fe0af33a9e8fdc9ab728669 | tests/test_replies.py | tests/test_replies.py | from __future__ import absolute_import, unicode_literals
import time
import unittest
class ReplyTestCase(unittest.TestCase):
def test_base_reply(self):
from wechatpy.replies import TextReply
timestamp = int(time.time())
reply = TextReply(source='user1', target='user2')
self.assertEqual('user1', reply.source)
self.assertEqual('user2', reply.target)
self.assertLessEqual(timestamp, reply.time)
| from __future__ import absolute_import, unicode_literals
import time
import unittest
class ReplyTestCase(unittest.TestCase):
def test_base_reply(self):
from wechatpy.replies import TextReply
timestamp = int(time.time())
reply = TextReply(source='user1', target='user2')
self.assertEqual('user1', reply.source)
self.assertEqual('user2', reply.target)
self.assertTrue(timestamp <= reply.time)
| Fix test error under Python 2.6 where assertLessEqual not defined | Fix test error under Python 2.6 where assertLessEqual not defined
| Python | mit | cloverstd/wechatpy,wechatpy/wechatpy,cysnake4713/wechatpy,tdautc19841202/wechatpy,zaihui/wechatpy,hunter007/wechatpy,Luckyseal/wechatpy,cysnake4713/wechatpy,navcat/wechatpy,Luckyseal/wechatpy,mruse/wechatpy,chenjiancan/wechatpy,mruse/wechatpy,zhaoqz/wechatpy,zhaoqz/wechatpy,EaseCloud/wechatpy,zaihui/wechatpy,tdautc19841202/wechatpy,tdautc19841202/wechatpy,messense/wechatpy,hunter007/wechatpy,Dufy/wechatpy,cloverstd/wechatpy,jxtech/wechatpy,chenjiancan/wechatpy,Dufy/wechatpy,Luckyseal/wechatpy,navcat/wechatpy,cysnake4713/wechatpy,EaseCloud/wechatpy | from __future__ import absolute_import, unicode_literals
import time
import unittest
class ReplyTestCase(unittest.TestCase):
def test_base_reply(self):
from wechatpy.replies import TextReply
timestamp = int(time.time())
reply = TextReply(source='user1', target='user2')
self.assertEqual('user1', reply.source)
self.assertEqual('user2', reply.target)
- self.assertLessEqual(timestamp, reply.time)
+ self.assertTrue(timestamp <= reply.time)
| Fix test error under Python 2.6 where assertLessEqual not defined | ## Code Before:
from __future__ import absolute_import, unicode_literals
import time
import unittest
class ReplyTestCase(unittest.TestCase):
def test_base_reply(self):
from wechatpy.replies import TextReply
timestamp = int(time.time())
reply = TextReply(source='user1', target='user2')
self.assertEqual('user1', reply.source)
self.assertEqual('user2', reply.target)
self.assertLessEqual(timestamp, reply.time)
## Instruction:
Fix test error under Python 2.6 where assertLessEqual not defined
## Code After:
from __future__ import absolute_import, unicode_literals
import time
import unittest
class ReplyTestCase(unittest.TestCase):
def test_base_reply(self):
from wechatpy.replies import TextReply
timestamp = int(time.time())
reply = TextReply(source='user1', target='user2')
self.assertEqual('user1', reply.source)
self.assertEqual('user2', reply.target)
self.assertTrue(timestamp <= reply.time)
| from __future__ import absolute_import, unicode_literals
import time
import unittest
class ReplyTestCase(unittest.TestCase):
def test_base_reply(self):
from wechatpy.replies import TextReply
timestamp = int(time.time())
reply = TextReply(source='user1', target='user2')
self.assertEqual('user1', reply.source)
self.assertEqual('user2', reply.target)
- self.assertLessEqual(timestamp, reply.time)
? ^ ------- ^
+ self.assertTrue(timestamp <= reply.time)
? ^^^ ^^^
|
a537f049bfb61488a056333d362d9983e8e9f88d | 2020/10/p1.py | 2020/10/p1.py |
def get_input():
with open('input.txt', 'r') as f:
return set(int(i) for i in f.read().split())
def main():
puzzle = get_input()
last_joltage = 0
one_jolt = 0
three_jolts = 1 # this is bad lmao
while len(puzzle) != 0:
if last_joltage + 1 in puzzle:
last_joltage = last_joltage + 1
one_jolt += 1
elif last_joltage + 2 in puzzle:
last_joltage = last_joltage + 2
elif last_joltage + 3 in puzzle:
last_joltage = last_joltage + 3
three_jolts += 1
puzzle.remove(last_joltage)
print(one_jolt, three_jolts)
return one_jolt * three_jolts
if __name__ == '__main__':
import time
start = time.perf_counter()
print(main())
print(time.perf_counter() - start)
|
def get_input():
with open('input.txt', 'r') as f:
return set(int(i) for i in f.read().split())
def main():
puzzle = get_input()
last_joltage = 0
one_jolt = 0
three_jolts = 1
while len(puzzle) != 0:
if last_joltage + 1 in puzzle:
last_joltage = last_joltage + 1
one_jolt += 1
elif last_joltage + 2 in puzzle:
last_joltage = last_joltage + 2
elif last_joltage + 3 in puzzle:
last_joltage = last_joltage + 3
three_jolts += 1
puzzle.remove(last_joltage)
print(one_jolt, three_jolts)
return one_jolt * three_jolts
if __name__ == '__main__':
import time
start = time.perf_counter()
print(main())
print(time.perf_counter() - start)
| Fix minor issues in 2020.10.1 file | Fix minor issues in 2020.10.1 file
The comment about the 1 being bad was incorrect, in fact it was good. I
had forgotten about adding the extra three-jolt difference for the final
adapter in the device, and didn't make the connection between it and the
three-jolt count being one short lol.
| Python | mit | foxscotch/advent-of-code,foxscotch/advent-of-code |
def get_input():
with open('input.txt', 'r') as f:
return set(int(i) for i in f.read().split())
def main():
puzzle = get_input()
last_joltage = 0
one_jolt = 0
- three_jolts = 1 # this is bad lmao
+ three_jolts = 1
while len(puzzle) != 0:
if last_joltage + 1 in puzzle:
last_joltage = last_joltage + 1
one_jolt += 1
elif last_joltage + 2 in puzzle:
last_joltage = last_joltage + 2
elif last_joltage + 3 in puzzle:
last_joltage = last_joltage + 3
three_jolts += 1
puzzle.remove(last_joltage)
print(one_jolt, three_jolts)
return one_jolt * three_jolts
-
if __name__ == '__main__':
import time
start = time.perf_counter()
print(main())
print(time.perf_counter() - start)
| Fix minor issues in 2020.10.1 file | ## Code Before:
def get_input():
with open('input.txt', 'r') as f:
return set(int(i) for i in f.read().split())
def main():
puzzle = get_input()
last_joltage = 0
one_jolt = 0
three_jolts = 1 # this is bad lmao
while len(puzzle) != 0:
if last_joltage + 1 in puzzle:
last_joltage = last_joltage + 1
one_jolt += 1
elif last_joltage + 2 in puzzle:
last_joltage = last_joltage + 2
elif last_joltage + 3 in puzzle:
last_joltage = last_joltage + 3
three_jolts += 1
puzzle.remove(last_joltage)
print(one_jolt, three_jolts)
return one_jolt * three_jolts
if __name__ == '__main__':
import time
start = time.perf_counter()
print(main())
print(time.perf_counter() - start)
## Instruction:
Fix minor issues in 2020.10.1 file
## Code After:
def get_input():
with open('input.txt', 'r') as f:
return set(int(i) for i in f.read().split())
def main():
puzzle = get_input()
last_joltage = 0
one_jolt = 0
three_jolts = 1
while len(puzzle) != 0:
if last_joltage + 1 in puzzle:
last_joltage = last_joltage + 1
one_jolt += 1
elif last_joltage + 2 in puzzle:
last_joltage = last_joltage + 2
elif last_joltage + 3 in puzzle:
last_joltage = last_joltage + 3
three_jolts += 1
puzzle.remove(last_joltage)
print(one_jolt, three_jolts)
return one_jolt * three_jolts
if __name__ == '__main__':
import time
start = time.perf_counter()
print(main())
print(time.perf_counter() - start)
|
def get_input():
with open('input.txt', 'r') as f:
return set(int(i) for i in f.read().split())
def main():
puzzle = get_input()
last_joltage = 0
one_jolt = 0
- three_jolts = 1 # this is bad lmao
+ three_jolts = 1
while len(puzzle) != 0:
if last_joltage + 1 in puzzle:
last_joltage = last_joltage + 1
one_jolt += 1
elif last_joltage + 2 in puzzle:
last_joltage = last_joltage + 2
elif last_joltage + 3 in puzzle:
last_joltage = last_joltage + 3
three_jolts += 1
puzzle.remove(last_joltage)
print(one_jolt, three_jolts)
return one_jolt * three_jolts
-
if __name__ == '__main__':
import time
start = time.perf_counter()
print(main())
print(time.perf_counter() - start) |
c2598058722531662aab8831640fc367689d2a43 | tests/utils/test_process_word_vectors.py | tests/utils/test_process_word_vectors.py | import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
call(["wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/" + vectors_name + " -O " +
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__])
| import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
call(["wget https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/" + vectors_name + " -O " +
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__])
| Update Fasttext pretrained vectors location | Update Fasttext pretrained vectors location
| Python | mit | lvapeab/nmt-keras,lvapeab/nmt-keras | import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
- call(["wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/" + vectors_name + " -O " +
+ call(["wget https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/" + vectors_name + " -O " +
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__])
| Update Fasttext pretrained vectors location | ## Code Before:
import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
call(["wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/" + vectors_name + " -O " +
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__])
## Instruction:
Update Fasttext pretrained vectors location
## Code After:
import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
call(["wget https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/" + vectors_name + " -O " +
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__])
| import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
- call(["wget https://s3-us-west-1.amazonaws.com/fasttext-vectors/" + vectors_name + " -O " +
? ^^^ ^^^ ------------- ^
+ call(["wget https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/" + vectors_name + " -O " +
? ^^^^^^^^ ^^^^^^^ ^ +++++
path + "/" + vectors_name],
shell=True)
txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4])
vectors = np.load('./' + vectors_name[:-4] + '.npy').item()
assert len(list(vectors)) == 8769
assert vectors['kihlkunnan'].shape[0] == 300
if __name__ == '__main__':
pytest.main([__file__]) |
123ffcabb6fa783b1524a55dd3dce52ad33a13db | nitrogen/local.py | nitrogen/local.py |
import collections
from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock
from .proxy import Proxy
class Local(Local):
# Just adding a __dict__ property to the object.
def __init__(self):
super(Local, self).__init__()
object.__setattr__(self, '__storage__', collections.defaultdict(dict))
@property
def __dict__(self):
return self.__storage__[self.__ident_func__()]
def __call__(self, name):
return Proxy(lambda: getattr(self, name))
class LocalManager(LocalManager):
def local(self):
obj = Local()
self.locals.append(obj)
return obj
def stack(self):
obj = LocalStack()
self.locals.append(obj)
return obj
class LocalStack(LocalStack):
def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError('object unbound')
return rv
return Proxy(_lookup)
def LocalProxy(local, name=None):
if name is None:
return Proxy(local)
return Proxy(lambda: getattr(local, name)) |
import collections
from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident
from .proxy import Proxy
class Local(Local):
# We are extending this class for the only purpose of adding a __dict__
# attribute, so that this will work nearly identically to the builtin
# threading.local class.
# Not adding any more attributes, but we don't want to actually add a dict.
__slots__ = ()
def __init__(self):
super(Local, self).__init__()
object.__setattr__(self, '__storage__', collections.defaultdict(dict))
@property
def __dict__(self):
# The __ident_func__ attribute is added after the 0.6.2 release (at
# this point it is still in the development branch). This lets us
# work with both versions.
try:
return self.__storage__[self.__ident_func__()]
except AttributeError:
return self.__storage__[get_ident()]
def __call__(self, name):
return Proxy(lambda: getattr(self, name))
class LocalManager(LocalManager):
def local(self):
obj = Local()
self.locals.append(obj)
return obj
def stack(self):
obj = LocalStack()
self.locals.append(obj)
return obj
class LocalStack(LocalStack):
def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError('object unbound')
return rv
return Proxy(_lookup)
def LocalProxy(local, name=None):
if name is None:
return Proxy(local)
return Proxy(lambda: getattr(local, name)) | Fix Local class to work with older werkzeug. | Fix Local class to work with older werkzeug. | Python | bsd-3-clause | mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen,mikeboers/Nitrogen |
import collections
- from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock
+ from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident
from .proxy import Proxy
class Local(Local):
-
- # Just adding a __dict__ property to the object.
+
+ # We are extending this class for the only purpose of adding a __dict__
+ # attribute, so that this will work nearly identically to the builtin
+ # threading.local class.
+
+ # Not adding any more attributes, but we don't want to actually add a dict.
+ __slots__ = ()
def __init__(self):
super(Local, self).__init__()
object.__setattr__(self, '__storage__', collections.defaultdict(dict))
@property
def __dict__(self):
+ # The __ident_func__ attribute is added after the 0.6.2 release (at
+ # this point it is still in the development branch). This lets us
+ # work with both versions.
+ try:
- return self.__storage__[self.__ident_func__()]
+ return self.__storage__[self.__ident_func__()]
+ except AttributeError:
+ return self.__storage__[get_ident()]
def __call__(self, name):
return Proxy(lambda: getattr(self, name))
class LocalManager(LocalManager):
def local(self):
obj = Local()
self.locals.append(obj)
return obj
def stack(self):
obj = LocalStack()
self.locals.append(obj)
return obj
class LocalStack(LocalStack):
def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError('object unbound')
return rv
return Proxy(_lookup)
def LocalProxy(local, name=None):
if name is None:
return Proxy(local)
return Proxy(lambda: getattr(local, name)) | Fix Local class to work with older werkzeug. | ## Code Before:
import collections
from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock
from .proxy import Proxy
class Local(Local):
# Just adding a __dict__ property to the object.
def __init__(self):
super(Local, self).__init__()
object.__setattr__(self, '__storage__', collections.defaultdict(dict))
@property
def __dict__(self):
return self.__storage__[self.__ident_func__()]
def __call__(self, name):
return Proxy(lambda: getattr(self, name))
class LocalManager(LocalManager):
def local(self):
obj = Local()
self.locals.append(obj)
return obj
def stack(self):
obj = LocalStack()
self.locals.append(obj)
return obj
class LocalStack(LocalStack):
def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError('object unbound')
return rv
return Proxy(_lookup)
def LocalProxy(local, name=None):
if name is None:
return Proxy(local)
return Proxy(lambda: getattr(local, name))
## Instruction:
Fix Local class to work with older werkzeug.
## Code After:
import collections
from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident
from .proxy import Proxy
class Local(Local):
# We are extending this class for the only purpose of adding a __dict__
# attribute, so that this will work nearly identically to the builtin
# threading.local class.
# Not adding any more attributes, but we don't want to actually add a dict.
__slots__ = ()
def __init__(self):
super(Local, self).__init__()
object.__setattr__(self, '__storage__', collections.defaultdict(dict))
@property
def __dict__(self):
# The __ident_func__ attribute is added after the 0.6.2 release (at
# this point it is still in the development branch). This lets us
# work with both versions.
try:
return self.__storage__[self.__ident_func__()]
except AttributeError:
return self.__storage__[get_ident()]
def __call__(self, name):
return Proxy(lambda: getattr(self, name))
class LocalManager(LocalManager):
def local(self):
obj = Local()
self.locals.append(obj)
return obj
def stack(self):
obj = LocalStack()
self.locals.append(obj)
return obj
class LocalStack(LocalStack):
def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError('object unbound')
return rv
return Proxy(_lookup)
def LocalProxy(local, name=None):
if name is None:
return Proxy(local)
return Proxy(lambda: getattr(local, name)) |
import collections
- from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock
+ from werkzeug.local import release_local, Local, LocalManager, LocalStack, allocate_lock, get_ident
? +++++++++++
from .proxy import Proxy
class Local(Local):
-
- # Just adding a __dict__ property to the object.
+
+ # We are extending this class for the only purpose of adding a __dict__
+ # attribute, so that this will work nearly identically to the builtin
+ # threading.local class.
+
+ # Not adding any more attributes, but we don't want to actually add a dict.
+ __slots__ = ()
def __init__(self):
super(Local, self).__init__()
object.__setattr__(self, '__storage__', collections.defaultdict(dict))
@property
def __dict__(self):
+ # The __ident_func__ attribute is added after the 0.6.2 release (at
+ # this point it is still in the development branch). This lets us
+ # work with both versions.
+ try:
- return self.__storage__[self.__ident_func__()]
+ return self.__storage__[self.__ident_func__()]
? ++++
+ except AttributeError:
+ return self.__storage__[get_ident()]
def __call__(self, name):
return Proxy(lambda: getattr(self, name))
class LocalManager(LocalManager):
def local(self):
obj = Local()
self.locals.append(obj)
return obj
def stack(self):
obj = LocalStack()
self.locals.append(obj)
return obj
class LocalStack(LocalStack):
def __call__(self):
def _lookup():
rv = self.top
if rv is None:
raise RuntimeError('object unbound')
return rv
return Proxy(_lookup)
def LocalProxy(local, name=None):
if name is None:
return Proxy(local)
return Proxy(lambda: getattr(local, name)) |
e9c6b22ffaf498dc64f590689cc637a152444665 | forms.py | forms.py | from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")])
username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")])
role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')])
password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")])
submit = SubmitField('Add User')
class LoginForm(Form):
username = StringField('Username', validators=[DataRequired("Please enter a usename")])
password = PasswordField('Password', validators=[DataRequired('Please enter a password')])
remember = BooleanField('Remember me')
submit = SubmitField("Login")
class RetrievalForm(Form):
amount = StringField('Input the amount taken', validators=[validators.input_required()])
submit = SubmitField("Enter Quantity")
| from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")])
username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")])
role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')])
password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")])
submit = SubmitField('Add User')
class LoginForm(Form):
username = StringField('Username', validators=[DataRequired("Please enter a username")])
password = PasswordField('Password', validators=[DataRequired('Please enter a password')])
remember = BooleanField()
submit = SubmitField("Login")
class RetrievalForm(Form):
amount = StringField('Input the amount taken', validators=[validators.input_required()])
submit = SubmitField("Enter Quantity")
| Change LoginForm parameter for BooleanField | Change LoginForm parameter for BooleanField
| Python | mit | jinjiaho/project57,jinjiaho/project57,jinjiaho/project57,jinjiaho/project57 | from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")])
username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")])
role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')])
password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")])
submit = SubmitField('Add User')
class LoginForm(Form):
- username = StringField('Username', validators=[DataRequired("Please enter a usename")])
+ username = StringField('Username', validators=[DataRequired("Please enter a username")])
password = PasswordField('Password', validators=[DataRequired('Please enter a password')])
- remember = BooleanField('Remember me')
+ remember = BooleanField()
submit = SubmitField("Login")
class RetrievalForm(Form):
amount = StringField('Input the amount taken', validators=[validators.input_required()])
submit = SubmitField("Enter Quantity")
| Change LoginForm parameter for BooleanField | ## Code Before:
from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")])
username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")])
role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')])
password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")])
submit = SubmitField('Add User')
class LoginForm(Form):
username = StringField('Username', validators=[DataRequired("Please enter a usename")])
password = PasswordField('Password', validators=[DataRequired('Please enter a password')])
remember = BooleanField('Remember me')
submit = SubmitField("Login")
class RetrievalForm(Form):
amount = StringField('Input the amount taken', validators=[validators.input_required()])
submit = SubmitField("Enter Quantity")
## Instruction:
Change LoginForm parameter for BooleanField
## Code After:
from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")])
username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")])
role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')])
password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")])
submit = SubmitField('Add User')
class LoginForm(Form):
username = StringField('Username', validators=[DataRequired("Please enter a username")])
password = PasswordField('Password', validators=[DataRequired('Please enter a password')])
remember = BooleanField()
submit = SubmitField("Login")
class RetrievalForm(Form):
amount = StringField('Input the amount taken', validators=[validators.input_required()])
submit = SubmitField("Enter Quantity")
| from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField, RadioField, validators, IntegerField, BooleanField
from wtforms.validators import DataRequired, Email, Length
class AddUserForm(Form):
name = StringField('Name of User', validators=[DataRequired("Please enter the name of the newcomer.")])
username= StringField('Create a Username', validators=[DataRequired("Please enter a username.")])
role = RadioField('Role of User', choices=[('attendent','Room Attendant'),('supervisor','Supervisor')],validators=[DataRequired('Input Choice')])
password = PasswordField('Password', validators=[DataRequired("Please enter a password."), Length(min=6, message="Passwords must be 6 characters or more.")])
submit = SubmitField('Add User')
class LoginForm(Form):
- username = StringField('Username', validators=[DataRequired("Please enter a usename")])
+ username = StringField('Username', validators=[DataRequired("Please enter a username")])
? +
password = PasswordField('Password', validators=[DataRequired('Please enter a password')])
- remember = BooleanField('Remember me')
? -------------
+ remember = BooleanField()
submit = SubmitField("Login")
class RetrievalForm(Form):
amount = StringField('Input the amount taken', validators=[validators.input_required()])
submit = SubmitField("Enter Quantity")
|
671ccd8e82e0c106b0ccd9cb61b674f342319725 | mopidy/backends/spotify.py | mopidy/backends/spotify.py | import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
self.spotify = spytify.Spytify(
settings.SPOTIFY_USERNAME.encode('utf-8'),
settings.SPOTIFY_PASSWORD.encode('utf-8'))
self._playlist_load_cache = None
def playlist_load(self, name):
if not self._playlist_load_cache:
for playlist in self.spotify.stored_playlists:
if playlist.name == name:
tracks = []
for track in playlist.tracks:
tracks.append(u'add %s\n' % track.file_id)
self._playlist_load_cache = tracks
break
return self._playlist_load_cache
def playlists_list(self):
playlists = []
for playlist in self.spotify.stored_playlists:
playlists.append(u'playlist: %s' % playlist.name.decode('utf-8'))
return playlists
def url_handlers(self):
return [u'spotify:', u'http://open.spotify.com/']
| import sys
import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
self.spotify = spytify.Spytify(self.username, self.password)
self._playlist_load_cache = None
@property
def username(self):
username = settings.SPOTIFY_USERNAME.encode('utf-8')
if not username:
sys.exit('Setting SPOTIFY_USERNAME is not set.')
return username
@property
def password(self):
password = settings.SPOTIFY_PASSWORD.encode('utf-8')
if not password:
sys.exit('Setting SPOTIFY_PASSWORD is not set.')
return password
def playlist_load(self, name):
if not self._playlist_load_cache:
for playlist in self.spotify.stored_playlists:
if playlist.name == name:
tracks = []
for track in playlist.tracks:
tracks.append(u'add %s\n' % track.file_id)
self._playlist_load_cache = tracks
break
return self._playlist_load_cache
def playlists_list(self):
playlists = []
for playlist in self.spotify.stored_playlists:
playlists.append(u'playlist: %s' % playlist.name.decode('utf-8'))
return playlists
def url_handlers(self):
return [u'spotify:', u'http://open.spotify.com/']
| Exit if SPOTIFY_{USERNAME,PASSWORD} is not set | Exit if SPOTIFY_{USERNAME,PASSWORD} is not set
| Python | apache-2.0 | hkariti/mopidy,ali/mopidy,jcass77/mopidy,priestd09/mopidy,jmarsik/mopidy,pacificIT/mopidy,mopidy/mopidy,priestd09/mopidy,kingosticks/mopidy,vrs01/mopidy,jcass77/mopidy,bacontext/mopidy,bacontext/mopidy,woutervanwijk/mopidy,tkem/mopidy,mokieyue/mopidy,ZenithDK/mopidy,mopidy/mopidy,jodal/mopidy,swak/mopidy,bencevans/mopidy,swak/mopidy,ZenithDK/mopidy,diandiankan/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,abarisain/mopidy,quartz55/mopidy,mokieyue/mopidy,dbrgn/mopidy,SuperStarPL/mopidy,woutervanwijk/mopidy,liamw9534/mopidy,hkariti/mopidy,quartz55/mopidy,glogiotatidis/mopidy,jmarsik/mopidy,quartz55/mopidy,pacificIT/mopidy,diandiankan/mopidy,ZenithDK/mopidy,pacificIT/mopidy,SuperStarPL/mopidy,tkem/mopidy,dbrgn/mopidy,vrs01/mopidy,bencevans/mopidy,jcass77/mopidy,priestd09/mopidy,pacificIT/mopidy,ali/mopidy,bacontext/mopidy,dbrgn/mopidy,bacontext/mopidy,adamcik/mopidy,mokieyue/mopidy,rawdlite/mopidy,swak/mopidy,dbrgn/mopidy,hkariti/mopidy,SuperStarPL/mopidy,tkem/mopidy,abarisain/mopidy,diandiankan/mopidy,adamcik/mopidy,ZenithDK/mopidy,jodal/mopidy,mopidy/mopidy,hkariti/mopidy,rawdlite/mopidy,mokieyue/mopidy,diandiankan/mopidy,vrs01/mopidy,bencevans/mopidy,kingosticks/mopidy,liamw9534/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,ali/mopidy,vrs01/mopidy,tkem/mopidy,quartz55/mopidy,jmarsik/mopidy,rawdlite/mopidy,jodal/mopidy,swak/mopidy,glogiotatidis/mopidy,glogiotatidis/mopidy,adamcik/mopidy,rawdlite/mopidy,ali/mopidy,bencevans/mopidy | + import sys
+
import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
+ self.spotify = spytify.Spytify(self.username, self.password)
- self.spotify = spytify.Spytify(
- settings.SPOTIFY_USERNAME.encode('utf-8'),
- settings.SPOTIFY_PASSWORD.encode('utf-8'))
self._playlist_load_cache = None
+
+ @property
+ def username(self):
+ username = settings.SPOTIFY_USERNAME.encode('utf-8')
+ if not username:
+ sys.exit('Setting SPOTIFY_USERNAME is not set.')
+ return username
+
+ @property
+ def password(self):
+ password = settings.SPOTIFY_PASSWORD.encode('utf-8')
+ if not password:
+ sys.exit('Setting SPOTIFY_PASSWORD is not set.')
+ return password
def playlist_load(self, name):
if not self._playlist_load_cache:
for playlist in self.spotify.stored_playlists:
if playlist.name == name:
tracks = []
for track in playlist.tracks:
tracks.append(u'add %s\n' % track.file_id)
self._playlist_load_cache = tracks
break
return self._playlist_load_cache
def playlists_list(self):
playlists = []
for playlist in self.spotify.stored_playlists:
playlists.append(u'playlist: %s' % playlist.name.decode('utf-8'))
return playlists
def url_handlers(self):
return [u'spotify:', u'http://open.spotify.com/']
| Exit if SPOTIFY_{USERNAME,PASSWORD} is not set | ## Code Before:
import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
self.spotify = spytify.Spytify(
settings.SPOTIFY_USERNAME.encode('utf-8'),
settings.SPOTIFY_PASSWORD.encode('utf-8'))
self._playlist_load_cache = None
def playlist_load(self, name):
if not self._playlist_load_cache:
for playlist in self.spotify.stored_playlists:
if playlist.name == name:
tracks = []
for track in playlist.tracks:
tracks.append(u'add %s\n' % track.file_id)
self._playlist_load_cache = tracks
break
return self._playlist_load_cache
def playlists_list(self):
playlists = []
for playlist in self.spotify.stored_playlists:
playlists.append(u'playlist: %s' % playlist.name.decode('utf-8'))
return playlists
def url_handlers(self):
return [u'spotify:', u'http://open.spotify.com/']
## Instruction:
Exit if SPOTIFY_{USERNAME,PASSWORD} is not set
## Code After:
import sys
import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
self.spotify = spytify.Spytify(self.username, self.password)
self._playlist_load_cache = None
@property
def username(self):
username = settings.SPOTIFY_USERNAME.encode('utf-8')
if not username:
sys.exit('Setting SPOTIFY_USERNAME is not set.')
return username
@property
def password(self):
password = settings.SPOTIFY_PASSWORD.encode('utf-8')
if not password:
sys.exit('Setting SPOTIFY_PASSWORD is not set.')
return password
def playlist_load(self, name):
if not self._playlist_load_cache:
for playlist in self.spotify.stored_playlists:
if playlist.name == name:
tracks = []
for track in playlist.tracks:
tracks.append(u'add %s\n' % track.file_id)
self._playlist_load_cache = tracks
break
return self._playlist_load_cache
def playlists_list(self):
playlists = []
for playlist in self.spotify.stored_playlists:
playlists.append(u'playlist: %s' % playlist.name.decode('utf-8'))
return playlists
def url_handlers(self):
return [u'spotify:', u'http://open.spotify.com/']
| + import sys
+
import spytify
from mopidy import settings
from mopidy.backends.base import BaseBackend
class SpotifyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(SpotifyBackend, self).__init__(*args, **kwargs)
+ self.spotify = spytify.Spytify(self.username, self.password)
- self.spotify = spytify.Spytify(
- settings.SPOTIFY_USERNAME.encode('utf-8'),
- settings.SPOTIFY_PASSWORD.encode('utf-8'))
self._playlist_load_cache = None
+
+ @property
+ def username(self):
+ username = settings.SPOTIFY_USERNAME.encode('utf-8')
+ if not username:
+ sys.exit('Setting SPOTIFY_USERNAME is not set.')
+ return username
+
+ @property
+ def password(self):
+ password = settings.SPOTIFY_PASSWORD.encode('utf-8')
+ if not password:
+ sys.exit('Setting SPOTIFY_PASSWORD is not set.')
+ return password
def playlist_load(self, name):
if not self._playlist_load_cache:
for playlist in self.spotify.stored_playlists:
if playlist.name == name:
tracks = []
for track in playlist.tracks:
tracks.append(u'add %s\n' % track.file_id)
self._playlist_load_cache = tracks
break
return self._playlist_load_cache
def playlists_list(self):
playlists = []
for playlist in self.spotify.stored_playlists:
playlists.append(u'playlist: %s' % playlist.name.decode('utf-8'))
return playlists
def url_handlers(self):
return [u'spotify:', u'http://open.spotify.com/'] |
a35d6f59d214741f554dde1363d2eac7addb04cb | crypto_enigma/__init__.py | crypto_enigma/__init__.py |
"""An Enigma machine simulator with rich textual display functionality."""
from ._version import __version__, __author__
#__all__ = ['machine', 'components']
from .components import *
from .machine import *
|
from ._version import __version__, __author__
#__all__ = ['machine', 'components']
from .components import *
from .machine import *
| Add limitations to package documentation | Add limitations to package documentation
| Python | bsd-3-clause | orome/crypto-enigma-py | -
- """An Enigma machine simulator with rich textual display functionality."""
from ._version import __version__, __author__
#__all__ = ['machine', 'components']
from .components import *
from .machine import *
| Add limitations to package documentation | ## Code Before:
"""An Enigma machine simulator with rich textual display functionality."""
from ._version import __version__, __author__
#__all__ = ['machine', 'components']
from .components import *
from .machine import *
## Instruction:
Add limitations to package documentation
## Code After:
from ._version import __version__, __author__
#__all__ = ['machine', 'components']
from .components import *
from .machine import *
| -
- """An Enigma machine simulator with rich textual display functionality."""
from ._version import __version__, __author__
#__all__ = ['machine', 'components']
from .components import *
from .machine import * |
9674a0869c2a333f74178e305677259e7ac379c3 | examples/ignore_websocket.py | examples/ignore_websocket.py |
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
if flow.response.headers.get_first("Connection", None) == "Upgrade":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) |
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
value = flow.response.headers.get_first("Connection", None)
if value and value.upper() == "UPGRADE":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) | Make the Websocket's connection header value case-insensitive | Make the Websocket's connection header value case-insensitive
| Python | mit | liorvh/mitmproxy,ccccccccccc/mitmproxy,dwfreed/mitmproxy,mhils/mitmproxy,ryoqun/mitmproxy,Kriechi/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,ikoz/mitmproxy,jpic/mitmproxy,tfeagle/mitmproxy,rauburtin/mitmproxy,MatthewShao/mitmproxy,pombredanne/mitmproxy,pombredanne/mitmproxy,laurmurclar/mitmproxy,StevenVanAcker/mitmproxy,fimad/mitmproxy,elitest/mitmproxy,claimsmall/mitmproxy,ikoz/mitmproxy,bazzinotti/mitmproxy,liorvh/mitmproxy,zbuc/mitmproxy,devasia1000/mitmproxy,ikoz/mitmproxy,StevenVanAcker/mitmproxy,jvillacorta/mitmproxy,tdickers/mitmproxy,StevenVanAcker/mitmproxy,syjzwjj/mitmproxy,ryoqun/mitmproxy,Endika/mitmproxy,0xwindows/InfoLeak,devasia1000/mitmproxy,elitest/mitmproxy,ParthGanatra/mitmproxy,mitmproxy/mitmproxy,noikiy/mitmproxy,jvillacorta/mitmproxy,onlywade/mitmproxy,sethp-jive/mitmproxy,cortesi/mitmproxy,dweinstein/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,Fuzion24/mitmproxy,ADemonisis/mitmproxy,noikiy/mitmproxy,scriptmediala/mitmproxy,macmantrl/mitmproxy,guiquanz/mitmproxy,gzzhanghao/mitmproxy,byt3bl33d3r/mitmproxy,cortesi/mitmproxy,owers19856/mitmproxy,tdickers/mitmproxy,devasia1000/mitmproxy,syjzwjj/mitmproxy,Endika/mitmproxy,ccccccccccc/mitmproxy,xbzbing/mitmproxy,ujjwal96/mitmproxy,elitest/mitmproxy,liorvh/mitmproxy,inscriptionweb/mitmproxy,inscriptionweb/mitmproxy,tekii/mitmproxy,guiquanz/mitmproxy,vhaupert/mitmproxy,mosajjal/mitmproxy,ADemonisis/mitmproxy,sethp-jive/mitmproxy,ddworken/mitmproxy,vhaupert/mitmproxy,tfeagle/mitmproxy,jpic/mitmproxy,fimad/mitmproxy,legendtang/mitmproxy,xbzbing/mitmproxy,ujjwal96/mitmproxy,ddworken/mitmproxy,Kriechi/mitmproxy,inscriptionweb/mitmproxy,azureplus/mitmproxy,pombredanne/mitmproxy,tfeagle/mitmproxy,legendtang/mitmproxy,byt3bl33d3r/mitmproxy,rauburtin/mitmproxy,Fuzion24/mitmproxy,gzzhanghao/mitmproxy,noikiy/mitmproxy,elitest/mitmproxy,mhils/mitmproxy,ParthGanatra/mitmproxy,mosajjal/mitmproxy,owers19856/mitmproxy,tekii/mitmproxy,cortesi/mitmproxy,macmantrl/mitmproxy,bazzinotti/mitmproxy,dxq-git/mitmproxy,mitmproxy/mitmproxy,jpic/mitmproxy,mosajjal/mitmproxy,mhils/mitmproxy,dweinstein/mitmproxy,fimad/mitmproxy,dxq-git/mitmproxy,xbzbing/mitmproxy,claimsmall/mitmproxy,dwfreed/mitmproxy,xaxa89/mitmproxy,vhaupert/mitmproxy,ujjwal96/mitmproxy,Endika/mitmproxy,ParthGanatra/mitmproxy,meizhoubao/mitmproxy,meizhoubao/mitmproxy,dweinstein/mitmproxy,mhils/mitmproxy,Fuzion24/mitmproxy,gzzhanghao/mitmproxy,azureplus/mitmproxy,dxq-git/mitmproxy,ddworken/mitmproxy,ADemonisis/mitmproxy,0xwindows/InfoLeak,dufferzafar/mitmproxy,zlorb/mitmproxy,tekii/mitmproxy,scriptmediala/mitmproxy,dwfreed/mitmproxy,zlorb/mitmproxy,bazzinotti/mitmproxy,StevenVanAcker/mitmproxy,syjzwjj/mitmproxy,ccccccccccc/mitmproxy,xbzbing/mitmproxy,syjzwjj/mitmproxy,Endika/mitmproxy,onlywade/mitmproxy,sethp-jive/mitmproxy,xaxa89/mitmproxy,xaxa89/mitmproxy,jpic/mitmproxy,guiquanz/mitmproxy,rauburtin/mitmproxy,jvillacorta/mitmproxy,owers19856/mitmproxy,ZeYt/mitmproxy,ZeYt/mitmproxy,zbuc/mitmproxy,zlorb/mitmproxy,Kriechi/mitmproxy,ZeYt/mitmproxy,Kriechi/mitmproxy,ZeYt/mitmproxy,ryoqun/mitmproxy,devasia1000/mitmproxy,claimsmall/mitmproxy,laurmurclar/mitmproxy,MatthewShao/mitmproxy,noikiy/mitmproxy,onlywade/mitmproxy,macmantrl/mitmproxy,scriptmediala/mitmproxy,mitmproxy/mitmproxy,zlorb/mitmproxy,mhils/mitmproxy,sethp-jive/mitmproxy,dxq-git/mitmproxy,MatthewShao/mitmproxy,mitmproxy/mitmproxy,tdickers/mitmproxy,legendtang/mitmproxy,laurmurclar/mitmproxy,macmantrl/mitmproxy,tfeagle/mitmproxy,byt3bl33d3r/mitmproxy,ujjwal96/mitmproxy,Fuzion24/mitmproxy,owers19856/mitmproxy,ikoz/mitmproxy,mosajjal/mitmproxy,vhaupert/mitmproxy,zbuc/mitmproxy,onlywade/mitmproxy,0xwindows/InfoLeak,mitmproxy/mitmproxy,inscriptionweb/mitmproxy,ParthGanatra/mitmproxy,0xwindows/InfoLeak,guiquanz/mitmproxy,byt3bl33d3r/mitmproxy,meizhoubao/mitmproxy,ryoqun/mitmproxy,legendtang/mitmproxy,tdickers/mitmproxy,laurmurclar/mitmproxy,cortesi/mitmproxy,liorvh/mitmproxy,jvillacorta/mitmproxy,dwfreed/mitmproxy,gzzhanghao/mitmproxy,scriptmediala/mitmproxy,dweinstein/mitmproxy,meizhoubao/mitmproxy,rauburtin/mitmproxy,ccccccccccc/mitmproxy,tekii/mitmproxy,bazzinotti/mitmproxy,zbuc/mitmproxy,pombredanne/mitmproxy,claimsmall/mitmproxy,ddworken/mitmproxy,xaxa89/mitmproxy,fimad/mitmproxy,dufferzafar/mitmproxy,ADemonisis/mitmproxy,MatthewShao/mitmproxy |
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
- if flow.response.headers.get_first("Connection", None) == "Upgrade":
+ value = flow.response.headers.get_first("Connection", None)
+ if value and value.upper() == "UPGRADE":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) | Make the Websocket's connection header value case-insensitive | ## Code Before:
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
if flow.response.headers.get_first("Connection", None) == "Upgrade":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL)
## Instruction:
Make the Websocket's connection header value case-insensitive
## Code After:
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
value = flow.response.headers.get_first("Connection", None)
if value and value.upper() == "UPGRADE":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) |
from libmproxy.protocol.http import HTTPRequest
from libmproxy.protocol.tcp import TCPHandler
from libmproxy.protocol import KILL
from libmproxy.script import concurrent
def start(context, argv):
HTTPRequest._headers_to_strip_off.remove("Connection")
HTTPRequest._headers_to_strip_off.remove("Upgrade")
def done(context):
HTTPRequest._headers_to_strip_off.append("Connection")
HTTPRequest._headers_to_strip_off.append("Upgrade")
@concurrent
def response(context, flow):
- if flow.response.headers.get_first("Connection", None) == "Upgrade":
? ^^ --------------
+ value = flow.response.headers.get_first("Connection", None)
? ^^^^^^^
+ if value and value.upper() == "UPGRADE":
# We need to send the response manually now...
flow.client_conn.send(flow.response.assemble())
# ...and then delegate to tcp passthrough.
TCPHandler(flow.live.c, log=False).handle_messages()
flow.reply(KILL) |
c4e1059b387269b6098d05d2227c085e7931b140 | setup.py | setup.py |
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
ext_modules = [
Extension(
'make_asym',
['make_asym.cc'],
include_dirs=['include'],
language='c++',
extra_compile_args=cpp_args,
),
]
setup(
name='make_asym',
version='0.1',
author='Nate Lust',
author_email='nlust@astro.princeton.edu',
description='A python extension module for calculating asymmetry values',
ext_modules=ext_modules,
)
|
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
ext_modules = [
Extension(
'make_asym',
['make_asym.cc'],
include_dirs=['include'],
language='c++',
extra_compile_args=cpp_args,
),
]
setup(
name='make_asym',
version='0.1',
author='Nate Lust',
author_email='nlust@astro.princeton.edu',
description='A module for calculating centers though least asymmetry',
ext_modules=ext_modules,
)
| Update module description for clarity | Update module description for clarity
| Python | mpl-2.0 | natelust/least_asymmetry,natelust/least_asymmetry,natelust/least_asymmetry |
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
ext_modules = [
Extension(
'make_asym',
['make_asym.cc'],
include_dirs=['include'],
language='c++',
extra_compile_args=cpp_args,
),
]
setup(
name='make_asym',
version='0.1',
author='Nate Lust',
author_email='nlust@astro.princeton.edu',
- description='A python extension module for calculating asymmetry values',
+ description='A module for calculating centers though least asymmetry',
ext_modules=ext_modules,
)
| Update module description for clarity | ## Code Before:
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
ext_modules = [
Extension(
'make_asym',
['make_asym.cc'],
include_dirs=['include'],
language='c++',
extra_compile_args=cpp_args,
),
]
setup(
name='make_asym',
version='0.1',
author='Nate Lust',
author_email='nlust@astro.princeton.edu',
description='A python extension module for calculating asymmetry values',
ext_modules=ext_modules,
)
## Instruction:
Update module description for clarity
## Code After:
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
ext_modules = [
Extension(
'make_asym',
['make_asym.cc'],
include_dirs=['include'],
language='c++',
extra_compile_args=cpp_args,
),
]
setup(
name='make_asym',
version='0.1',
author='Nate Lust',
author_email='nlust@astro.princeton.edu',
description='A module for calculating centers though least asymmetry',
ext_modules=ext_modules,
)
|
from distutils.core import setup, Extension
cpp_args = ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.7']
ext_modules = [
Extension(
'make_asym',
['make_asym.cc'],
include_dirs=['include'],
language='c++',
extra_compile_args=cpp_args,
),
]
setup(
name='make_asym',
version='0.1',
author='Nate Lust',
author_email='nlust@astro.princeton.edu',
- description='A python extension module for calculating asymmetry values',
+ description='A module for calculating centers though least asymmetry',
ext_modules=ext_modules,
) |
1cc6ec9f328d3ce045a4a1a50138b11c0b23cc3a | pyfr/ctypesutil.py | pyfr/ctypesutil.py |
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
# First attempt to utilise the system search path
try:
return ctypes.CDLL(lname)
# Otherwise, if this fails then run our own search
except OSError:
for sd in sdirs:
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
|
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
# If an explicit override has been given then use it
lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
if lpath:
return ctypes.CDLL(lpath)
# Otherwise synthesise the library name and start searching
lname = platform_libname(name)
# Start with system search path
try:
return ctypes.CDLL(lname)
# ..and if this fails then run our own search
except OSError:
for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
| Enable library paths to be explicitly specified. | Enable library paths to be explicitly specified.
All shared libraries loaded through the load_library function
can bow be specified explicitly through a suitable environmental
variable
PYFR_<LIB>_LIBRARY_PATH=/path/to/lib.here
where <LIB> corresponds to the name of the library, e.g. METIS.
| Python | bsd-3-clause | BrianVermeire/PyFR |
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
+ # If an explicit override has been given then use it
+ lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
+ if lpath:
+ return ctypes.CDLL(lpath)
+
+ # Otherwise synthesise the library name and start searching
lname = platform_libname(name)
- sdirs = platform_libdirs()
- # First attempt to utilise the system search path
+ # Start with system search path
try:
return ctypes.CDLL(lname)
- # Otherwise, if this fails then run our own search
+ # ..and if this fails then run our own search
except OSError:
- for sd in sdirs:
+ for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
| Enable library paths to be explicitly specified. | ## Code Before:
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
lname = platform_libname(name)
sdirs = platform_libdirs()
# First attempt to utilise the system search path
try:
return ctypes.CDLL(lname)
# Otherwise, if this fails then run our own search
except OSError:
for sd in sdirs:
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
## Instruction:
Enable library paths to be explicitly specified.
## Code After:
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
# If an explicit override has been given then use it
lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
if lpath:
return ctypes.CDLL(lpath)
# Otherwise synthesise the library name and start searching
lname = platform_libname(name)
# Start with system search path
try:
return ctypes.CDLL(lname)
# ..and if this fails then run our own search
except OSError:
for sd in platform_libdirs():
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs
|
import ctypes
import ctypes.util
import os
import sys
def find_libc():
if sys.platform == 'win32':
return ctypes.util.find_msvcrt()
else:
return ctypes.util.find_library('c')
def load_library(name):
+ # If an explicit override has been given then use it
+ lpath = os.environ.get('PYFR_{0}_LIBRARY_PATH'.format(name.upper()))
+ if lpath:
+ return ctypes.CDLL(lpath)
+
+ # Otherwise synthesise the library name and start searching
lname = platform_libname(name)
- sdirs = platform_libdirs()
- # First attempt to utilise the system search path
+ # Start with system search path
try:
return ctypes.CDLL(lname)
- # Otherwise, if this fails then run our own search
? ^^^^^^^^^^
+ # ..and if this fails then run our own search
? ^^^^^
except OSError:
- for sd in sdirs:
? ^
+ for sd in platform_libdirs():
? ^^^^^^^^^^^^ ++
try:
return ctypes.CDLL(os.path.abspath(os.path.join(sd, lname)))
except OSError:
pass
else:
raise OSError('Unable to load {0}'.format(name))
def platform_libname(name):
if sys.platform == 'darwin':
return 'lib{0}.dylib'.format(name)
elif sys.platform == 'win32':
return '{0}.dll'.format(name)
else:
return 'lib{0}.so'.format(name)
def platform_libdirs():
path = os.environ.get('PYFR_LIBRARY_PATH', '')
dirs = [d for d in path.split(':') if d]
# On Mac OS X append the default path used by MacPorts
if sys.platform == 'darwin':
return dirs + ['/opt/local/lib']
# Otherwise just return
else:
return dirs |
86a992dc15482087773f1591752a667a6014ba5d | docker/settings/celery.py | docker/settings/celery.py | from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
pass
CeleryDevSettings.load_settings(__name__)
| from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
# Since we can't properly set CORS on Azurite container
# (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561)
# trying to fetch ``objects.inv`` from celery container fails because the
# URL is like http://docs.dev.readthedocs.io/... and it should be
# http://storage:10000/... This setting fixes that.
# Once we can use CORS, we should define this setting in the
# ``docker_compose.py`` file instead.
AZURE_MEDIA_STORAGE_HOSTNAME = 'storage:10000'
CeleryDevSettings.load_settings(__name__)
| Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME | Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME
We can't access docs.dev.readthedocs.io from celery container because
that domain points to 127.0.0.1 and we don't have the storage in that
IP. So, we need to override the AZURE_MEDIA_STORAGE_HOSTNAME in the
celery container to point to the storage.
We should do this directly in `docker_compose.py` settings file, but
since we can't configure CORS in Azurite we can't do it yet.
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
- pass
+ # Since we can't properly set CORS on Azurite container
+ # (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561)
+ # trying to fetch ``objects.inv`` from celery container fails because the
+ # URL is like http://docs.dev.readthedocs.io/... and it should be
+ # http://storage:10000/... This setting fixes that.
+ # Once we can use CORS, we should define this setting in the
+ # ``docker_compose.py`` file instead.
+ AZURE_MEDIA_STORAGE_HOSTNAME = 'storage:10000'
+
CeleryDevSettings.load_settings(__name__)
| Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME | ## Code Before:
from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
pass
CeleryDevSettings.load_settings(__name__)
## Instruction:
Use proper domain for AZURE_MEDIA_STORAGE_HOSTNAME
## Code After:
from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
# Since we can't properly set CORS on Azurite container
# (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561)
# trying to fetch ``objects.inv`` from celery container fails because the
# URL is like http://docs.dev.readthedocs.io/... and it should be
# http://storage:10000/... This setting fixes that.
# Once we can use CORS, we should define this setting in the
# ``docker_compose.py`` file instead.
AZURE_MEDIA_STORAGE_HOSTNAME = 'storage:10000'
CeleryDevSettings.load_settings(__name__)
| from .docker_compose import DockerBaseSettings
class CeleryDevSettings(DockerBaseSettings):
- pass
+ # Since we can't properly set CORS on Azurite container
+ # (see https://github.com/Azure/Azurite/issues/55#issuecomment-503380561)
+ # trying to fetch ``objects.inv`` from celery container fails because the
+ # URL is like http://docs.dev.readthedocs.io/... and it should be
+ # http://storage:10000/... This setting fixes that.
+ # Once we can use CORS, we should define this setting in the
+ # ``docker_compose.py`` file instead.
+ AZURE_MEDIA_STORAGE_HOSTNAME = 'storage:10000'
+
CeleryDevSettings.load_settings(__name__) |
1666f883e3f6a497971b484c9ba875df2f6693a2 | test/testall.py | test/testall.py |
import os
import re
import sys
from _common import unittest
pkgpath = os.path.dirname(__file__) or '.'
sys.path.append(pkgpath)
os.chdir(pkgpath)
def suite():
s = unittest.TestSuite()
# Get the suite() of every module in this directory beginning with
# "test_".
for fname in os.listdir(pkgpath):
match = re.match(r'(test_\S+)\.py$', fname)
if match:
modname = match.group(1)
s.addTest(__import__(modname).suite())
return s
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
import os
import re
import sys
from _common import unittest
pkgpath = os.path.dirname(__file__) or '.'
sys.path.append(pkgpath)
os.chdir(pkgpath)
# Make sure we use local version of beetsplug and not system namespaced version
# for tests
try:
del sys.modules["beetsplug"]
except KeyError:
pass
def suite():
s = unittest.TestSuite()
# Get the suite() of every module in this directory beginning with
# "test_".
for fname in os.listdir(pkgpath):
match = re.match(r'(test_\S+)\.py$', fname)
if match:
modname = match.group(1)
s.addTest(__import__(modname).suite())
return s
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| Fix python namespaces for test runs | Fix python namespaces for test runs
We need to make sure we don't use namespaced versions that are already installed
on the system but rather use local version from current sources
| Python | mit | SusannaMaria/beets,mathstuf/beets,mathstuf/beets,YetAnotherNerd/beets,lengtche/beets,LordSputnik/beets,shamangeorge/beets,ibmibmibm/beets,m-urban/beets,krig/beets,lightwang1/beets,shamangeorge/beets,MyTunesFreeMusic/privacy-policy,jcoady9/beets,SusannaMaria/beets,beetbox/beets,Andypsamp/CODfinalJUNIT,Andypsamp/CODfinalJUNIT,jcoady9/beets,pkess/beets,PierreRust/beets,tima/beets,mried/beets,pkess/beets,Freso/beets,bj-yinyan/beets,beetbox/beets,dfc/beets,YetAnotherNerd/beets,tima/beets,ruippeixotog/beets,diego-plan9/beets,drm00/beets,ruippeixotog/beets,marcuskrahl/beets,kareemallen/beets,arabenjamin/beets,drm00/beets,parapente/beets,Dishwishy/beets,madmouser1/beets,imsparsh/beets,Freso/beets,mathstuf/beets,andremiller/beets,LordSputnik/beets,moodboom/beets,YetAnotherNerd/beets,mosesfistos1/beetbox,multikatt/beets,jackwilsdon/beets,jmwatte/beets,jayme-github/beets,asteven/beets,xsteadfastx/beets,m-urban/beets,bj-yinyan/beets,YetAnotherNerd/beets,LordSputnik/beets,Dishwishy/beets,Kraymer/beets,mosesfistos1/beetbox,ruippeixotog/beets,jcoady9/beets,randybias/beets,untitaker/beets,PierreRust/beets,beetbox/beets,mried/beets,artemutin/beets,shanemikel/beets,Freso/beets,Andypsamp/CODfinalJUNIT,lightwang1/beets,shanemikel/beets,kelvinhammond/beets,mried/beets,gabrielaraujof/beets,ttsda/beets,randybias/beets,krig/beets,sadatay/beets,sampsyo/beets,parapente/beets,kareemallen/beets,ttsda/beets,swt30/beets,PierreRust/beets,imsparsh/beets,sampsyo/beets,madmouser1/beets,gabrielaraujof/beets,pkess/beets,jackwilsdon/beets,m-urban/beets,arabenjamin/beets,drm00/beets,Andypsamp/CODfinalJUNIT,beetbox/beets,sadatay/beets,ibmibmibm/beets,untitaker/beets,moodboom/beets,SusannaMaria/beets,sampsyo/beets,tima/beets,ttsda/beets,jmwatte/beets,kelvinhammond/beets,drm00/beets,jayme-github/beets,xsteadfastx/beets,kareemallen/beets,jackwilsdon/beets,MyTunesFreeMusic/privacy-policy,xsteadfastx/beets,jbaiter/beets,m-urban/beets,parapente/beets,lengtche/beets,randybias/beets,mosesfistos1/beetbox,tima/beets,andremiller/beets,PierreRust/beets,kelvinhammond/beets,artemutin/beets,marcuskrahl/beets,diego-plan9/beets,xsteadfastx/beets,gabrielaraujof/beets,arabenjamin/beets,Wen777/beets,imsparsh/beets,swt30/beets,arabenjamin/beets,diego-plan9/beets,asteven/beets,MyTunesFreeMusic/privacy-policy,lengtche/beets,dfc/beets,sampsyo/beets,bj-yinyan/beets,Kraymer/beets,moodboom/beets,shanemikel/beets,swt30/beets,madmouser1/beets,asteven/beets,Freso/beets,ttsda/beets,Kraymer/beets,randybias/beets,Andypsamp/CODjunit,parapente/beets,Wen777/beets,jcoady9/beets,swt30/beets,multikatt/beets,bj-yinyan/beets,kareemallen/beets,ruippeixotog/beets,Andypsamp/CODjunit,shamangeorge/beets,lengtche/beets,MyTunesFreeMusic/privacy-policy,lightwang1/beets,lightwang1/beets,LordSputnik/beets,artemutin/beets,Wen777/beets,untitaker/beets,multikatt/beets,Andypsamp/CODfinalJUNIT,marcuskrahl/beets,shamangeorge/beets,andremiller/beets,mried/beets,jackwilsdon/beets,dfc/beets,gabrielaraujof/beets,mosesfistos1/beetbox,SusannaMaria/beets,marcuskrahl/beets,asteven/beets,Andypsamp/CODjunit,moodboom/beets,madmouser1/beets,ibmibmibm/beets,dfc/beets,artemutin/beets,diego-plan9/beets,sadatay/beets,Andypsamp/CODjunit,sadatay/beets,Dishwishy/beets,ibmibmibm/beets,Dishwishy/beets,mathstuf/beets,Kraymer/beets,pkess/beets,imsparsh/beets,Andypsamp/CODjunit,krig/beets,jbaiter/beets,jmwatte/beets,multikatt/beets,jmwatte/beets,shanemikel/beets,kelvinhammond/beets,untitaker/beets |
import os
import re
import sys
from _common import unittest
pkgpath = os.path.dirname(__file__) or '.'
sys.path.append(pkgpath)
os.chdir(pkgpath)
+
+ # Make sure we use local version of beetsplug and not system namespaced version
+ # for tests
+ try:
+ del sys.modules["beetsplug"]
+ except KeyError:
+ pass
def suite():
s = unittest.TestSuite()
# Get the suite() of every module in this directory beginning with
# "test_".
for fname in os.listdir(pkgpath):
match = re.match(r'(test_\S+)\.py$', fname)
if match:
modname = match.group(1)
s.addTest(__import__(modname).suite())
return s
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| Fix python namespaces for test runs | ## Code Before:
import os
import re
import sys
from _common import unittest
pkgpath = os.path.dirname(__file__) or '.'
sys.path.append(pkgpath)
os.chdir(pkgpath)
def suite():
s = unittest.TestSuite()
# Get the suite() of every module in this directory beginning with
# "test_".
for fname in os.listdir(pkgpath):
match = re.match(r'(test_\S+)\.py$', fname)
if match:
modname = match.group(1)
s.addTest(__import__(modname).suite())
return s
if __name__ == '__main__':
unittest.main(defaultTest='suite')
## Instruction:
Fix python namespaces for test runs
## Code After:
import os
import re
import sys
from _common import unittest
pkgpath = os.path.dirname(__file__) or '.'
sys.path.append(pkgpath)
os.chdir(pkgpath)
# Make sure we use local version of beetsplug and not system namespaced version
# for tests
try:
del sys.modules["beetsplug"]
except KeyError:
pass
def suite():
s = unittest.TestSuite()
# Get the suite() of every module in this directory beginning with
# "test_".
for fname in os.listdir(pkgpath):
match = re.match(r'(test_\S+)\.py$', fname)
if match:
modname = match.group(1)
s.addTest(__import__(modname).suite())
return s
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
import os
import re
import sys
from _common import unittest
pkgpath = os.path.dirname(__file__) or '.'
sys.path.append(pkgpath)
os.chdir(pkgpath)
+
+ # Make sure we use local version of beetsplug and not system namespaced version
+ # for tests
+ try:
+ del sys.modules["beetsplug"]
+ except KeyError:
+ pass
def suite():
s = unittest.TestSuite()
# Get the suite() of every module in this directory beginning with
# "test_".
for fname in os.listdir(pkgpath):
match = re.match(r'(test_\S+)\.py$', fname)
if match:
modname = match.group(1)
s.addTest(__import__(modname).suite())
return s
if __name__ == '__main__':
unittest.main(defaultTest='suite') |
178bde1703bbb044f8af8c70a57517af4490a3c0 | databot/handlers/download.py | databot/handlers/download.py | import time
import requests
import bs4
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
'cookies': dict(response.cookies),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
content_type = data.get('headers', {}).get('Content-Type')
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content']
| import time
import requests
import bs4
import cgi
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
'cookies': response.cookies.get_dict(),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
content_type_header = data.get('headers', {}).get('Content-Type', '')
content_type, params = cgi.parse_header(content_type_header)
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content']
| Fix duplicate cookie issue and header parsing | Fix duplicate cookie issue and header parsing
| Python | agpl-3.0 | sirex/databot,sirex/databot | import time
import requests
import bs4
+ import cgi
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
- 'cookies': dict(response.cookies),
+ 'cookies': response.cookies.get_dict(),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
- content_type = data.get('headers', {}).get('Content-Type')
+ content_type_header = data.get('headers', {}).get('Content-Type', '')
+ content_type, params = cgi.parse_header(content_type_header)
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content']
| Fix duplicate cookie issue and header parsing | ## Code Before:
import time
import requests
import bs4
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
'cookies': dict(response.cookies),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
content_type = data.get('headers', {}).get('Content-Type')
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content']
## Instruction:
Fix duplicate cookie issue and header parsing
## Code After:
import time
import requests
import bs4
import cgi
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
'cookies': response.cookies.get_dict(),
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
content_type_header = data.get('headers', {}).get('Content-Type', '')
content_type, params = cgi.parse_header(content_type_header)
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content']
| import time
import requests
import bs4
+ import cgi
from databot.recursive import call
class DownloadErrror(Exception):
pass
def dump_response(response):
return {
'headers': dict(response.headers),
- 'cookies': dict(response.cookies),
? -----
+ 'cookies': response.cookies.get_dict(),
? ++++++++++
'status_code': response.status_code,
'encoding': response.encoding,
'content': response.content,
}
def download(url, delay=None, update=None, **kwargs):
update = update or {}
def func(row):
if delay is not None:
time.sleep(delay)
kw = call(kwargs, row)
_url = url(row)
response = requests.get(_url, **kw)
if response.status_code == 200:
value = dump_response(response)
for k, fn in update.items():
value[k] = fn(row)
yield _url, value
else:
raise DownloadErrror('Error while downloading %s, returned status code was %s, response content:\n\n%s' % (
_url, response.status_code, response.content,
))
return func
def get_content(data):
- content_type = data.get('headers', {}).get('Content-Type')
+ content_type_header = data.get('headers', {}).get('Content-Type', '')
? +++++++ ++++
+ content_type, params = cgi.parse_header(content_type_header)
if content_type == 'text/html':
soup = bs4.BeautifulSoup(data['content'], 'lxml')
return data['content'].decode(soup.original_encoding)
else:
return data['content'] |
c354d130cb542c2a5d57e519ce49175daa597e9c | froide/accesstoken/apps.py | froide/accesstoken/apps.py | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccessTokenConfig(AppConfig):
name = 'froide.accesstoken'
verbose_name = _('Secret Access Token')
def ready(self):
from froide.account import account_canceled
account_canceled.connect(cancel_user)
def cancel_user(sender, user=None, **kwargs):
from .models import AccessToken
if user is None:
return
AccessToken.objects.filter(user=user).delete()
| import json
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccessTokenConfig(AppConfig):
name = 'froide.accesstoken'
verbose_name = _('Secret Access Token')
def ready(self):
from froide.account import account_canceled
from froide.account.export import registry
account_canceled.connect(cancel_user)
registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import AccessToken
if user is None:
return
AccessToken.objects.filter(user=user).delete()
def export_user_data(user):
from .models import AccessToken
access_tokens = (
AccessToken.objects.filter(user=user)
)
if access_tokens:
yield ('access_tokens.json', json.dumps([
{
'purpose': a.purpose,
'timestamp': a.timestamp.isoformat(),
}
for a in access_tokens]).encode('utf-8')
)
| Add user data export for accesstokens | Add user data export for accesstokens | Python | mit | fin/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide,stefanw/froide | + import json
+
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccessTokenConfig(AppConfig):
name = 'froide.accesstoken'
verbose_name = _('Secret Access Token')
def ready(self):
from froide.account import account_canceled
+ from froide.account.export import registry
account_canceled.connect(cancel_user)
+ registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import AccessToken
if user is None:
return
AccessToken.objects.filter(user=user).delete()
+
+ def export_user_data(user):
+ from .models import AccessToken
+
+ access_tokens = (
+ AccessToken.objects.filter(user=user)
+ )
+ if access_tokens:
+ yield ('access_tokens.json', json.dumps([
+ {
+ 'purpose': a.purpose,
+ 'timestamp': a.timestamp.isoformat(),
+ }
+ for a in access_tokens]).encode('utf-8')
+ )
+ | Add user data export for accesstokens | ## Code Before:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccessTokenConfig(AppConfig):
name = 'froide.accesstoken'
verbose_name = _('Secret Access Token')
def ready(self):
from froide.account import account_canceled
account_canceled.connect(cancel_user)
def cancel_user(sender, user=None, **kwargs):
from .models import AccessToken
if user is None:
return
AccessToken.objects.filter(user=user).delete()
## Instruction:
Add user data export for accesstokens
## Code After:
import json
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccessTokenConfig(AppConfig):
name = 'froide.accesstoken'
verbose_name = _('Secret Access Token')
def ready(self):
from froide.account import account_canceled
from froide.account.export import registry
account_canceled.connect(cancel_user)
registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import AccessToken
if user is None:
return
AccessToken.objects.filter(user=user).delete()
def export_user_data(user):
from .models import AccessToken
access_tokens = (
AccessToken.objects.filter(user=user)
)
if access_tokens:
yield ('access_tokens.json', json.dumps([
{
'purpose': a.purpose,
'timestamp': a.timestamp.isoformat(),
}
for a in access_tokens]).encode('utf-8')
)
| + import json
+
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AccessTokenConfig(AppConfig):
name = 'froide.accesstoken'
verbose_name = _('Secret Access Token')
def ready(self):
from froide.account import account_canceled
+ from froide.account.export import registry
account_canceled.connect(cancel_user)
+ registry.register(export_user_data)
def cancel_user(sender, user=None, **kwargs):
from .models import AccessToken
if user is None:
return
AccessToken.objects.filter(user=user).delete()
+
+
+ def export_user_data(user):
+ from .models import AccessToken
+
+ access_tokens = (
+ AccessToken.objects.filter(user=user)
+ )
+ if access_tokens:
+ yield ('access_tokens.json', json.dumps([
+ {
+ 'purpose': a.purpose,
+ 'timestamp': a.timestamp.isoformat(),
+ }
+ for a in access_tokens]).encode('utf-8')
+ ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.