commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
3.52k
new_contents
stringlengths
21
3.18k
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.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
17
3.24k
aec62c210bc1746c6fefa12030ada548730faf62
plugins/titlegiver/titlegiver.py
plugins/titlegiver/titlegiver.py
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()) @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
Fix for titles containing cr
Fix for titles containing cr
Python
mit
Tigge/platinumshrimp
import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log - title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) + title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): - return Titlegiver.find_title(urllib2.urlopen(url).read()) + return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
Fix for titles containing cr
## Code Before: import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()) @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run()) ## Instruction: Fix for titles containing cr ## Code After: import sys import plugin import re import urllib2 from utils import url_parser from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): def __init__(self): plugin.Plugin.__init__(self, "Titlegiver") @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod def find_title(text): return title_re.search(text).group(1) def privmsg(self, server_id, user, channel, message): for url in url_parser.find_urls(message): try: self.say(server_id, channel, Titlegiver.find_title_url(url)) except: log.msg("Unable to find title for:", url) if __name__ == "__main__": sys.exit(Titlegiver.run())
# ... existing code ... from twisted.python import log title_re = re.compile(r'<title>(.*?)</title>', re.IGNORECASE|re.DOTALL) class Titlegiver(plugin.Plugin): # ... modified code ... @staticmethod def find_title_url(url): return Titlegiver.find_title(urllib2.urlopen(url).read()).strip() @staticmethod # ... rest of the code ...
bd4506dc95ee7a778a5b0f062d6d0423ade5890c
alerts/lib/alert_plugin_set.py
alerts/lib/alert_plugin_set.py
from mozdef_util.plugin_set import PluginSet from mozdef_util.utilities.logger import logger class AlertPluginSet(PluginSet): def send_message_to_plugin(self, plugin_class, message, metadata=None): if 'utctimestamp' in message and 'summary' in message: message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary']) logger.info(message_log_str) return plugin_class.onMessage(message), metadata
from mozdef_util.plugin_set import PluginSet class AlertPluginSet(PluginSet): def send_message_to_plugin(self, plugin_class, message, metadata=None): return plugin_class.onMessage(message), metadata
Remove logger entry for alert plugins receiving alerts
Remove logger entry for alert plugins receiving alerts
Python
mpl-2.0
mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mpurzynski/MozDef,mozilla/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef
from mozdef_util.plugin_set import PluginSet - from mozdef_util.utilities.logger import logger class AlertPluginSet(PluginSet): def send_message_to_plugin(self, plugin_class, message, metadata=None): - if 'utctimestamp' in message and 'summary' in message: - message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary']) - logger.info(message_log_str) - return plugin_class.onMessage(message), metadata
Remove logger entry for alert plugins receiving alerts
## Code Before: from mozdef_util.plugin_set import PluginSet from mozdef_util.utilities.logger import logger class AlertPluginSet(PluginSet): def send_message_to_plugin(self, plugin_class, message, metadata=None): if 'utctimestamp' in message and 'summary' in message: message_log_str = '{0} received message: ({1}) {2}'.format(plugin_class.__module__, message['utctimestamp'], message['summary']) logger.info(message_log_str) return plugin_class.onMessage(message), metadata ## Instruction: Remove logger entry for alert plugins receiving alerts ## Code After: from mozdef_util.plugin_set import PluginSet class AlertPluginSet(PluginSet): def send_message_to_plugin(self, plugin_class, message, metadata=None): return plugin_class.onMessage(message), metadata
# ... existing code ... from mozdef_util.plugin_set import PluginSet # ... modified code ... def send_message_to_plugin(self, plugin_class, message, metadata=None): return plugin_class.onMessage(message), metadata # ... rest of the code ...
e98a098ac6a21b0192771fd3a8d5c48468cd4340
pymatgen/phasediagram/__init__.py
pymatgen/phasediagram/__init__.py
__author__ = "Shyue" __date__ = "Mar 28 2013"
__author__ = "Shyue" __date__ = "Mar 28 2013" from .maker import PhaseDiagram, GrandPotentialPhaseDiagram, CompoundPhaseDiagram from .analyzer import PDAnalyzer from .plotter import PDPlotter
Add quick aliases to PD.
Add quick aliases to PD. Former-commit-id: 6a0680d54cc1d391a351f4d5e8ff72f696d303db [formerly 5fe981c7ed92d45548d3f7ab6abb38d149d0ada2] Former-commit-id: f76e0dc538c182b4978eb54b51cbebafa257ce04
Python
mit
aykol/pymatgen,tschaume/pymatgen,Bismarrck/pymatgen,setten/pymatgen,fraricci/pymatgen,Bismarrck/pymatgen,gVallverdu/pymatgen,richardtran415/pymatgen,johnson1228/pymatgen,davidwaroquiers/pymatgen,gpetretto/pymatgen,tallakahath/pymatgen,gpetretto/pymatgen,gVallverdu/pymatgen,matk86/pymatgen,davidwaroquiers/pymatgen,setten/pymatgen,johnson1228/pymatgen,blondegeek/pymatgen,richardtran415/pymatgen,fraricci/pymatgen,davidwaroquiers/pymatgen,blondegeek/pymatgen,setten/pymatgen,gpetretto/pymatgen,gmatteo/pymatgen,Bismarrck/pymatgen,richardtran415/pymatgen,montoyjh/pymatgen,setten/pymatgen,mbkumar/pymatgen,mbkumar/pymatgen,vorwerkc/pymatgen,blondegeek/pymatgen,davidwaroquiers/pymatgen,ndardenne/pymatgen,tschaume/pymatgen,czhengsci/pymatgen,gpetretto/pymatgen,mbkumar/pymatgen,Bismarrck/pymatgen,xhqu1981/pymatgen,vorwerkc/pymatgen,montoyjh/pymatgen,tallakahath/pymatgen,johnson1228/pymatgen,richardtran415/pymatgen,dongsenfo/pymatgen,montoyjh/pymatgen,johnson1228/pymatgen,czhengsci/pymatgen,tschaume/pymatgen,ndardenne/pymatgen,czhengsci/pymatgen,aykol/pymatgen,dongsenfo/pymatgen,vorwerkc/pymatgen,tschaume/pymatgen,gVallverdu/pymatgen,dongsenfo/pymatgen,Bismarrck/pymatgen,dongsenfo/pymatgen,matk86/pymatgen,czhengsci/pymatgen,matk86/pymatgen,nisse3000/pymatgen,tschaume/pymatgen,ndardenne/pymatgen,gVallverdu/pymatgen,xhqu1981/pymatgen,fraricci/pymatgen,aykol/pymatgen,matk86/pymatgen,gmatteo/pymatgen,vorwerkc/pymatgen,nisse3000/pymatgen,mbkumar/pymatgen,xhqu1981/pymatgen,nisse3000/pymatgen,montoyjh/pymatgen,fraricci/pymatgen,tallakahath/pymatgen,nisse3000/pymatgen,blondegeek/pymatgen
__author__ = "Shyue" __date__ = "Mar 28 2013" + from .maker import PhaseDiagram, GrandPotentialPhaseDiagram, CompoundPhaseDiagram + from .analyzer import PDAnalyzer + from .plotter import PDPlotter
Add quick aliases to PD.
## Code Before: __author__ = "Shyue" __date__ = "Mar 28 2013" ## Instruction: Add quick aliases to PD. ## Code After: __author__ = "Shyue" __date__ = "Mar 28 2013" from .maker import PhaseDiagram, GrandPotentialPhaseDiagram, CompoundPhaseDiagram from .analyzer import PDAnalyzer from .plotter import PDPlotter
# ... existing code ... __author__ = "Shyue" __date__ = "Mar 28 2013" from .maker import PhaseDiagram, GrandPotentialPhaseDiagram, CompoundPhaseDiagram from .analyzer import PDAnalyzer from .plotter import PDPlotter # ... rest of the code ...
091b1f5eb7c999a8d9b2448c1ca75941d2efb926
opentaxii/auth/sqldb/models.py
opentaxii/auth/sqldb/models.py
import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return bcrypt.hashpw(password, hashed) == hashed
import hmac import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed)
Use constant time string comparison for password checking
Use constant time string comparison for password checking
Python
bsd-3-clause
EclecticIQ/OpenTAXII,Intelworks/OpenTAXII,EclecticIQ/OpenTAXII,Intelworks/OpenTAXII
+ import hmac + import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 + class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) - def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') - return bcrypt.hashpw(password, hashed) == hashed + return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed) - -
Use constant time string comparison for password checking
## Code Before: import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return bcrypt.hashpw(password, hashed) == hashed ## Instruction: Use constant time string comparison for password checking ## Code After: import hmac import bcrypt from sqlalchemy.schema import Column from sqlalchemy.types import Integer, String from sqlalchemy.ext.declarative import declarative_base __all__ = ['Base', 'Account'] Base = declarative_base() MAX_STR_LEN = 256 class Account(Base): __tablename__ = 'accounts' id = Column(Integer, primary_key=True) username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): if isinstance(password, unicode): password = password.encode('utf-8') self.password_hash = bcrypt.hashpw(password, bcrypt.gensalt()) def is_password_valid(self, password): if isinstance(password, unicode): password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed)
// ... existing code ... import hmac import bcrypt // ... modified code ... MAX_STR_LEN = 256 class Account(Base): ... username = Column(String(MAX_STR_LEN), unique=True) password_hash = Column(String(MAX_STR_LEN)) def set_password(self, password): ... password = password.encode('utf-8') hashed = self.password_hash.encode('utf-8') return hmac.compare_digest(bcrypt.hashpw(password, hashed), hashed) // ... rest of the code ...
bf241d6c7aa96c5fca834eb1063fc009a9320329
portfolio/urls.py
portfolio/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), url(r'^weather/$', views.weather, name='weather'), url(r'^randomquote/$', views.randomquote, name='randomquote'), url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'), url(r'^twitch/$', views.twitch, name='twitch'), url(r'^tictactoe/$', views.tictactoe, name='tictactoe'), # url(r'^react/', views.react, name='react'), url(r'^react/simon', views.react, name='simon'), url(r'^react/pomodoro', views.react, name='clock'), url(r'^react/calculator', views.react, name='calc'), ]
from django.conf.urls import url from django.views.generic import TemplateView from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'), # url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), url(r'^weather/$', views.weather, name='weather'), url(r'^randomquote/$', views.randomquote, name='randomquote'), url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'), url(r'^twitch/$', views.twitch, name='twitch'), url(r'^tictactoe/$', views.tictactoe, name='tictactoe'), # url(r'^react/', views.react, name='react'), url(r'^react/simon', views.react, name='simon'), url(r'^react/pomodoro', views.react, name='clock'), url(r'^react/calculator', views.react, name='calc'), ]
Change URL pattern for contacts
Change URL pattern for contacts
Python
mit
bacarlino/portfolio,bacarlino/portfolio,bacarlino/portfolio
from django.conf.urls import url + from django.views.generic import TemplateView from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), + url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'), - url(r'^contact/$', views.contact, name='contact'), + # url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), url(r'^weather/$', views.weather, name='weather'), url(r'^randomquote/$', views.randomquote, name='randomquote'), url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'), url(r'^twitch/$', views.twitch, name='twitch'), url(r'^tictactoe/$', views.tictactoe, name='tictactoe'), # url(r'^react/', views.react, name='react'), url(r'^react/simon', views.react, name='simon'), url(r'^react/pomodoro', views.react, name='clock'), url(r'^react/calculator', views.react, name='calc'), ]
Change URL pattern for contacts
## Code Before: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), url(r'^weather/$', views.weather, name='weather'), url(r'^randomquote/$', views.randomquote, name='randomquote'), url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'), url(r'^twitch/$', views.twitch, name='twitch'), url(r'^tictactoe/$', views.tictactoe, name='tictactoe'), # url(r'^react/', views.react, name='react'), url(r'^react/simon', views.react, name='simon'), url(r'^react/pomodoro', views.react, name='clock'), url(r'^react/calculator', views.react, name='calc'), ] ## Instruction: Change URL pattern for contacts ## Code After: from django.conf.urls import url from django.views.generic import TemplateView from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'), # url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), url(r'^weather/$', views.weather, name='weather'), url(r'^randomquote/$', views.randomquote, name='randomquote'), url(r'^wikiviewer/$', views.wikiviewer, name='wikiviewer'), url(r'^twitch/$', views.twitch, name='twitch'), url(r'^tictactoe/$', views.tictactoe, name='tictactoe'), # url(r'^react/', views.react, name='react'), url(r'^react/simon', views.react, name='simon'), url(r'^react/pomodoro', views.react, name='clock'), url(r'^react/calculator', views.react, name='calc'), ]
// ... existing code ... from django.conf.urls import url from django.views.generic import TemplateView from . import views // ... modified code ... url(r'^$', views.home, name='home'), url(r'^about/$', views.about, name='about'), url(r'^contact/$', TemplateView.as_view(template_name="contact.html"), name='contact'), # url(r'^contact/$', views.contact, name='contact'), url(r'^projects/$', views.projects, name='projects'), url(r'^tribute/$', views.tribute, name='tribute'), // ... rest of the code ...
4f27be336a58d0bba66a4f7ab57126d9dd734ab9
talks/views.py
talks/views.py
from django.shortcuts import render, get_object_or_404 from config.utils import get_active_event from .models import Talk def list_talks(request): event = get_active_event() talks = event.talks.prefetch_related( 'applicants', 'applicants__user', 'skill_level', 'sponsor', ).order_by('-keynote', 'title') # Temporary hack to let only admins & committee members see the talks user = request.user permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member()) if not permitted: talks = event.talks.none() return render(request, 'talks/list_talks.html', { "talks": talks, }) def view_talk(request, slug): event = get_active_event() talk = get_object_or_404(Talk, slug=slug, event=event) return render(request, 'talks/view_talk.html', { 'talk': talk})
from django.shortcuts import render, get_object_or_404 from config.utils import get_active_event from .models import Talk def list_talks(request): event = get_active_event() talks = event.talks.prefetch_related( 'applicants', 'applicants__user', 'skill_level', 'sponsor', ).order_by('-keynote', 'title') return render(request, 'talks/list_talks.html', { "talks": talks, }) def view_talk(request, slug): event = get_active_event() talk = get_object_or_404(Talk, slug=slug, event=event) return render(request, 'talks/view_talk.html', { 'talk': talk})
Revert "Temporarily make talks visible only to committee"
Revert "Temporarily make talks visible only to committee" This reverts commit 57050b7025acb3de66024fe01255849a5ba5f1fc.
Python
bsd-3-clause
WebCampZg/conference-web,WebCampZg/conference-web,WebCampZg/conference-web
from django.shortcuts import render, get_object_or_404 from config.utils import get_active_event from .models import Talk def list_talks(request): event = get_active_event() talks = event.talks.prefetch_related( 'applicants', 'applicants__user', 'skill_level', 'sponsor', ).order_by('-keynote', 'title') - # Temporary hack to let only admins & committee members see the talks - user = request.user - permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member()) - if not permitted: - talks = event.talks.none() - return render(request, 'talks/list_talks.html', { "talks": talks, }) def view_talk(request, slug): event = get_active_event() talk = get_object_or_404(Talk, slug=slug, event=event) return render(request, 'talks/view_talk.html', { 'talk': talk})
Revert "Temporarily make talks visible only to committee"
## Code Before: from django.shortcuts import render, get_object_or_404 from config.utils import get_active_event from .models import Talk def list_talks(request): event = get_active_event() talks = event.talks.prefetch_related( 'applicants', 'applicants__user', 'skill_level', 'sponsor', ).order_by('-keynote', 'title') # Temporary hack to let only admins & committee members see the talks user = request.user permitted = user.is_authenticated and (user.is_superuser or user.is_talk_committee_member()) if not permitted: talks = event.talks.none() return render(request, 'talks/list_talks.html', { "talks": talks, }) def view_talk(request, slug): event = get_active_event() talk = get_object_or_404(Talk, slug=slug, event=event) return render(request, 'talks/view_talk.html', { 'talk': talk}) ## Instruction: Revert "Temporarily make talks visible only to committee" ## Code After: from django.shortcuts import render, get_object_or_404 from config.utils import get_active_event from .models import Talk def list_talks(request): event = get_active_event() talks = event.talks.prefetch_related( 'applicants', 'applicants__user', 'skill_level', 'sponsor', ).order_by('-keynote', 'title') return render(request, 'talks/list_talks.html', { "talks": talks, }) def view_talk(request, slug): event = get_active_event() talk = get_object_or_404(Talk, slug=slug, event=event) return render(request, 'talks/view_talk.html', { 'talk': talk})
// ... existing code ... ).order_by('-keynote', 'title') return render(request, 'talks/list_talks.html', { "talks": talks, // ... rest of the code ...
942ccea9445789423b3ea5131dcbd42c5a509797
conans/model/conan_generator.py
conans/model/conan_generator.py
from conans.util.files import save from conans.errors import ConanException from abc import ABCMeta, abstractproperty class Generator(object): __metaclass__ = ABCMeta def __init__(self, deps_build_info, build_info): self._deps_build_info = deps_build_info self._build_info = build_info @abstractproperty def deps_build_info(self): return self._deps_build_info @abstractproperty def build_info(self): return self._build_info @abstractproperty def content(self): raise NotImplementedError() @abstractproperty def filename(self): raise NotImplementedError() class GeneratorManager(object): def __init__(self): self._known_generators = {} def add(self, name, generator_class): if name in self._known_generators: raise ConanException() elif not issubclass(generator_class, Generator): raise ConanException() else: self._known_generators[name] = generator_class def remove(self, name): if name in self._known_generators: del self._known_generators[name] @property def available(self): return self._known_generators.keys() def __contains__(self, key): return key in self._known_generators def __getitem__(self, key): return self._known_generators[key]
from conans.util.files import save from conans.errors import ConanException from abc import ABCMeta, abstractproperty class Generator(object): __metaclass__ = ABCMeta def __init__(self, deps_build_info, build_info): self._deps_build_info = deps_build_info self._build_info = build_info @property def deps_build_info(self): return self._deps_build_info @property def build_info(self): return self._build_info @abstractproperty def content(self): raise NotImplementedError() @abstractproperty def filename(self): raise NotImplementedError() class GeneratorManager(object): def __init__(self): self._known_generators = {} def add(self, name, generator_class): if name in self._known_generators: raise ConanException() elif not issubclass(generator_class, Generator): raise ConanException() else: self._known_generators[name] = generator_class def remove(self, name): if name in self._known_generators: del self._known_generators[name] @property def available(self): return self._known_generators.keys() def __contains__(self, key): return key in self._known_generators def __getitem__(self, key): return self._known_generators[key]
Fix bug associated with bad ABC implementation.
Fix bug associated with bad ABC implementation.
Python
mit
tivek/conan,mropert/conan,memsharded/conan,dragly/conan,conan-io/conan,dragly/conan,Xaltotun/conan,tivek/conan,mropert/conan,memsharded/conan,luckielordie/conan,Xaltotun/conan,memsharded/conan,conan-io/conan,lasote/conan,birsoyo/conan,conan-io/conan,luckielordie/conan,lasote/conan,birsoyo/conan,memsharded/conan
from conans.util.files import save from conans.errors import ConanException from abc import ABCMeta, abstractproperty class Generator(object): __metaclass__ = ABCMeta def __init__(self, deps_build_info, build_info): self._deps_build_info = deps_build_info self._build_info = build_info - @abstractproperty + @property def deps_build_info(self): return self._deps_build_info - @abstractproperty + @property def build_info(self): return self._build_info @abstractproperty def content(self): raise NotImplementedError() @abstractproperty def filename(self): raise NotImplementedError() class GeneratorManager(object): def __init__(self): self._known_generators = {} def add(self, name, generator_class): if name in self._known_generators: raise ConanException() elif not issubclass(generator_class, Generator): raise ConanException() else: self._known_generators[name] = generator_class def remove(self, name): if name in self._known_generators: del self._known_generators[name] @property def available(self): return self._known_generators.keys() def __contains__(self, key): return key in self._known_generators def __getitem__(self, key): return self._known_generators[key]
Fix bug associated with bad ABC implementation.
## Code Before: from conans.util.files import save from conans.errors import ConanException from abc import ABCMeta, abstractproperty class Generator(object): __metaclass__ = ABCMeta def __init__(self, deps_build_info, build_info): self._deps_build_info = deps_build_info self._build_info = build_info @abstractproperty def deps_build_info(self): return self._deps_build_info @abstractproperty def build_info(self): return self._build_info @abstractproperty def content(self): raise NotImplementedError() @abstractproperty def filename(self): raise NotImplementedError() class GeneratorManager(object): def __init__(self): self._known_generators = {} def add(self, name, generator_class): if name in self._known_generators: raise ConanException() elif not issubclass(generator_class, Generator): raise ConanException() else: self._known_generators[name] = generator_class def remove(self, name): if name in self._known_generators: del self._known_generators[name] @property def available(self): return self._known_generators.keys() def __contains__(self, key): return key in self._known_generators def __getitem__(self, key): return self._known_generators[key] ## Instruction: Fix bug associated with bad ABC implementation. ## Code After: from conans.util.files import save from conans.errors import ConanException from abc import ABCMeta, abstractproperty class Generator(object): __metaclass__ = ABCMeta def __init__(self, deps_build_info, build_info): self._deps_build_info = deps_build_info self._build_info = build_info @property def deps_build_info(self): return self._deps_build_info @property def build_info(self): return self._build_info @abstractproperty def content(self): raise NotImplementedError() @abstractproperty def filename(self): raise NotImplementedError() class GeneratorManager(object): def __init__(self): self._known_generators = {} def add(self, name, generator_class): if name in self._known_generators: raise ConanException() elif not issubclass(generator_class, Generator): raise ConanException() else: self._known_generators[name] = generator_class def remove(self, name): if name in self._known_generators: del self._known_generators[name] @property def available(self): return self._known_generators.keys() def __contains__(self, key): return key in self._known_generators def __getitem__(self, key): return self._known_generators[key]
# ... existing code ... self._build_info = build_info @property def deps_build_info(self): return self._deps_build_info @property def build_info(self): return self._build_info # ... rest of the code ...
28f504dccd02046604761e997f929015a285dffd
pyQuantuccia/tests/test_get_holiday_date.py
pyQuantuccia/tests/test_get_holiday_date.py
from datetime import date import calendar print(calendar.__dir__()) print(calendar.__dict__) def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
from datetime import date import calendar def test_foo(): assert(calendar.__dir__() == "") def test_dummy(): assert(calendar.__dict__ == "") def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
Add some bogus tests to try and get this info.
Add some bogus tests to try and get this info.
Python
bsd-3-clause
jwg4/pyQuantuccia,jwg4/pyQuantuccia
from datetime import date import calendar - print(calendar.__dir__()) - print(calendar.__dict__) + + def test_foo(): + assert(calendar.__dir__() == "") + + + def test_dummy(): + assert(calendar.__dict__ == "") def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
Add some bogus tests to try and get this info.
## Code Before: from datetime import date import calendar print(calendar.__dir__()) print(calendar.__dict__) def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False) ## Instruction: Add some bogus tests to try and get this info. ## Code After: from datetime import date import calendar def test_foo(): assert(calendar.__dir__() == "") def test_dummy(): assert(calendar.__dict__ == "") def test_united_kingdom_is_business_day(): """ Check a single day to see that we can identify holidays. """ assert(calendar.united_kingdom_is_business_day(date(2017, 4, 17)) is False)
# ... existing code ... import calendar def test_foo(): assert(calendar.__dir__() == "") def test_dummy(): assert(calendar.__dict__ == "") # ... rest of the code ...
6cedfb17afbb3a869336d23cefdfcae1a65754f9
tests/test_check.py
tests/test_check.py
import unittest from binaryornot import check class TestIsBinary(unittest.TestCase): def setUp(self): pass def test_is_binary(self): pass def tearDown(self): pass if __name__ == '__main__': unittest.main()
import unittest from binaryornot.check import is_binary class TestIsBinary(unittest.TestCase): def test_css(self): self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css')) def test_json(self): self.assertFalse(is_binary('tests/files/cookiecutter.json')) def test_eot(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot')) def test_otf(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf')) def test_svg(self): self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg')) def test_ttf(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf')) def test_woff(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff')) def test_txt(self): self.assertFalse(is_binary('tests/files/robots.txt')) if __name__ == '__main__': unittest.main()
Add lots of miserably failing tests.
Add lots of miserably failing tests.
Python
bsd-3-clause
pombredanne/binaryornot,0k/binaryornot,pombredanne/binaryornot,pombredanne/binaryornot,audreyr/binaryornot,audreyr/binaryornot,hackebrot/binaryornot,hackebrot/binaryornot,0k/binaryornot,audreyr/binaryornot,hackebrot/binaryornot
import unittest - from binaryornot import check + from binaryornot.check import is_binary class TestIsBinary(unittest.TestCase): - def setUp(self): + def test_css(self): - pass + self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css')) - def test_is_binary(self): + def test_json(self): - pass + self.assertFalse(is_binary('tests/files/cookiecutter.json')) - def tearDown(self): + def test_eot(self): - pass + self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot')) + + def test_otf(self): + self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf')) + + def test_svg(self): + self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg')) + + def test_ttf(self): + self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf')) + + def test_woff(self): + self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff')) + + def test_txt(self): + self.assertFalse(is_binary('tests/files/robots.txt')) + if __name__ == '__main__': unittest.main()
Add lots of miserably failing tests.
## Code Before: import unittest from binaryornot import check class TestIsBinary(unittest.TestCase): def setUp(self): pass def test_is_binary(self): pass def tearDown(self): pass if __name__ == '__main__': unittest.main() ## Instruction: Add lots of miserably failing tests. ## Code After: import unittest from binaryornot.check import is_binary class TestIsBinary(unittest.TestCase): def test_css(self): self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css')) def test_json(self): self.assertFalse(is_binary('tests/files/cookiecutter.json')) def test_eot(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot')) def test_otf(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf')) def test_svg(self): self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg')) def test_ttf(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf')) def test_woff(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff')) def test_txt(self): self.assertFalse(is_binary('tests/files/robots.txt')) if __name__ == '__main__': unittest.main()
... import unittest from binaryornot.check import is_binary ... class TestIsBinary(unittest.TestCase): def test_css(self): self.assertFalse(is_binary('tests/files/bootstrap-glyphicons.css')) def test_json(self): self.assertFalse(is_binary('tests/files/cookiecutter.json')) def test_eot(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.eot')) def test_otf(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.otf')) def test_svg(self): self.assertFalse(is_binary('tests/files/glyphiconshalflings-regular.svg')) def test_ttf(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.ttf')) def test_woff(self): self.assertTrue(is_binary('tests/files/glyphiconshalflings-regular.woff')) def test_txt(self): self.assertFalse(is_binary('tests/files/robots.txt')) if __name__ == '__main__': ...
9f6b12b2579f228fd9d04151771a22474a2744a3
tabula/wrapper.py
tabula/wrapper.py
import subprocess, io, shlex, os import pandas as pd def read_pdf_table(input_path, options=""): jar_path = os.path.abspath(os.path.dirname(__file__)) JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar" args = ["java", "-jar"] + [jar_path + "/" + JAR_NAME] + shlex.split(options) + [input_path] result = subprocess.run(args, stdout=subprocess.PIPE) if len(result.stdout) == 0: return return pd.read_csv(io.BytesIO(result.stdout))
import subprocess, io, shlex, os import pandas as pd def read_pdf_table(input_path, options=""): JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar" jar_dir = os.path.abspath(os.path.dirname(__file__)) jar_path = os.path.join(jar_dir, JAR_NAME) args = ["java", "-jar", jar_path] + shlex.split(options) + [input_path] result = subprocess.run(args, stdout=subprocess.PIPE) if len(result.stdout) == 0: return return pd.read_csv(io.BytesIO(result.stdout))
Use os.path.join for Jar path to make it OS independent
Use os.path.join for Jar path to make it OS independent
Python
mit
chezou/tabula-py
import subprocess, io, shlex, os import pandas as pd def read_pdf_table(input_path, options=""): - jar_path = os.path.abspath(os.path.dirname(__file__)) JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar" + jar_dir = os.path.abspath(os.path.dirname(__file__)) + jar_path = os.path.join(jar_dir, JAR_NAME) - args = ["java", "-jar"] + [jar_path + "/" + JAR_NAME] + shlex.split(options) + [input_path] + args = ["java", "-jar", jar_path] + shlex.split(options) + [input_path] result = subprocess.run(args, stdout=subprocess.PIPE) if len(result.stdout) == 0: return return pd.read_csv(io.BytesIO(result.stdout))
Use os.path.join for Jar path to make it OS independent
## Code Before: import subprocess, io, shlex, os import pandas as pd def read_pdf_table(input_path, options=""): jar_path = os.path.abspath(os.path.dirname(__file__)) JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar" args = ["java", "-jar"] + [jar_path + "/" + JAR_NAME] + shlex.split(options) + [input_path] result = subprocess.run(args, stdout=subprocess.PIPE) if len(result.stdout) == 0: return return pd.read_csv(io.BytesIO(result.stdout)) ## Instruction: Use os.path.join for Jar path to make it OS independent ## Code After: import subprocess, io, shlex, os import pandas as pd def read_pdf_table(input_path, options=""): JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar" jar_dir = os.path.abspath(os.path.dirname(__file__)) jar_path = os.path.join(jar_dir, JAR_NAME) args = ["java", "-jar", jar_path] + shlex.split(options) + [input_path] result = subprocess.run(args, stdout=subprocess.PIPE) if len(result.stdout) == 0: return return pd.read_csv(io.BytesIO(result.stdout))
... def read_pdf_table(input_path, options=""): JAR_NAME = "tabula-0.9.1-jar-with-dependencies.jar" jar_dir = os.path.abspath(os.path.dirname(__file__)) jar_path = os.path.join(jar_dir, JAR_NAME) args = ["java", "-jar", jar_path] + shlex.split(options) + [input_path] result = subprocess.run(args, stdout=subprocess.PIPE) ...
2234cbdc78e81329c4110f4eb4e69f429d9b6fb5
csvkit/convert/dbase.py
csvkit/convert/dbase.py
from cStringIO import StringIO import dbf from csvkit import table def dbf2csv(f, **kwargs): """ Convert a dBASE .dbf file to csv. """ db = dbf.Table(f.name) headers = db.field_names column_ids = range(len(headers)) data_columns = [[] for c in headers] for row in db: for i, d in enumerate(row): try: data_columns[i].append(unicode(row[column_ids[i]]).strip()) except IndexError: # Non-rectangular data is truncated break columns = [] for i, c in enumerate(data_columns): columns.append(table.Column(column_ids[i], headers[i], c)) tab = table.Table(columns=columns) o = StringIO() output = tab.to_csv(o) output = o.getvalue() o.close() return output
from cStringIO import StringIO import dbf from csvkit import table def dbf2csv(f, **kwargs): """ Convert a dBASE .dbf file to csv. """ with dbf.Table(f.name) as db: headers = db.field_names column_ids = range(len(headers)) data_columns = [[] for c in headers] for row in db: for i, d in enumerate(row): try: data_columns[i].append(unicode(row[column_ids[i]]).strip()) except IndexError: # Non-rectangular data is truncated break columns = [] for i, c in enumerate(data_columns): columns.append(table.Column(column_ids[i], headers[i], c)) tab = table.Table(columns=columns) o = StringIO() output = tab.to_csv(o) output = o.getvalue() o.close() return output
Fix for bug in latest dbf module. Pypy passes now.
Fix for bug in latest dbf module. Pypy passes now.
Python
mit
bradparks/csvkit__query_join_filter_CSV_cli,matterker/csvkit,unpingco/csvkit,kyeoh/csvkit,Jobava/csvkit,snuggles08/csvkit,dannguyen/csvkit,cypreess/csvkit,jpalvarezf/csvkit,archaeogeek/csvkit,gepuro/csvkit,haginara/csvkit,barentsen/csvkit,bmispelon/csvkit,wjr1985/csvkit,KarrieK/csvkit,onyxfish/csvkit,wireservice/csvkit,moradology/csvkit,aequitas/csvkit,doganmeh/csvkit,themiurgo/csvkit,Tabea-K/csvkit,elcritch/csvkit,tlevine/csvkit,metasoarous/csvkit,reubano/csvkit,nriyer/csvkit,arowla/csvkit
from cStringIO import StringIO import dbf from csvkit import table def dbf2csv(f, **kwargs): """ Convert a dBASE .dbf file to csv. + """ + with dbf.Table(f.name) as db: + headers = db.field_names + column_ids = range(len(headers)) - """ - db = dbf.Table(f.name) - headers = db.field_names + data_columns = [[] for c in headers] - column_ids = range(len(headers)) + for row in db: + for i, d in enumerate(row): + try: + data_columns[i].append(unicode(row[column_ids[i]]).strip()) + except IndexError: + # Non-rectangular data is truncated + break - data_columns = [[] for c in headers] + columns = [] - for row in db: - for i, d in enumerate(row): + for i, c in enumerate(data_columns): + columns.append(table.Column(column_ids[i], headers[i], c)) - try: - data_columns[i].append(unicode(row[column_ids[i]]).strip()) - except IndexError: - # Non-rectangular data is truncated - break - columns = [] + tab = table.Table(columns=columns) - for i, c in enumerate(data_columns): - columns.append(table.Column(column_ids[i], headers[i], c)) + o = StringIO() + output = tab.to_csv(o) + output = o.getvalue() + o.close() - tab = table.Table(columns=columns) - - o = StringIO() - output = tab.to_csv(o) - output = o.getvalue() - o.close() - - return output + return output
Fix for bug in latest dbf module. Pypy passes now.
## Code Before: from cStringIO import StringIO import dbf from csvkit import table def dbf2csv(f, **kwargs): """ Convert a dBASE .dbf file to csv. """ db = dbf.Table(f.name) headers = db.field_names column_ids = range(len(headers)) data_columns = [[] for c in headers] for row in db: for i, d in enumerate(row): try: data_columns[i].append(unicode(row[column_ids[i]]).strip()) except IndexError: # Non-rectangular data is truncated break columns = [] for i, c in enumerate(data_columns): columns.append(table.Column(column_ids[i], headers[i], c)) tab = table.Table(columns=columns) o = StringIO() output = tab.to_csv(o) output = o.getvalue() o.close() return output ## Instruction: Fix for bug in latest dbf module. Pypy passes now. ## Code After: from cStringIO import StringIO import dbf from csvkit import table def dbf2csv(f, **kwargs): """ Convert a dBASE .dbf file to csv. """ with dbf.Table(f.name) as db: headers = db.field_names column_ids = range(len(headers)) data_columns = [[] for c in headers] for row in db: for i, d in enumerate(row): try: data_columns[i].append(unicode(row[column_ids[i]]).strip()) except IndexError: # Non-rectangular data is truncated break columns = [] for i, c in enumerate(data_columns): columns.append(table.Column(column_ids[i], headers[i], c)) tab = table.Table(columns=columns) o = StringIO() output = tab.to_csv(o) output = o.getvalue() o.close() return output
# ... existing code ... """ Convert a dBASE .dbf file to csv. """ with dbf.Table(f.name) as db: headers = db.field_names column_ids = range(len(headers)) data_columns = [[] for c in headers] for row in db: for i, d in enumerate(row): try: data_columns[i].append(unicode(row[column_ids[i]]).strip()) except IndexError: # Non-rectangular data is truncated break columns = [] for i, c in enumerate(data_columns): columns.append(table.Column(column_ids[i], headers[i], c)) tab = table.Table(columns=columns) o = StringIO() output = tab.to_csv(o) output = o.getvalue() o.close() return output # ... rest of the code ...
0c3529bd264d5512e31d828c65676baff6edefa6
pinax/waitinglist/templatetags/pinax_waitinglist_tags.py
pinax/waitinglist/templatetags/pinax_waitinglist_tags.py
from django import template from ..forms import WaitingListEntryForm register = template.Library() @register.assignment_tag def waitinglist_entry_form(): """ Get a (new) form object to post a new comment. Syntax:: {% waitinglist_entry_form as [varname] %} """ return WaitingListEntryForm()
from django import template from ..forms import WaitingListEntryForm register = template.Library() @register.simple_tag(takes_context=True) def waitinglist_entry_form(context): """ Get a (new) form object to post a new comment. Syntax:: {% waitinglist_entry_form as [varname] %} """ initial = {} if "request" in context: initial.update({ "referrer": context["request"].META.get("HTTP_REFERER", ""), "campaign": context["request"].GET.get("wlc", "") }) return WaitingListEntryForm(initial=initial)
Update template tag to also take context
Update template tag to also take context
Python
mit
pinax/pinax-waitinglist,pinax/pinax-waitinglist
from django import template from ..forms import WaitingListEntryForm register = template.Library() - @register.assignment_tag + @register.simple_tag(takes_context=True) - def waitinglist_entry_form(): + def waitinglist_entry_form(context): """ Get a (new) form object to post a new comment. Syntax:: {% waitinglist_entry_form as [varname] %} """ + initial = {} + if "request" in context: + initial.update({ + "referrer": context["request"].META.get("HTTP_REFERER", ""), + "campaign": context["request"].GET.get("wlc", "") + }) - return WaitingListEntryForm() + return WaitingListEntryForm(initial=initial)
Update template tag to also take context
## Code Before: from django import template from ..forms import WaitingListEntryForm register = template.Library() @register.assignment_tag def waitinglist_entry_form(): """ Get a (new) form object to post a new comment. Syntax:: {% waitinglist_entry_form as [varname] %} """ return WaitingListEntryForm() ## Instruction: Update template tag to also take context ## Code After: from django import template from ..forms import WaitingListEntryForm register = template.Library() @register.simple_tag(takes_context=True) def waitinglist_entry_form(context): """ Get a (new) form object to post a new comment. Syntax:: {% waitinglist_entry_form as [varname] %} """ initial = {} if "request" in context: initial.update({ "referrer": context["request"].META.get("HTTP_REFERER", ""), "campaign": context["request"].GET.get("wlc", "") }) return WaitingListEntryForm(initial=initial)
// ... existing code ... @register.simple_tag(takes_context=True) def waitinglist_entry_form(context): """ Get a (new) form object to post a new comment. // ... modified code ... """ initial = {} if "request" in context: initial.update({ "referrer": context["request"].META.get("HTTP_REFERER", ""), "campaign": context["request"].GET.get("wlc", "") }) return WaitingListEntryForm(initial=initial) // ... rest of the code ...
bece8b815ea3359433df708272ec3065d2c2a231
examples/basic_siggen.py
examples/basic_siggen.py
from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time, logging import matplotlib import matplotlib.pyplot as plt logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("example") i = m.discover_instrument() if i is None or i.type != 'signal_generator': print("No or wrong instrument deployed") i = SignalGenerator() m.attach_instrument(i) else: print("Attached to existing Signal Generator") m.take_ownership() try: i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10) i.commit() finally: m.close()
from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("example") i = SignalGenerator() m.attach_instrument(i) try: i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) # Amplitude modulate the CH1 sinewave with another internally-generated sinewave. # 100% modulation depth at 10Hz. i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10) i.commit() finally: m.close()
Simplify and clean the siggen example
PM-133: Simplify and clean the siggen example
Python
mit
liquidinstruments/pymoku
from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * + import time - import time, logging - - import matplotlib - import matplotlib.pyplot as plt - - logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') - logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("example") - - i = m.discover_instrument() - - if i is None or i.type != 'signal_generator': - print("No or wrong instrument deployed") - i = SignalGenerator() + i = SignalGenerator() - m.attach_instrument(i) + m.attach_instrument(i) - else: - print("Attached to existing Signal Generator") - m.take_ownership() try: i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) + + # Amplitude modulate the CH1 sinewave with another internally-generated sinewave. + # 100% modulation depth at 10Hz. i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10) i.commit() finally: m.close()
Simplify and clean the siggen example
## Code Before: from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time, logging import matplotlib import matplotlib.pyplot as plt logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("example") i = m.discover_instrument() if i is None or i.type != 'signal_generator': print("No or wrong instrument deployed") i = SignalGenerator() m.attach_instrument(i) else: print("Attached to existing Signal Generator") m.take_ownership() try: i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10) i.commit() finally: m.close() ## Instruction: Simplify and clean the siggen example ## Code After: from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("example") i = SignalGenerator() m.attach_instrument(i) try: i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) # Amplitude modulate the CH1 sinewave with another internally-generated sinewave. # 100% modulation depth at 10Hz. i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10) i.commit() finally: m.close()
# ... existing code ... from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time # Use Moku.get_by_serial() or get_by_name() if you don't know the IP m = Moku.get_by_name("example") i = SignalGenerator() m.attach_instrument(i) try: # ... modified code ... i.synth_sinewave(1, 1.0, 1000000) i.synth_squarewave(2, 1.0, 2000000, risetime=0.1, falltime=0.1, duty=0.3) # Amplitude modulate the CH1 sinewave with another internally-generated sinewave. # 100% modulation depth at 10Hz. i.synth_modulate(1, SG_MOD_AMPL, SG_MODSOURCE_INT, 1, 10) i.commit() # ... rest of the code ...
631983a14f941fa745b6e7f4b32fe1ef697d5703
tests/mixers/denontest.py
tests/mixers/denontest.py
import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('00') def write(self, x): pass def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('MV00\r') def write(self, x): if x[2] != '?': self.ret_val = bytes(x) def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
Update denon device mock to reflect mixer changes
Update denon device mock to reflect mixer changes
Python
apache-2.0
mokieyue/mopidy,diandiankan/mopidy,bacontext/mopidy,tkem/mopidy,bacontext/mopidy,priestd09/mopidy,ZenithDK/mopidy,tkem/mopidy,quartz55/mopidy,bencevans/mopidy,vrs01/mopidy,priestd09/mopidy,jodal/mopidy,glogiotatidis/mopidy,ZenithDK/mopidy,rawdlite/mopidy,dbrgn/mopidy,bencevans/mopidy,abarisain/mopidy,jmarsik/mopidy,ali/mopidy,hkariti/mopidy,hkariti/mopidy,swak/mopidy,kingosticks/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,pacificIT/mopidy,vrs01/mopidy,SuperStarPL/mopidy,swak/mopidy,bencevans/mopidy,hkariti/mopidy,jmarsik/mopidy,jcass77/mopidy,diandiankan/mopidy,jmarsik/mopidy,mokieyue/mopidy,vrs01/mopidy,jcass77/mopidy,mokieyue/mopidy,dbrgn/mopidy,tkem/mopidy,ZenithDK/mopidy,pacificIT/mopidy,glogiotatidis/mopidy,adamcik/mopidy,jcass77/mopidy,bacontext/mopidy,woutervanwijk/mopidy,adamcik/mopidy,hkariti/mopidy,rawdlite/mopidy,abarisain/mopidy,mopidy/mopidy,quartz55/mopidy,jodal/mopidy,dbrgn/mopidy,liamw9534/mopidy,tkem/mopidy,mopidy/mopidy,jmarsik/mopidy,kingosticks/mopidy,pacificIT/mopidy,ali/mopidy,vrs01/mopidy,diandiankan/mopidy,SuperStarPL/mopidy,rawdlite/mopidy,mopidy/mopidy,swak/mopidy,diandiankan/mopidy,glogiotatidis/mopidy,woutervanwijk/mopidy,ali/mopidy,priestd09/mopidy,rawdlite/mopidy,quartz55/mopidy,bacontext/mopidy,liamw9534/mopidy,swak/mopidy,mokieyue/mopidy,adamcik/mopidy,quartz55/mopidy,SuperStarPL/mopidy,pacificIT/mopidy,bencevans/mopidy,ali/mopidy,jodal/mopidy,glogiotatidis/mopidy,dbrgn/mopidy
import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True - self.ret_val = bytes('00') + self.ret_val = bytes('MV00\r') def write(self, x): - pass + if x[2] != '?': + self.ret_val = bytes(x) def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
Update denon device mock to reflect mixer changes
## Code Before: import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('00') def write(self, x): pass def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open) ## Instruction: Update denon device mock to reflect mixer changes ## Code After: import unittest import os from mopidy.mixers.denon import DenonMixer class DenonMixerDeviceMock(object): def __init__(self): self._open = True self.ret_val = bytes('MV00\r') def write(self, x): if x[2] != '?': self.ret_val = bytes(x) def read(self, x): return self.ret_val def isOpen(self): return self._open def open(self): self._open = True class DenonMixerTest(unittest.TestCase): def setUp(self): self.m = DenonMixer() self.m._device = DenonMixerDeviceMock() def test_volume_set_to_min(self): self.m.volume = 0 self.assertEqual(self.m.volume, 0) def test_volume_set_to_max(self): self.m.volume = 100 self.assertEqual(self.m.volume, 99) def test_volume_set_to_below_min_results_in_min(self): self.m.volume = -10 self.assertEqual(self.m.volume, 0) def test_volume_set_to_above_max_results_in_max(self): self.m.volume = 110 self.assertEqual(self.m.volume, 99) def test_reopen_device(self): self.m._device._open = False self.m.volume = 10 self.assertTrue(self.m._device._open)
// ... existing code ... def __init__(self): self._open = True self.ret_val = bytes('MV00\r') def write(self, x): if x[2] != '?': self.ret_val = bytes(x) def read(self, x): return self.ret_val // ... rest of the code ...
519a5afc8c8561166f4d8fb0ca43f0ff35a0389b
addons/hr_payroll_account/__manifest__.py
addons/hr_payroll_account/__manifest__.py
{ 'name': 'Payroll Accounting', 'category': 'Human Resources', 'description': """ Generic Payroll system Integrated with Accounting. ================================================== * Expense Encoding * Payment Encoding * Company Contribution Management """, 'depends': ['hr_payroll', 'account', 'hr_expense'], 'data': ['views/hr_payroll_account_views.xml'], 'demo': ['data/hr_payroll_account_demo.xml'], 'test': ['../account/test/account_minimal_test.xml'], }
{ 'name': 'Payroll Accounting', 'category': 'Human Resources', 'description': """ Generic Payroll system Integrated with Accounting. ================================================== * Expense Encoding * Payment Encoding * Company Contribution Management """, 'depends': ['hr_payroll', 'account'], 'data': ['views/hr_payroll_account_views.xml'], 'demo': ['data/hr_payroll_account_demo.xml'], 'test': ['../account/test/account_minimal_test.xml'], }
Remove useless dependency to hr_expense
[IMP] hr_payroll_account: Remove useless dependency to hr_expense
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
{ 'name': 'Payroll Accounting', 'category': 'Human Resources', 'description': """ Generic Payroll system Integrated with Accounting. ================================================== * Expense Encoding * Payment Encoding * Company Contribution Management """, - 'depends': ['hr_payroll', 'account', 'hr_expense'], + 'depends': ['hr_payroll', 'account'], 'data': ['views/hr_payroll_account_views.xml'], 'demo': ['data/hr_payroll_account_demo.xml'], 'test': ['../account/test/account_minimal_test.xml'], }
Remove useless dependency to hr_expense
## Code Before: { 'name': 'Payroll Accounting', 'category': 'Human Resources', 'description': """ Generic Payroll system Integrated with Accounting. ================================================== * Expense Encoding * Payment Encoding * Company Contribution Management """, 'depends': ['hr_payroll', 'account', 'hr_expense'], 'data': ['views/hr_payroll_account_views.xml'], 'demo': ['data/hr_payroll_account_demo.xml'], 'test': ['../account/test/account_minimal_test.xml'], } ## Instruction: Remove useless dependency to hr_expense ## Code After: { 'name': 'Payroll Accounting', 'category': 'Human Resources', 'description': """ Generic Payroll system Integrated with Accounting. ================================================== * Expense Encoding * Payment Encoding * Company Contribution Management """, 'depends': ['hr_payroll', 'account'], 'data': ['views/hr_payroll_account_views.xml'], 'demo': ['data/hr_payroll_account_demo.xml'], 'test': ['../account/test/account_minimal_test.xml'], }
// ... existing code ... * Company Contribution Management """, 'depends': ['hr_payroll', 'account'], 'data': ['views/hr_payroll_account_views.xml'], 'demo': ['data/hr_payroll_account_demo.xml'], // ... rest of the code ...
987c54559cb52370fc459a30cdbdfd0e38c5ef62
plata/context_processors.py
plata/context_processors.py
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance """ shop = plata.shop_instance() if not shop: return {} return {'plata': { 'shop': shop, 'order': shop.order_from_request(request), 'contact': shop.contact_from_user(request.user), }}
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_includes_tax``: Whether prices include tax or not """ shop = plata.shop_instance() if not shop: return {} return {'plata': { 'shop': shop, 'order': shop.order_from_request(request), 'contact': shop.contact_from_user(request.user), 'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX, }}
Add the variable `plata.price_includes_tax` to the template context
Add the variable `plata.price_includes_tax` to the template context
Python
bsd-3-clause
armicron/plata,armicron/plata,stefanklug/plata,armicron/plata
import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance + * ``plata.price_includes_tax``: Whether prices include tax or not """ shop = plata.shop_instance() if not shop: return {} return {'plata': { 'shop': shop, 'order': shop.order_from_request(request), 'contact': shop.contact_from_user(request.user), + 'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX, }}
Add the variable `plata.price_includes_tax` to the template context
## Code Before: import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance """ shop = plata.shop_instance() if not shop: return {} return {'plata': { 'shop': shop, 'order': shop.order_from_request(request), 'contact': shop.contact_from_user(request.user), }} ## Instruction: Add the variable `plata.price_includes_tax` to the template context ## Code After: import plata def plata_context(request): """ Adds a few variables from Plata to the context if they are available: * ``plata.shop``: The current :class:`plata.shop.views.Shop` instance * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_includes_tax``: Whether prices include tax or not """ shop = plata.shop_instance() if not shop: return {} return {'plata': { 'shop': shop, 'order': shop.order_from_request(request), 'contact': shop.contact_from_user(request.user), 'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX, }}
... * ``plata.order``: The current order * ``plata.contact``: The current contact instance * ``plata.price_includes_tax``: Whether prices include tax or not """ ... 'order': shop.order_from_request(request), 'contact': shop.contact_from_user(request.user), 'price_includes_tax': plata.settings.PLATA_PRICE_INCLUDES_TAX, }} ...
cd27849acae57a0382f66116771491576177a39e
setup.py
setup.py
from distutils.core import setup __VERSION__ = '0.2.4' long_description = "See https://furtive.readthedocs.org" setup(name='Furtive', version=__VERSION__, description='File Integrity Verification System', author='Derrick Bryant', author_email='[email protected]', long_description=long_description, license='MIT', packages=['furtive'], scripts=['scripts/furtive'], url='https://furtive.readthedocs.org', install_requires=[ 'PyYAML==3.11', 'argparse==1.4.0' ] )
from distutils.core import setup __VERSION__ = '0.2.4' long_description = """ Github: https://github.com/dbryant4/furtive """ setup(name='Furtive', version=__VERSION__, description='File Integrity Verification System', author='Derrick Bryant', author_email='[email protected]', long_description=long_description, license='MIT', packages=['furtive'], scripts=['scripts/furtive'], url='https://furtive.readthedocs.org', download_url='https://github.com/dbryant4/furtive', install_requires=[ 'PyYAML==3.11', 'argparse==1.4.0' ] )
Add links to github project page
Add links to github project page
Python
mit
dbryant4/furtive
from distutils.core import setup __VERSION__ = '0.2.4' - long_description = "See https://furtive.readthedocs.org" + long_description = """ + Github: https://github.com/dbryant4/furtive + """ setup(name='Furtive', version=__VERSION__, description='File Integrity Verification System', author='Derrick Bryant', author_email='[email protected]', long_description=long_description, license='MIT', packages=['furtive'], scripts=['scripts/furtive'], url='https://furtive.readthedocs.org', + download_url='https://github.com/dbryant4/furtive', install_requires=[ 'PyYAML==3.11', 'argparse==1.4.0' ] )
Add links to github project page
## Code Before: from distutils.core import setup __VERSION__ = '0.2.4' long_description = "See https://furtive.readthedocs.org" setup(name='Furtive', version=__VERSION__, description='File Integrity Verification System', author='Derrick Bryant', author_email='[email protected]', long_description=long_description, license='MIT', packages=['furtive'], scripts=['scripts/furtive'], url='https://furtive.readthedocs.org', install_requires=[ 'PyYAML==3.11', 'argparse==1.4.0' ] ) ## Instruction: Add links to github project page ## Code After: from distutils.core import setup __VERSION__ = '0.2.4' long_description = """ Github: https://github.com/dbryant4/furtive """ setup(name='Furtive', version=__VERSION__, description='File Integrity Verification System', author='Derrick Bryant', author_email='[email protected]', long_description=long_description, license='MIT', packages=['furtive'], scripts=['scripts/furtive'], url='https://furtive.readthedocs.org', download_url='https://github.com/dbryant4/furtive', install_requires=[ 'PyYAML==3.11', 'argparse==1.4.0' ] )
// ... existing code ... __VERSION__ = '0.2.4' long_description = """ Github: https://github.com/dbryant4/furtive """ setup(name='Furtive', // ... modified code ... scripts=['scripts/furtive'], url='https://furtive.readthedocs.org', download_url='https://github.com/dbryant4/furtive', install_requires=[ 'PyYAML==3.11', // ... rest of the code ...
12acfff456e1a696d1117b20b8843c6789ee38bb
wake/views.py
wake/views.py
from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events)
from been.couch import CouchStore from flask import render_template, abort, request, url_for from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed from datetime import datetime from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events) @app.route('/recent.atom') def recent_feed(): feed = AtomFeed('Recent Posts', feed_url=request.url, url=request.url_root, generator=('Wake', None, None)) sources = store.get_sources() for event in store.events(): if sources[event['source']].get('syndicate'): feed.add(event['title'], unicode(event['content']), content_type='html', author=event.get('author', ''), url=urljoin(request.url_root, url_for('by_slug', slug=event.get('slug', ''))), updated=datetime.fromtimestamp(event['timestamp']), published=datetime.fromtimestamp(event['timestamp'])) return feed.get_response()
Add Atom feed for events that have 'syndicate' set in their source config.
Add Atom feed for events that have 'syndicate' set in their source config.
Python
bsd-3-clause
chromakode/wake
from been.couch import CouchStore - from flask import render_template, abort + from flask import render_template, abort, request, url_for + from urlparse import urljoin + from werkzeug.contrib.atom import AtomFeed + from datetime import datetime from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events) + @app.route('/recent.atom') + def recent_feed(): + feed = AtomFeed('Recent Posts', feed_url=request.url, url=request.url_root, + generator=('Wake', None, None)) + sources = store.get_sources() + for event in store.events(): + if sources[event['source']].get('syndicate'): + feed.add(event['title'], + unicode(event['content']), + content_type='html', + author=event.get('author', ''), + url=urljoin(request.url_root, url_for('by_slug', slug=event.get('slug', ''))), + updated=datetime.fromtimestamp(event['timestamp']), + published=datetime.fromtimestamp(event['timestamp'])) + return feed.get_response()
Add Atom feed for events that have 'syndicate' set in their source config.
## Code Before: from been.couch import CouchStore from flask import render_template, abort from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events) ## Instruction: Add Atom feed for events that have 'syndicate' set in their source config. ## Code After: from been.couch import CouchStore from flask import render_template, abort, request, url_for from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed from datetime import datetime from wake import app store = CouchStore().load() @app.route('/') def wake(): return render_template('stream.html', events=store.collapsed_events()) @app.route('/<slug>') def by_slug(slug): events = list(store.events_by_slug(slug)) if not events: abort(404) return render_template('stream.html', events=events) @app.route('/recent.atom') def recent_feed(): feed = AtomFeed('Recent Posts', feed_url=request.url, url=request.url_root, generator=('Wake', None, None)) sources = store.get_sources() for event in store.events(): if sources[event['source']].get('syndicate'): feed.add(event['title'], unicode(event['content']), content_type='html', author=event.get('author', ''), url=urljoin(request.url_root, url_for('by_slug', slug=event.get('slug', ''))), updated=datetime.fromtimestamp(event['timestamp']), published=datetime.fromtimestamp(event['timestamp'])) return feed.get_response()
... from been.couch import CouchStore from flask import render_template, abort, request, url_for from urlparse import urljoin from werkzeug.contrib.atom import AtomFeed from datetime import datetime from wake import app ... return render_template('stream.html', events=events) @app.route('/recent.atom') def recent_feed(): feed = AtomFeed('Recent Posts', feed_url=request.url, url=request.url_root, generator=('Wake', None, None)) sources = store.get_sources() for event in store.events(): if sources[event['source']].get('syndicate'): feed.add(event['title'], unicode(event['content']), content_type='html', author=event.get('author', ''), url=urljoin(request.url_root, url_for('by_slug', slug=event.get('slug', ''))), updated=datetime.fromtimestamp(event['timestamp']), published=datetime.fromtimestamp(event['timestamp'])) return feed.get_response() ...
52058f7ea882d9d62d1003796520387e2a092c6c
volt/hooks.py
volt/hooks.py
"""Hooks for various events.""" # Copyright (c) 2012-2022 Wibowo Arindrarto <[email protected]> # SPDX-License-Identifier: BSD-3-Clause import sys import structlog from typing import Any from . import signals as s __all__ = [ "log", "post_site_load_engines", "post_site_collect_targets", "pre_site_write", ] def log() -> Any: """Return a logger for a hook function. This function is meant to be called inside the top-level hook function. That is, the function that is decorated with the hook. Calling this elsewhere will result in the log message showing incorrect hook names. :returns: A :class:`structlog.BoundLogger` instance ready for logging. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name mod_name = frame.f_globals["__name__"] return structlog.get_logger(mod_name, hook=hook_name) post_site_load_engines = s.post_site_load_engines.connect post_site_collect_targets = s.post_site_collect_targets.connect pre_site_write = s.pre_site_write.connect
"""Hooks for various events.""" # Copyright (c) 2012-2022 Wibowo Arindrarto <[email protected]> # SPDX-License-Identifier: BSD-3-Clause import sys import structlog from typing import Any from . import signals as s __all__ = [ "log", "post_site_load_engines", "post_site_collect_targets", "pre_site_write", ] def name() -> str: """Return the name of the current hook. This function must be called inside the top-level hook function. That is, the function that is decorated with the hook. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name return hook_name def log() -> Any: """Return a logger for a hook function. This function is meant to be called inside the top-level hook function. That is, the function that is decorated with the hook. Calling this elsewhere will result in the log message showing incorrect hook names. :returns: A :class:`structlog.BoundLogger` instance ready for logging. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name mod_name = frame.f_globals["__name__"] return structlog.get_logger(mod_name, hook=hook_name) post_site_load_engines = s.post_site_load_engines.connect post_site_collect_targets = s.post_site_collect_targets.connect pre_site_write = s.pre_site_write.connect
Add hook.name function for inferring hook names
feat: Add hook.name function for inferring hook names
Python
bsd-3-clause
bow/volt
"""Hooks for various events.""" # Copyright (c) 2012-2022 Wibowo Arindrarto <[email protected]> # SPDX-License-Identifier: BSD-3-Clause import sys import structlog from typing import Any from . import signals as s __all__ = [ "log", "post_site_load_engines", "post_site_collect_targets", "pre_site_write", ] + + + def name() -> str: + """Return the name of the current hook. + + This function must be called inside the top-level hook function. That is, the + function that is decorated with the hook. + + """ + frame = sys._getframe(1) + hook_name = frame.f_code.co_name + return hook_name def log() -> Any: """Return a logger for a hook function. This function is meant to be called inside the top-level hook function. That is, the function that is decorated with the hook. Calling this elsewhere will result in the log message showing incorrect hook names. :returns: A :class:`structlog.BoundLogger` instance ready for logging. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name mod_name = frame.f_globals["__name__"] return structlog.get_logger(mod_name, hook=hook_name) post_site_load_engines = s.post_site_load_engines.connect post_site_collect_targets = s.post_site_collect_targets.connect pre_site_write = s.pre_site_write.connect
Add hook.name function for inferring hook names
## Code Before: """Hooks for various events.""" # Copyright (c) 2012-2022 Wibowo Arindrarto <[email protected]> # SPDX-License-Identifier: BSD-3-Clause import sys import structlog from typing import Any from . import signals as s __all__ = [ "log", "post_site_load_engines", "post_site_collect_targets", "pre_site_write", ] def log() -> Any: """Return a logger for a hook function. This function is meant to be called inside the top-level hook function. That is, the function that is decorated with the hook. Calling this elsewhere will result in the log message showing incorrect hook names. :returns: A :class:`structlog.BoundLogger` instance ready for logging. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name mod_name = frame.f_globals["__name__"] return structlog.get_logger(mod_name, hook=hook_name) post_site_load_engines = s.post_site_load_engines.connect post_site_collect_targets = s.post_site_collect_targets.connect pre_site_write = s.pre_site_write.connect ## Instruction: Add hook.name function for inferring hook names ## Code After: """Hooks for various events.""" # Copyright (c) 2012-2022 Wibowo Arindrarto <[email protected]> # SPDX-License-Identifier: BSD-3-Clause import sys import structlog from typing import Any from . import signals as s __all__ = [ "log", "post_site_load_engines", "post_site_collect_targets", "pre_site_write", ] def name() -> str: """Return the name of the current hook. This function must be called inside the top-level hook function. That is, the function that is decorated with the hook. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name return hook_name def log() -> Any: """Return a logger for a hook function. This function is meant to be called inside the top-level hook function. That is, the function that is decorated with the hook. Calling this elsewhere will result in the log message showing incorrect hook names. :returns: A :class:`structlog.BoundLogger` instance ready for logging. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name mod_name = frame.f_globals["__name__"] return structlog.get_logger(mod_name, hook=hook_name) post_site_load_engines = s.post_site_load_engines.connect post_site_collect_targets = s.post_site_collect_targets.connect pre_site_write = s.pre_site_write.connect
# ... existing code ... "pre_site_write", ] def name() -> str: """Return the name of the current hook. This function must be called inside the top-level hook function. That is, the function that is decorated with the hook. """ frame = sys._getframe(1) hook_name = frame.f_code.co_name return hook_name # ... rest of the code ...
f67704c271b8b88ba97d1b44c73552119d79b048
tests/test_utils.py
tests/test_utils.py
import pickle from six.moves import range from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_pickable", "bulky_attr") class TestClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_pickable = lambda x: x def test_do_not_pickle_attributes(): cl = TestClass() dump = pickle.dumps(cl) loaded = pickle.loads(dump) assert loaded.bulky_attr == list(range(100)) assert loaded.non_pickable is not None
from numpy.testing import assert_raises, assert_equal from six.moves import range, cPickle from fuel.iterator import DataIterator from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_picklable", "bulky_attr") class DummyClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_picklable = lambda x: x class FaultyClass(object): pass @do_not_pickle_attributes("iterator") class UnpicklableClass(object): def __init__(self): self.load() def load(self): self.iterator = DataIterator(None) @do_not_pickle_attributes("attribute") class NonLoadingClass(object): def load(self): pass class TestDoNotPickleAttributes(object): def test_load(self): instance = cPickle.loads(cPickle.dumps(DummyClass())) assert_equal(instance.bulky_attr, list(range(100))) assert instance.non_picklable is not None def test_value_error_no_load_method(self): assert_raises(ValueError, do_not_pickle_attributes("x"), FaultyClass) def test_value_error_iterator(self): assert_raises(ValueError, cPickle.dumps, UnpicklableClass()) def test_value_error_attribute_non_loaded(self): assert_raises(ValueError, getattr, NonLoadingClass(), 'attribute')
Increase test coverage in utils.py
Increase test coverage in utils.py
Python
mit
chrishokamp/fuel,ejls/fuel,harmdevries89/fuel,glewis17/fuel,EderSantana/fuel,rodrigob/fuel,markusnagel/fuel,bouthilx/fuel,janchorowski/fuel,aalmah/fuel,vdumoulin/fuel,rodrigob/fuel,orhanf/fuel,laurent-dinh/fuel,rizar/fuel,capybaralet/fuel,aalmah/fuel,hantek/fuel,mila-udem/fuel,janchorowski/fuel,hantek/fuel,dmitriy-serdyuk/fuel,rizar/fuel,dwf/fuel,dhruvparamhans/fuel,chrishokamp/fuel,harmdevries89/fuel,dhruvparamhans/fuel,markusnagel/fuel,mjwillson/fuel,mila-udem/fuel,jbornschein/fuel,udibr/fuel,orhanf/fuel,glewis17/fuel,bouthilx/fuel,dmitriy-serdyuk/fuel,codeaudit/fuel,dwf/fuel,dribnet/fuel,mjwillson/fuel,jbornschein/fuel,ejls/fuel,laurent-dinh/fuel,vdumoulin/fuel,dribnet/fuel,lamblin/fuel,capybaralet/fuel,codeaudit/fuel,EderSantana/fuel,udibr/fuel,lamblin/fuel
- import pickle + from numpy.testing import assert_raises, assert_equal - from six.moves import range + from six.moves import range, cPickle + from fuel.iterator import DataIterator from fuel.utils import do_not_pickle_attributes - @do_not_pickle_attributes("non_pickable", "bulky_attr") + @do_not_pickle_attributes("non_picklable", "bulky_attr") - class TestClass(object): + class DummyClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) - self.non_pickable = lambda x: x + self.non_picklable = lambda x: x - def test_do_not_pickle_attributes(): - cl = TestClass() + class FaultyClass(object): + pass - dump = pickle.dumps(cl) - loaded = pickle.loads(dump) - assert loaded.bulky_attr == list(range(100)) - assert loaded.non_pickable is not None + @do_not_pickle_attributes("iterator") + class UnpicklableClass(object): + def __init__(self): + self.load() + def load(self): + self.iterator = DataIterator(None) + + + @do_not_pickle_attributes("attribute") + class NonLoadingClass(object): + def load(self): + pass + + + class TestDoNotPickleAttributes(object): + def test_load(self): + instance = cPickle.loads(cPickle.dumps(DummyClass())) + assert_equal(instance.bulky_attr, list(range(100))) + assert instance.non_picklable is not None + + def test_value_error_no_load_method(self): + assert_raises(ValueError, do_not_pickle_attributes("x"), FaultyClass) + + def test_value_error_iterator(self): + assert_raises(ValueError, cPickle.dumps, UnpicklableClass()) + + def test_value_error_attribute_non_loaded(self): + assert_raises(ValueError, getattr, NonLoadingClass(), 'attribute') +
Increase test coverage in utils.py
## Code Before: import pickle from six.moves import range from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_pickable", "bulky_attr") class TestClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_pickable = lambda x: x def test_do_not_pickle_attributes(): cl = TestClass() dump = pickle.dumps(cl) loaded = pickle.loads(dump) assert loaded.bulky_attr == list(range(100)) assert loaded.non_pickable is not None ## Instruction: Increase test coverage in utils.py ## Code After: from numpy.testing import assert_raises, assert_equal from six.moves import range, cPickle from fuel.iterator import DataIterator from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_picklable", "bulky_attr") class DummyClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_picklable = lambda x: x class FaultyClass(object): pass @do_not_pickle_attributes("iterator") class UnpicklableClass(object): def __init__(self): self.load() def load(self): self.iterator = DataIterator(None) @do_not_pickle_attributes("attribute") class NonLoadingClass(object): def load(self): pass class TestDoNotPickleAttributes(object): def test_load(self): instance = cPickle.loads(cPickle.dumps(DummyClass())) assert_equal(instance.bulky_attr, list(range(100))) assert instance.non_picklable is not None def test_value_error_no_load_method(self): assert_raises(ValueError, do_not_pickle_attributes("x"), FaultyClass) def test_value_error_iterator(self): assert_raises(ValueError, cPickle.dumps, UnpicklableClass()) def test_value_error_attribute_non_loaded(self): assert_raises(ValueError, getattr, NonLoadingClass(), 'attribute')
# ... existing code ... from numpy.testing import assert_raises, assert_equal from six.moves import range, cPickle from fuel.iterator import DataIterator from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_picklable", "bulky_attr") class DummyClass(object): def __init__(self): self.load() # ... modified code ... def load(self): self.bulky_attr = list(range(100)) self.non_picklable = lambda x: x class FaultyClass(object): pass @do_not_pickle_attributes("iterator") class UnpicklableClass(object): def __init__(self): self.load() def load(self): self.iterator = DataIterator(None) @do_not_pickle_attributes("attribute") class NonLoadingClass(object): def load(self): pass class TestDoNotPickleAttributes(object): def test_load(self): instance = cPickle.loads(cPickle.dumps(DummyClass())) assert_equal(instance.bulky_attr, list(range(100))) assert instance.non_picklable is not None def test_value_error_no_load_method(self): assert_raises(ValueError, do_not_pickle_attributes("x"), FaultyClass) def test_value_error_iterator(self): assert_raises(ValueError, cPickle.dumps, UnpicklableClass()) def test_value_error_attribute_non_loaded(self): assert_raises(ValueError, getattr, NonLoadingClass(), 'attribute') # ... rest of the code ...
b8770a85e11c048fb0dc6c46f799b17add07568d
productController.py
productController.py
from endpoints import Controller, CorsMixin import sqlite3 from datetime import datetime conn = sqlite3.connect('CIUK.db') cur = conn.cursor() class Default(Controller, CorsMixin): def GET(self): return "CIUK" def POST(self, **kwargs): return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['price']) class Products(Controller, CorsMixin): def GET(self): cur.execute("select * from products") return cur.fetchall() class Product(Controller, CorsMixin): def GET(self, id): cur.execute("select * from products where id=?", (id,)) return cur.fetchone() def POST(self, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), datetime.now()] cur.execute("insert into products values (null, ?, ?, ?, ?, ?);", (row)) conn.commit() return "New product added!" def PUT(self, id, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), id] cur.execute("update products set title=?, description=?, price=?, created_at=? where id=?", (row)) conn.commit() return "Product updated!" def DELETE(self, id): cur.execute("delete from products where id=?", (id,)) conn.commit() return "Product deleted!"
from endpoints import Controller, CorsMixin import sqlite3 from datetime import datetime conn = sqlite3.connect('databaseForTest.db') cur = conn.cursor() class Default(Controller, CorsMixin): def GET(self): return "CIUK" def POST(self, **kwargs): return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['price']) class Products(Controller, CorsMixin): def GET(self): cur.execute("select * from products") return cur.fetchall() class Product(Controller, CorsMixin): def GET(self, id): cur.execute("select * from products where id=?", (id,)) return cur.fetchone() def POST(self, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), datetime.now()] cur.execute("insert into products values (null, ?, ?, ?, ?, ?);", (row)) conn.commit() return "New product added!" def PUT(self, id, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), id] cur.execute("update products set title=?, description=?, price=?, created_at=? where id=?", (row)) conn.commit() return "Product updated!" def DELETE(self, id): cur.execute("delete from products where id=?", (id,)) conn.commit() return "Product deleted!"
Change name of database for test
Change name of database for test
Python
mit
joykuotw/python-endpoints,joykuotw/python-endpoints,joykuotw/python-endpoints
from endpoints import Controller, CorsMixin import sqlite3 from datetime import datetime - conn = sqlite3.connect('CIUK.db') + conn = sqlite3.connect('databaseForTest.db') cur = conn.cursor() class Default(Controller, CorsMixin): def GET(self): return "CIUK" def POST(self, **kwargs): return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['price']) class Products(Controller, CorsMixin): def GET(self): cur.execute("select * from products") return cur.fetchall() class Product(Controller, CorsMixin): def GET(self, id): cur.execute("select * from products where id=?", (id,)) return cur.fetchone() def POST(self, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), datetime.now()] cur.execute("insert into products values (null, ?, ?, ?, ?, ?);", (row)) conn.commit() return "New product added!" def PUT(self, id, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), id] cur.execute("update products set title=?, description=?, price=?, created_at=? where id=?", (row)) conn.commit() return "Product updated!" def DELETE(self, id): cur.execute("delete from products where id=?", (id,)) conn.commit() return "Product deleted!"
Change name of database for test
## Code Before: from endpoints import Controller, CorsMixin import sqlite3 from datetime import datetime conn = sqlite3.connect('CIUK.db') cur = conn.cursor() class Default(Controller, CorsMixin): def GET(self): return "CIUK" def POST(self, **kwargs): return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['price']) class Products(Controller, CorsMixin): def GET(self): cur.execute("select * from products") return cur.fetchall() class Product(Controller, CorsMixin): def GET(self, id): cur.execute("select * from products where id=?", (id,)) return cur.fetchone() def POST(self, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), datetime.now()] cur.execute("insert into products values (null, ?, ?, ?, ?, ?);", (row)) conn.commit() return "New product added!" def PUT(self, id, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), id] cur.execute("update products set title=?, description=?, price=?, created_at=? where id=?", (row)) conn.commit() return "Product updated!" def DELETE(self, id): cur.execute("delete from products where id=?", (id,)) conn.commit() return "Product deleted!" ## Instruction: Change name of database for test ## Code After: from endpoints import Controller, CorsMixin import sqlite3 from datetime import datetime conn = sqlite3.connect('databaseForTest.db') cur = conn.cursor() class Default(Controller, CorsMixin): def GET(self): return "CIUK" def POST(self, **kwargs): return '{}, {}, {}'.format(kwargs['title'], kwargs['desc'], kwargs['price']) class Products(Controller, CorsMixin): def GET(self): cur.execute("select * from products") return cur.fetchall() class Product(Controller, CorsMixin): def GET(self, id): cur.execute("select * from products where id=?", (id,)) return cur.fetchone() def POST(self, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), datetime.now()] cur.execute("insert into products values (null, ?, ?, ?, ?, ?);", (row)) conn.commit() return "New product added!" def PUT(self, id, **kwargs): row =[kwargs['title'], kwargs['desc'], kwargs['price'], datetime.now(), id] cur.execute("update products set title=?, description=?, price=?, created_at=? where id=?", (row)) conn.commit() return "Product updated!" def DELETE(self, id): cur.execute("delete from products where id=?", (id,)) conn.commit() return "Product deleted!"
// ... existing code ... from datetime import datetime conn = sqlite3.connect('databaseForTest.db') cur = conn.cursor() // ... rest of the code ...
98dfc5569fb1ae58905f8b6a36deeda324dcdd7b
cronos/teilar/models.py
cronos/teilar/models.py
from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) class Teachers(models.Model): urlid = models.CharField("URL ID", max_length = 30, unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) def __unicode__(self): return self.name
from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name class Teachers(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name
Add deprecated flag for teachers and departments
Add deprecated flag for teachers and departments
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) + deprecated = models.BooleanField(default = False) - - class Teachers(models.Model): - urlid = models.CharField("URL ID", max_length = 30, unique = True) - name = models.CharField("Teacher name", max_length = 100) - email = models.EmailField("Teacher's mail", null = True) - department = models.CharField("Teacher's department", max_length = 100, null = True) def __unicode__(self): return self.name + class Teachers(models.Model): + urlid = models.IntegerField(unique = True) + name = models.CharField("Teacher name", max_length = 100) + email = models.EmailField("Teacher's mail", null = True) + department = models.CharField("Teacher's department", max_length = 100, null = True) + deprecated = models.BooleanField(default = False) + + def __unicode__(self): + return self.name +
Add deprecated flag for teachers and departments
## Code Before: from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) class Teachers(models.Model): urlid = models.CharField("URL ID", max_length = 30, unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) def __unicode__(self): return self.name ## Instruction: Add deprecated flag for teachers and departments ## Code After: from django.db import models class Departments(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name class Teachers(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name
... urlid = models.IntegerField(unique = True) name = models.CharField("Department name", max_length = 200) deprecated = models.BooleanField(default = False) def __unicode__(self): return self.name class Teachers(models.Model): urlid = models.IntegerField(unique = True) name = models.CharField("Teacher name", max_length = 100) email = models.EmailField("Teacher's mail", null = True) department = models.CharField("Teacher's department", max_length = 100, null = True) deprecated = models.BooleanField(default = False) def __unicode__(self): ...
d0367aacfea7c238c476772a2c83f7826b1e9de5
corehq/apps/export/tasks.py
corehq/apps/export/tasks.py
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None) def rebuild_export_task(export_instance): rebuild_export(export_instance)
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True) def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): rebuild_export(export_instance, last_access_cutoff, filter)
Fix botched keyword args in rebuild_export_task()
Fix botched keyword args in rebuild_export_task()
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() - @task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None) - def rebuild_export_task(export_instance): - rebuild_export(export_instance) + @task(queue='background_queue', ignore_result=True) + def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): + rebuild_export(export_instance, last_access_cutoff, filter)
Fix botched keyword args in rebuild_export_task()
## Code Before: from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True, last_access_cutoff=None, filter=None) def rebuild_export_task(export_instance): rebuild_export(export_instance) ## Instruction: Fix botched keyword args in rebuild_export_task() ## Code After: from celery.task import task from corehq.apps.export.export import get_export_file, rebuild_export from couchexport.models import Format from couchexport.tasks import escape_quotes from soil.util import expose_cached_download @task def populate_export_download_task(export_instances, filters, download_id, filename=None, expiry=10 * 60 * 60): export_file = get_export_file(export_instances, filters) file_format = Format.from_format(export_file.format) filename = filename or export_instances[0].name escaped_filename = escape_quotes('%s.%s' % (filename, file_format.extension)) payload = export_file.file.payload expose_cached_download( payload, expiry, ".{}".format(file_format.extension), mimetype=file_format.mimetype, content_disposition='attachment; filename="%s"' % escaped_filename, download_id=download_id, ) export_file.file.delete() @task(queue='background_queue', ignore_result=True) def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): rebuild_export(export_instance, last_access_cutoff, filter)
# ... existing code ... @task(queue='background_queue', ignore_result=True) def rebuild_export_task(export_instance, last_access_cutoff=None, filter=None): rebuild_export(export_instance, last_access_cutoff, filter) # ... rest of the code ...
5e6fc0017d6e4c35338455496924616b12d4b9e1
tests/test_simple.py
tests/test_simple.py
from nose.tools import eq_ from resumable import rebuild, split def test_simple(): @rebuild def function(original): return split(str.upper)(original) original = 'hello' original = function['function'](original) eq_(original, 'HELLO') def test_value(): @rebuild def function(original): return value(original + ' world') original = 'hello' original = function['function'](original) eq_(original, 'hello world') def test_nested(): @rebuild def first(a): @rebuild def second(b): return split(lambda s: s + 'b')(b) return split(second['second'])(a) original = 'ba' original = first['first'](original) eq_(original, 'bab') if __name__ == '__main__': test_simple()
from nose.tools import eq_ from resumable import rebuild, value def test_simple(): @rebuild def function(original): return value(original.upper()) original = 'hello' original = function['function'](original) eq_(original, 'HELLO') def test_value(): @rebuild def function(original): return value(original + ' world') original = 'hello' original = function['function'](original) eq_(original, 'hello world') def test_nested(): @rebuild def first(a): @rebuild def second(b): return value(b + 'b') return value(second['second'](a)) original = 'ba' original = first['first'](original) eq_(original, 'bab') if __name__ == '__main__': test_simple()
Revise tests to reflect removed split
Revise tests to reflect removed split
Python
mit
Mause/resumable
from nose.tools import eq_ - from resumable import rebuild, split + from resumable import rebuild, value def test_simple(): @rebuild def function(original): - return split(str.upper)(original) + return value(original.upper()) original = 'hello' original = function['function'](original) eq_(original, 'HELLO') def test_value(): @rebuild def function(original): return value(original + ' world') original = 'hello' original = function['function'](original) eq_(original, 'hello world') def test_nested(): @rebuild def first(a): @rebuild def second(b): - return split(lambda s: s + 'b')(b) + return value(b + 'b') - return split(second['second'])(a) + return value(second['second'](a)) original = 'ba' original = first['first'](original) eq_(original, 'bab') if __name__ == '__main__': test_simple()
Revise tests to reflect removed split
## Code Before: from nose.tools import eq_ from resumable import rebuild, split def test_simple(): @rebuild def function(original): return split(str.upper)(original) original = 'hello' original = function['function'](original) eq_(original, 'HELLO') def test_value(): @rebuild def function(original): return value(original + ' world') original = 'hello' original = function['function'](original) eq_(original, 'hello world') def test_nested(): @rebuild def first(a): @rebuild def second(b): return split(lambda s: s + 'b')(b) return split(second['second'])(a) original = 'ba' original = first['first'](original) eq_(original, 'bab') if __name__ == '__main__': test_simple() ## Instruction: Revise tests to reflect removed split ## Code After: from nose.tools import eq_ from resumable import rebuild, value def test_simple(): @rebuild def function(original): return value(original.upper()) original = 'hello' original = function['function'](original) eq_(original, 'HELLO') def test_value(): @rebuild def function(original): return value(original + ' world') original = 'hello' original = function['function'](original) eq_(original, 'hello world') def test_nested(): @rebuild def first(a): @rebuild def second(b): return value(b + 'b') return value(second['second'](a)) original = 'ba' original = first['first'](original) eq_(original, 'bab') if __name__ == '__main__': test_simple()
// ... existing code ... from nose.tools import eq_ from resumable import rebuild, value // ... modified code ... @rebuild def function(original): return value(original.upper()) original = 'hello' ... @rebuild def second(b): return value(b + 'b') return value(second['second'](a)) original = 'ba' // ... rest of the code ...
0155ed7c37fd4cafa2650911d4f902a3a8982761
test/test_bot.py
test/test_bot.py
import re import unittest from gather.bot import ListenerBot class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' action = unittest.mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) if __name__ == '__main__': unittest.main()
import asyncio import re import unittest from unittest import mock from gather.bot import ListenerBot def async_test(f): # http://stackoverflow.com/a/23036785/304210 def wrapper(*args, **kwargs): coro = asyncio.coroutine(f) future = coro(*args, **kwargs) loop = asyncio.get_event_loop() loop.run_until_complete(future) return wrapper class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' action = mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) @async_test def test_on_message_from_bot(self): bot = ListenerBot() bot.username = 'testuser' regex = r'^test' action = mock.Mock() bot.actions = {regex: (re.compile(regex, re.IGNORECASE), action)} bot.on_message(mock.Mock(), mock.Mock, 'test') action.assert_not_called() if __name__ == '__main__': unittest.main()
Add a test for on_message
Add a test for on_message
Python
mit
veryhappythings/discord-gather
+ import asyncio import re import unittest + from unittest import mock from gather.bot import ListenerBot + + + def async_test(f): + # http://stackoverflow.com/a/23036785/304210 + def wrapper(*args, **kwargs): + coro = asyncio.coroutine(f) + future = coro(*args, **kwargs) + loop = asyncio.get_event_loop() + loop.run_until_complete(future) + return wrapper class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' - action = unittest.mock.Mock() + action = mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) + @async_test + def test_on_message_from_bot(self): + bot = ListenerBot() + bot.username = 'testuser' + regex = r'^test' + action = mock.Mock() + bot.actions = {regex: (re.compile(regex, re.IGNORECASE), action)} + bot.on_message(mock.Mock(), mock.Mock, 'test') + action.assert_not_called() + if __name__ == '__main__': unittest.main()
Add a test for on_message
## Code Before: import re import unittest from gather.bot import ListenerBot class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' action = unittest.mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) if __name__ == '__main__': unittest.main() ## Instruction: Add a test for on_message ## Code After: import asyncio import re import unittest from unittest import mock from gather.bot import ListenerBot def async_test(f): # http://stackoverflow.com/a/23036785/304210 def wrapper(*args, **kwargs): coro = asyncio.coroutine(f) future = coro(*args, **kwargs) loop = asyncio.get_event_loop() loop.run_until_complete(future) return wrapper class TestGatherBot(unittest.TestCase): def test_register(self): bot = ListenerBot() self.assertEqual({}, bot.actions) regex = r'^test' action = mock.Mock() bot.register_action(regex, action) self.assertEqual( {regex: (re.compile(regex, re.IGNORECASE), action)}, bot.actions ) @async_test def test_on_message_from_bot(self): bot = ListenerBot() bot.username = 'testuser' regex = r'^test' action = mock.Mock() bot.actions = {regex: (re.compile(regex, re.IGNORECASE), action)} bot.on_message(mock.Mock(), mock.Mock, 'test') action.assert_not_called() if __name__ == '__main__': unittest.main()
// ... existing code ... import asyncio import re import unittest from unittest import mock from gather.bot import ListenerBot def async_test(f): # http://stackoverflow.com/a/23036785/304210 def wrapper(*args, **kwargs): coro = asyncio.coroutine(f) future = coro(*args, **kwargs) loop = asyncio.get_event_loop() loop.run_until_complete(future) return wrapper // ... modified code ... self.assertEqual({}, bot.actions) regex = r'^test' action = mock.Mock() bot.register_action(regex, action) self.assertEqual( ... ) @async_test def test_on_message_from_bot(self): bot = ListenerBot() bot.username = 'testuser' regex = r'^test' action = mock.Mock() bot.actions = {regex: (re.compile(regex, re.IGNORECASE), action)} bot.on_message(mock.Mock(), mock.Mock, 'test') action.assert_not_called() if __name__ == '__main__': // ... rest of the code ...
d56ffde056a7758539ce834943ceb0f656e795a8
CI/syntaxCheck.py
CI/syntaxCheck.py
import sys from CITests import CITests # Libs in Application Examples appExamples = { "KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", "TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", "SevenBus":"/ApplicationExamples/SevenBus/package.mo", "IEEE9":"/ApplicationExamples/IEEE9/package.mo", "IEEE14":"/ApplicationExamples/IEEE14/package.mo", "AKD":"/ApplicationExamples/AKD/package.mo", "N44":"/ApplicationExamples/N44/package.mo", "OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
import sys from CITests import CITests # Libs in Application Examples appExamples = { "KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", "TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", "SevenBus":"/ApplicationExamples/SevenBus/package.mo", "IEEE9":"/ApplicationExamples/IEEE9/package.mo", "IEEE14":"/ApplicationExamples/IEEE14/package.mo", "AKD":"/ApplicationExamples/AKD/package.mo", "N44":"/ApplicationExamples/N44/package.mo", "OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", "RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
Fix missing test probably got removed in my clumsy merge
Fix missing test probably got removed in my clumsy merge
Python
bsd-3-clause
fran-jo/OpenIPSL,tinrabuzin/OpenIPSL,SmarTS-Lab/OpenIPSL,SmarTS-Lab/OpenIPSL,MaximeBaudette/OpenIPSL,OpenIPSL/OpenIPSL
import sys from CITests import CITests # Libs in Application Examples appExamples = { "KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", "TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", "SevenBus":"/ApplicationExamples/SevenBus/package.mo", "IEEE9":"/ApplicationExamples/IEEE9/package.mo", "IEEE14":"/ApplicationExamples/IEEE14/package.mo", "AKD":"/ApplicationExamples/AKD/package.mo", "N44":"/ApplicationExamples/N44/package.mo", "OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", + "RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
Fix missing test probably got removed in my clumsy merge
## Code Before: import sys from CITests import CITests # Libs in Application Examples appExamples = { "KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", "TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", "SevenBus":"/ApplicationExamples/SevenBus/package.mo", "IEEE9":"/ApplicationExamples/IEEE9/package.mo", "IEEE14":"/ApplicationExamples/IEEE14/package.mo", "AKD":"/ApplicationExamples/AKD/package.mo", "N44":"/ApplicationExamples/N44/package.mo", "OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1) ## Instruction: Fix missing test probably got removed in my clumsy merge ## Code After: import sys from CITests import CITests # Libs in Application Examples appExamples = { "KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", "TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", "SevenBus":"/ApplicationExamples/SevenBus/package.mo", "IEEE9":"/ApplicationExamples/IEEE9/package.mo", "IEEE14":"/ApplicationExamples/IEEE14/package.mo", "AKD":"/ApplicationExamples/AKD/package.mo", "N44":"/ApplicationExamples/N44/package.mo", "OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", "RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
... "N44":"/ApplicationExamples/N44/package.mo", "OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", "RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } ...
8b92bc6c4a782dbb83aadb1bbfc5951dc53f53e1
netbox/dcim/migrations/0145_site_remove_deprecated_fields.py
netbox/dcim/migrations/0145_site_remove_deprecated_fields.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dcim', '0144_fix_cable_abs_length'), ] operations = [ migrations.RemoveField( model_name='site', name='asn', ), migrations.RemoveField( model_name='site', name='contact_email', ), migrations.RemoveField( model_name='site', name='contact_name', ), migrations.RemoveField( model_name='site', name='contact_phone', ), ]
from django.db import migrations from django.db.utils import DataError def check_legacy_data(apps, schema_editor): """ Abort the migration if any legacy site fields still contain data. """ Site = apps.get_model('dcim', 'Site') if site_count := Site.objects.exclude(asn__isnull=True).count(): raise DataError( f"Unable to proceed with deleting asn field from Site model: Found {site_count} sites with " f"legacy ASN data. Please ensure all legacy site ASN data has been migrated to ASN objects " f"before proceeding." ) if site_count := Site.objects.exclude(contact_name='', contact_phone='', contact_email='').count(): raise DataError( f"Unable to proceed with deleting contact fields from Site model: Found {site_count} sites " f"with legacy contact data. Please ensure all legacy site contact data has been migrated to " f"contact objects before proceeding." ) class Migration(migrations.Migration): dependencies = [ ('dcim', '0144_fix_cable_abs_length'), ] operations = [ migrations.RunPython( code=check_legacy_data, reverse_code=migrations.RunPython.noop ), migrations.RemoveField( model_name='site', name='asn', ), migrations.RemoveField( model_name='site', name='contact_email', ), migrations.RemoveField( model_name='site', name='contact_name', ), migrations.RemoveField( model_name='site', name='contact_phone', ), ]
Add migration safeguard to prevent accidental destruction of data
Add migration safeguard to prevent accidental destruction of data
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
from django.db import migrations + from django.db.utils import DataError + + + def check_legacy_data(apps, schema_editor): + """ + Abort the migration if any legacy site fields still contain data. + """ + Site = apps.get_model('dcim', 'Site') + + if site_count := Site.objects.exclude(asn__isnull=True).count(): + raise DataError( + f"Unable to proceed with deleting asn field from Site model: Found {site_count} sites with " + f"legacy ASN data. Please ensure all legacy site ASN data has been migrated to ASN objects " + f"before proceeding." + ) + + if site_count := Site.objects.exclude(contact_name='', contact_phone='', contact_email='').count(): + raise DataError( + f"Unable to proceed with deleting contact fields from Site model: Found {site_count} sites " + f"with legacy contact data. Please ensure all legacy site contact data has been migrated to " + f"contact objects before proceeding." + ) class Migration(migrations.Migration): dependencies = [ ('dcim', '0144_fix_cable_abs_length'), ] operations = [ + migrations.RunPython( + code=check_legacy_data, + reverse_code=migrations.RunPython.noop + ), migrations.RemoveField( model_name='site', name='asn', ), migrations.RemoveField( model_name='site', name='contact_email', ), migrations.RemoveField( model_name='site', name='contact_name', ), migrations.RemoveField( model_name='site', name='contact_phone', ), ]
Add migration safeguard to prevent accidental destruction of data
## Code Before: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('dcim', '0144_fix_cable_abs_length'), ] operations = [ migrations.RemoveField( model_name='site', name='asn', ), migrations.RemoveField( model_name='site', name='contact_email', ), migrations.RemoveField( model_name='site', name='contact_name', ), migrations.RemoveField( model_name='site', name='contact_phone', ), ] ## Instruction: Add migration safeguard to prevent accidental destruction of data ## Code After: from django.db import migrations from django.db.utils import DataError def check_legacy_data(apps, schema_editor): """ Abort the migration if any legacy site fields still contain data. """ Site = apps.get_model('dcim', 'Site') if site_count := Site.objects.exclude(asn__isnull=True).count(): raise DataError( f"Unable to proceed with deleting asn field from Site model: Found {site_count} sites with " f"legacy ASN data. Please ensure all legacy site ASN data has been migrated to ASN objects " f"before proceeding." ) if site_count := Site.objects.exclude(contact_name='', contact_phone='', contact_email='').count(): raise DataError( f"Unable to proceed with deleting contact fields from Site model: Found {site_count} sites " f"with legacy contact data. Please ensure all legacy site contact data has been migrated to " f"contact objects before proceeding." ) class Migration(migrations.Migration): dependencies = [ ('dcim', '0144_fix_cable_abs_length'), ] operations = [ migrations.RunPython( code=check_legacy_data, reverse_code=migrations.RunPython.noop ), migrations.RemoveField( model_name='site', name='asn', ), migrations.RemoveField( model_name='site', name='contact_email', ), migrations.RemoveField( model_name='site', name='contact_name', ), migrations.RemoveField( model_name='site', name='contact_phone', ), ]
... from django.db import migrations from django.db.utils import DataError def check_legacy_data(apps, schema_editor): """ Abort the migration if any legacy site fields still contain data. """ Site = apps.get_model('dcim', 'Site') if site_count := Site.objects.exclude(asn__isnull=True).count(): raise DataError( f"Unable to proceed with deleting asn field from Site model: Found {site_count} sites with " f"legacy ASN data. Please ensure all legacy site ASN data has been migrated to ASN objects " f"before proceeding." ) if site_count := Site.objects.exclude(contact_name='', contact_phone='', contact_email='').count(): raise DataError( f"Unable to proceed with deleting contact fields from Site model: Found {site_count} sites " f"with legacy contact data. Please ensure all legacy site contact data has been migrated to " f"contact objects before proceeding." ) ... operations = [ migrations.RunPython( code=check_legacy_data, reverse_code=migrations.RunPython.noop ), migrations.RemoveField( model_name='site', ...
8161ec1fc511ba948451ce121c863ca878ef482d
tests/test_pool.py
tests/test_pool.py
import random import unittest from aioes.pool import RandomSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r)
import random import unittest from aioes.pool import RandomSelector, RoundRobinSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r) class TestRoundRobinSelector(unittest.TestCase): def test_select(self): s = RoundRobinSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r) r = s.select([1, 2, 3]) self.assertEqual(3, r) r = s.select([1, 2, 3]) self.assertEqual(1, r) r = s.select([1, 2, 3]) self.assertEqual(2, r)
Add test for round-robin selector
Add test for round-robin selector
Python
apache-2.0
aio-libs/aioes
import random import unittest - from aioes.pool import RandomSelector + from aioes.pool import RandomSelector, RoundRobinSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r) + + class TestRoundRobinSelector(unittest.TestCase): + + def test_select(self): + s = RoundRobinSelector() + r = s.select([1, 2, 3]) + self.assertEqual(2, r) + r = s.select([1, 2, 3]) + self.assertEqual(3, r) + r = s.select([1, 2, 3]) + self.assertEqual(1, r) + r = s.select([1, 2, 3]) + self.assertEqual(2, r) +
Add test for round-robin selector
## Code Before: import random import unittest from aioes.pool import RandomSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r) ## Instruction: Add test for round-robin selector ## Code After: import random import unittest from aioes.pool import RandomSelector, RoundRobinSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r) class TestRoundRobinSelector(unittest.TestCase): def test_select(self): s = RoundRobinSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r) r = s.select([1, 2, 3]) self.assertEqual(3, r) r = s.select([1, 2, 3]) self.assertEqual(1, r) r = s.select([1, 2, 3]) self.assertEqual(2, r)
... import unittest from aioes.pool import RandomSelector, RoundRobinSelector ... r = s.select([1, 2, 3]) self.assertEqual(2, r) class TestRoundRobinSelector(unittest.TestCase): def test_select(self): s = RoundRobinSelector() r = s.select([1, 2, 3]) self.assertEqual(2, r) r = s.select([1, 2, 3]) self.assertEqual(3, r) r = s.select([1, 2, 3]) self.assertEqual(1, r) r = s.select([1, 2, 3]) self.assertEqual(2, r) ...
9639eb34f53444387621ed0a27ef9b273b38df79
slackclient/_slackrequest.py
slackclient/_slackrequest.py
import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): ''' Perform a POST request to the Slack Web API Args: token (str): your authentication token request (str): the method to call from the Slack API. For example: 'channels.list' post_data (dict): key/value arguments to pass for the request. For example: {'channel': 'CABC12345'} domain (str): if for some reason you want to send your request to something other than slack.com ''' post_data = post_data or {} # Pull file out so it isn't JSON encoded like normal fields. files = {'file': post_data.pop('file')} if 'file' in post_data else None for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k] = json.dumps(v) url = 'https://{0}/api/{1}'.format(domain, request) post_data['token'] = token return requests.post(url, data=post_data, files=files)
import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): ''' Perform a POST request to the Slack Web API Args: token (str): your authentication token request (str): the method to call from the Slack API. For example: 'channels.list' post_data (dict): key/value arguments to pass for the request. For example: {'channel': 'CABC12345'} domain (str): if for some reason you want to send your request to something other than slack.com ''' post_data = post_data or {} # Pull file out so it isn't JSON encoded like normal fields. # Only do this for requests that are UPLOADING files; downloading files # use the 'file' argument to point to a File ID. upload_requests = ['files.upload'] files = None if request in upload_requests: files = {'file': post_data.pop('file')} if 'file' in post_data else None for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k] = json.dumps(v) url = 'https://{0}/api/{1}'.format(domain, request) post_data['token'] = token return requests.post(url, data=post_data, files=files)
Fix bug preventing API calls requiring a file ID
Fix bug preventing API calls requiring a file ID For example, an API call to files.info takes a file ID argument named "file", which was stripped out by this call. Currently, there is only one request type that accepts file data (files.upload). Every other use of 'file' is an ID that aught to be contained in the request.
Python
mit
slackhq/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient
import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): ''' Perform a POST request to the Slack Web API Args: token (str): your authentication token request (str): the method to call from the Slack API. For example: 'channels.list' post_data (dict): key/value arguments to pass for the request. For example: {'channel': 'CABC12345'} domain (str): if for some reason you want to send your request to something other than slack.com ''' post_data = post_data or {} # Pull file out so it isn't JSON encoded like normal fields. + # Only do this for requests that are UPLOADING files; downloading files + # use the 'file' argument to point to a File ID. + upload_requests = ['files.upload'] + files = None + if request in upload_requests: - files = {'file': post_data.pop('file')} if 'file' in post_data else None + files = {'file': post_data.pop('file')} if 'file' in post_data else None for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k] = json.dumps(v) url = 'https://{0}/api/{1}'.format(domain, request) post_data['token'] = token return requests.post(url, data=post_data, files=files)
Fix bug preventing API calls requiring a file ID
## Code Before: import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): ''' Perform a POST request to the Slack Web API Args: token (str): your authentication token request (str): the method to call from the Slack API. For example: 'channels.list' post_data (dict): key/value arguments to pass for the request. For example: {'channel': 'CABC12345'} domain (str): if for some reason you want to send your request to something other than slack.com ''' post_data = post_data or {} # Pull file out so it isn't JSON encoded like normal fields. files = {'file': post_data.pop('file')} if 'file' in post_data else None for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k] = json.dumps(v) url = 'https://{0}/api/{1}'.format(domain, request) post_data['token'] = token return requests.post(url, data=post_data, files=files) ## Instruction: Fix bug preventing API calls requiring a file ID ## Code After: import json import requests import six class SlackRequest(object): @staticmethod def do(token, request="?", post_data=None, domain="slack.com"): ''' Perform a POST request to the Slack Web API Args: token (str): your authentication token request (str): the method to call from the Slack API. For example: 'channels.list' post_data (dict): key/value arguments to pass for the request. For example: {'channel': 'CABC12345'} domain (str): if for some reason you want to send your request to something other than slack.com ''' post_data = post_data or {} # Pull file out so it isn't JSON encoded like normal fields. # Only do this for requests that are UPLOADING files; downloading files # use the 'file' argument to point to a File ID. upload_requests = ['files.upload'] files = None if request in upload_requests: files = {'file': post_data.pop('file')} if 'file' in post_data else None for k, v in six.iteritems(post_data): if not isinstance(v, six.string_types): post_data[k] = json.dumps(v) url = 'https://{0}/api/{1}'.format(domain, request) post_data['token'] = token return requests.post(url, data=post_data, files=files)
# ... existing code ... # Pull file out so it isn't JSON encoded like normal fields. # Only do this for requests that are UPLOADING files; downloading files # use the 'file' argument to point to a File ID. upload_requests = ['files.upload'] files = None if request in upload_requests: files = {'file': post_data.pop('file')} if 'file' in post_data else None for k, v in six.iteritems(post_data): # ... rest of the code ...
40edb65ee751dfe4cf6e04ee59891266d8b14f30
spacy/tests/regression/test_issue1380.py
spacy/tests/regression/test_issue1380.py
import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
from __future__ import unicode_literals import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
Make test work for Python 2.7
Make test work for Python 2.7
Python
mit
recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy
+ from __future__ import unicode_literals import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
Make test work for Python 2.7
## Code Before: import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0 ## Instruction: Make test work for Python 2.7 ## Code After: from __future__ import unicode_literals import pytest from ...language import Language def test_issue1380_empty_string(): nlp = Language() doc = nlp('') assert len(doc) == 0 @pytest.mark.models('en') def test_issue1380_en(EN): doc = EN('') assert len(doc) == 0
// ... existing code ... from __future__ import unicode_literals import pytest // ... rest of the code ...
4bd16d369cc9c89973247afee6ee5ab28eeee014
tests/providers/test_dnsimple.py
tests/providers/test_dnsimple.py
from lexicon.providers.dnsimple import Provider from integration_tests import IntegrationTests from unittest import TestCase # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *each and every* implementation of the interface must # pass, by inheritance from define_tests.TheTests class DnsimpleProviderTests(TestCase, IntegrationTests): Provider = Provider provider_name = 'dnsimple' domain = 'wopr.tech' provider_opts = {'api_endpoint': 'https://api.sandbox.dnsimple.com/v2'} def _filter_headers(self): return ['Authorization','set-cookie']
from lexicon.providers.dnsimple import Provider from integration_tests import IntegrationTests from unittest import TestCase # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *each and every* implementation of the interface must # pass, by inheritance from define_tests.TheTests class DnsimpleProviderTests(TestCase, IntegrationTests): Provider = Provider provider_name = 'dnsimple' domain = 'wopr.tech' provider_opts = {'api_endpoint': 'https://api.sandbox.dnsimple.com/v2'} def _filter_headers(self): return ['Authorization','set-cookie','X-Dnsimple-OTP']
Add OTP to test filters
Add OTP to test filters
Python
mit
AnalogJ/lexicon,tnwhitwell/lexicon,tnwhitwell/lexicon,AnalogJ/lexicon
from lexicon.providers.dnsimple import Provider from integration_tests import IntegrationTests from unittest import TestCase # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *each and every* implementation of the interface must # pass, by inheritance from define_tests.TheTests class DnsimpleProviderTests(TestCase, IntegrationTests): Provider = Provider provider_name = 'dnsimple' domain = 'wopr.tech' provider_opts = {'api_endpoint': 'https://api.sandbox.dnsimple.com/v2'} def _filter_headers(self): - return ['Authorization','set-cookie'] + return ['Authorization','set-cookie','X-Dnsimple-OTP']
Add OTP to test filters
## Code Before: from lexicon.providers.dnsimple import Provider from integration_tests import IntegrationTests from unittest import TestCase # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *each and every* implementation of the interface must # pass, by inheritance from define_tests.TheTests class DnsimpleProviderTests(TestCase, IntegrationTests): Provider = Provider provider_name = 'dnsimple' domain = 'wopr.tech' provider_opts = {'api_endpoint': 'https://api.sandbox.dnsimple.com/v2'} def _filter_headers(self): return ['Authorization','set-cookie'] ## Instruction: Add OTP to test filters ## Code After: from lexicon.providers.dnsimple import Provider from integration_tests import IntegrationTests from unittest import TestCase # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *each and every* implementation of the interface must # pass, by inheritance from define_tests.TheTests class DnsimpleProviderTests(TestCase, IntegrationTests): Provider = Provider provider_name = 'dnsimple' domain = 'wopr.tech' provider_opts = {'api_endpoint': 'https://api.sandbox.dnsimple.com/v2'} def _filter_headers(self): return ['Authorization','set-cookie','X-Dnsimple-OTP']
// ... existing code ... provider_opts = {'api_endpoint': 'https://api.sandbox.dnsimple.com/v2'} def _filter_headers(self): return ['Authorization','set-cookie','X-Dnsimple-OTP'] // ... rest of the code ...
fb5ad293c34387b1ab7b7b7df3aed3942fdd9282
src/webapp/activities/forms.py
src/webapp/activities/forms.py
from django import forms class ActivitySubscribeForm(forms.Form): id = forms.IntegerField( min_value = 0, required=True, widget = forms.HiddenInput, ) title = forms.CharField( max_length=100, required=True, widget = forms.HiddenInput, ) class ProposalForm(forms.Form): title = forms.CharField( max_length=100, required=True, ) subtitle = forms.CharField( required = False, widget = forms.Textarea, ) duration = forms.CharField( max_length=50, required=True, ) max_places = forms.IntegerField( min_value = 0, required=True, ) show_owners = forms.BooleanField( initial = False, required = False, ) requires_inscription = forms.BooleanField( initial = False, required = False, ) owners = forms.CharField( required = False, widget = forms.Textarea, ) organizers = forms.CharField( required = False, widget = forms.Textarea, ) text = forms.CharField( required = False, widget = forms.Textarea, ) logistics = forms.CharField( required = False, widget = forms.Textarea, ) notes_organization = forms.CharField( required = False, widget = forms.Textarea, )
from django import forms class ActivitySubscribeForm(forms.Form): id = forms.IntegerField( min_value = 0, required=True, widget = forms.HiddenInput, ) title = forms.CharField( max_length=100, required=True, widget = forms.HiddenInput, ) class ProposalForm(forms.Form): title = forms.CharField( max_length=100, required=True, ) subtitle = forms.CharField( required = False, widget = forms.Textarea, ) duration = forms.CharField( max_length=50, required=True, ) max_places = forms.IntegerField( min_value = 0, required=True, initial = 0, ) show_owners = forms.BooleanField( initial = False, required = False, ) requires_inscription = forms.BooleanField( initial = False, required = False, ) owners = forms.CharField( required = False, widget = forms.Textarea, ) organizers = forms.CharField( required = False, widget = forms.Textarea, ) text = forms.CharField( required = False, widget = forms.Textarea, ) logistics = forms.CharField( required = False, widget = forms.Textarea, ) notes_organization = forms.CharField( required = False, widget = forms.Textarea, )
Add default to max_places in proposal form
Add default to max_places in proposal form
Python
agpl-3.0
hirunatan/estelcon_web,hirunatan/estelcon_web,hirunatan/estelcon_web,hirunatan/estelcon_web
from django import forms class ActivitySubscribeForm(forms.Form): id = forms.IntegerField( min_value = 0, required=True, widget = forms.HiddenInput, ) title = forms.CharField( max_length=100, required=True, widget = forms.HiddenInput, ) class ProposalForm(forms.Form): title = forms.CharField( max_length=100, required=True, ) subtitle = forms.CharField( required = False, widget = forms.Textarea, ) duration = forms.CharField( max_length=50, required=True, ) max_places = forms.IntegerField( - min_value = 0, required=True, + min_value = 0, required=True, initial = 0, ) show_owners = forms.BooleanField( initial = False, required = False, ) requires_inscription = forms.BooleanField( initial = False, required = False, ) owners = forms.CharField( required = False, widget = forms.Textarea, ) organizers = forms.CharField( required = False, widget = forms.Textarea, ) text = forms.CharField( required = False, widget = forms.Textarea, ) logistics = forms.CharField( required = False, widget = forms.Textarea, ) notes_organization = forms.CharField( required = False, widget = forms.Textarea, )
Add default to max_places in proposal form
## Code Before: from django import forms class ActivitySubscribeForm(forms.Form): id = forms.IntegerField( min_value = 0, required=True, widget = forms.HiddenInput, ) title = forms.CharField( max_length=100, required=True, widget = forms.HiddenInput, ) class ProposalForm(forms.Form): title = forms.CharField( max_length=100, required=True, ) subtitle = forms.CharField( required = False, widget = forms.Textarea, ) duration = forms.CharField( max_length=50, required=True, ) max_places = forms.IntegerField( min_value = 0, required=True, ) show_owners = forms.BooleanField( initial = False, required = False, ) requires_inscription = forms.BooleanField( initial = False, required = False, ) owners = forms.CharField( required = False, widget = forms.Textarea, ) organizers = forms.CharField( required = False, widget = forms.Textarea, ) text = forms.CharField( required = False, widget = forms.Textarea, ) logistics = forms.CharField( required = False, widget = forms.Textarea, ) notes_organization = forms.CharField( required = False, widget = forms.Textarea, ) ## Instruction: Add default to max_places in proposal form ## Code After: from django import forms class ActivitySubscribeForm(forms.Form): id = forms.IntegerField( min_value = 0, required=True, widget = forms.HiddenInput, ) title = forms.CharField( max_length=100, required=True, widget = forms.HiddenInput, ) class ProposalForm(forms.Form): title = forms.CharField( max_length=100, required=True, ) subtitle = forms.CharField( required = False, widget = forms.Textarea, ) duration = forms.CharField( max_length=50, required=True, ) max_places = forms.IntegerField( min_value = 0, required=True, initial = 0, ) show_owners = forms.BooleanField( initial = False, required = False, ) requires_inscription = forms.BooleanField( initial = False, required = False, ) owners = forms.CharField( required = False, widget = forms.Textarea, ) organizers = forms.CharField( required = False, widget = forms.Textarea, ) text = forms.CharField( required = False, widget = forms.Textarea, ) logistics = forms.CharField( required = False, widget = forms.Textarea, ) notes_organization = forms.CharField( required = False, widget = forms.Textarea, )
... ) max_places = forms.IntegerField( min_value = 0, required=True, initial = 0, ) show_owners = forms.BooleanField( ...
78c96e56b46f800c972bcdb5c5aa525d73d84a80
src/setuptools_scm/__main__.py
src/setuptools_scm/__main__.py
import sys from setuptools_scm import _get_version from setuptools_scm import get_version from setuptools_scm.config import Configuration from setuptools_scm.integration import find_files def main() -> None: files = list(sorted(find_files("."), key=len)) try: pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) print(_get_version(Configuration.from_file(pyproject))) except (LookupError, StopIteration): print("Guessed Version", get_version()) if "ls" in sys.argv: for fname in files: print(fname) if __name__ == "__main__": main()
import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
Add options to better control CLI command
Add options to better control CLI command Instead of trying to guess the `pyprojec.toml` file by looking at the files controlled by the SCM, use explicit options to control it.
Python
mit
pypa/setuptools_scm,pypa/setuptools_scm,RonnyPfannschmidt/setuptools_scm,RonnyPfannschmidt/setuptools_scm
+ import argparse - import sys + import os + import warnings from setuptools_scm import _get_version - from setuptools_scm import get_version from setuptools_scm.config import Configuration + from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: - files = list(sorted(find_files("."), key=len)) + opts = _get_cli_opts() + root = opts.root or "." + try: - pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) + pyproject = opts.config or _find_pyproject(root) + root = opts.root or os.path.relpath(os.path.dirname(pyproject)) - print(_get_version(Configuration.from_file(pyproject))) + config = Configuration.from_file(pyproject) - except (LookupError, StopIteration): - print("Guessed Version", get_version()) + config.root = root + except (LookupError, FileNotFoundError) as ex: + # no pyproject.toml OR no [tool.setuptools_scm] + warnings.warn(f"{ex}. Using default configuration.") + config = Configuration(root) - if "ls" in sys.argv: + print(_get_version(config)) + + if opts.command == "ls": - for fname in files: + for fname in find_files(config.root): print(fname) + + + def _get_cli_opts(): + prog = "python -m setuptools_scm" + desc = "Print project version according to SCM metadata" + parser = argparse.ArgumentParser(prog, description=desc) + # By default, help for `--help` starts with lower case, so we keep the pattern: + parser.add_argument( + "-r", + "--root", + default=None, + help='directory managed by the SCM, default: inferred from config file, or "."', + ) + parser.add_argument( + "-c", + "--config", + default=None, + metavar="PATH", + help="path to 'pyproject.toml' with setuptools_scm config, " + "default: looked up in the current or parent directories", + ) + sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") + # We avoid `metavar` to prevent printing repetitive information + desc = "List files managed by the SCM" + sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) + return parser.parse_args() + + + def _find_pyproject(parent): + for directory in walk_potential_roots(os.path.abspath(parent)): + pyproject = os.path.join(directory, "pyproject.toml") + if os.path.exists(pyproject): + return pyproject + + raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
Add options to better control CLI command
## Code Before: import sys from setuptools_scm import _get_version from setuptools_scm import get_version from setuptools_scm.config import Configuration from setuptools_scm.integration import find_files def main() -> None: files = list(sorted(find_files("."), key=len)) try: pyproject = next(fname for fname in files if fname.endswith("pyproject.toml")) print(_get_version(Configuration.from_file(pyproject))) except (LookupError, StopIteration): print("Guessed Version", get_version()) if "ls" in sys.argv: for fname in files: print(fname) if __name__ == "__main__": main() ## Instruction: Add options to better control CLI command ## Code After: import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") if __name__ == "__main__": main()
// ... existing code ... import argparse import os import warnings from setuptools_scm import _get_version from setuptools_scm.config import Configuration from setuptools_scm.discover import walk_potential_roots from setuptools_scm.integration import find_files // ... modified code ... def main() -> None: opts = _get_cli_opts() root = opts.root or "." try: pyproject = opts.config or _find_pyproject(root) root = opts.root or os.path.relpath(os.path.dirname(pyproject)) config = Configuration.from_file(pyproject) config.root = root except (LookupError, FileNotFoundError) as ex: # no pyproject.toml OR no [tool.setuptools_scm] warnings.warn(f"{ex}. Using default configuration.") config = Configuration(root) print(_get_version(config)) if opts.command == "ls": for fname in find_files(config.root): print(fname) def _get_cli_opts(): prog = "python -m setuptools_scm" desc = "Print project version according to SCM metadata" parser = argparse.ArgumentParser(prog, description=desc) # By default, help for `--help` starts with lower case, so we keep the pattern: parser.add_argument( "-r", "--root", default=None, help='directory managed by the SCM, default: inferred from config file, or "."', ) parser.add_argument( "-c", "--config", default=None, metavar="PATH", help="path to 'pyproject.toml' with setuptools_scm config, " "default: looked up in the current or parent directories", ) sub = parser.add_subparsers(title="extra commands", dest="command", metavar="") # We avoid `metavar` to prevent printing repetitive information desc = "List files managed by the SCM" sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc) return parser.parse_args() def _find_pyproject(parent): for directory in walk_potential_roots(os.path.abspath(parent)): pyproject = os.path.join(directory, "pyproject.toml") if os.path.exists(pyproject): return pyproject raise FileNotFoundError("'pyproject.toml' was not found") // ... rest of the code ...
220e0008924878f774f570cc0122c563f2c17465
recipes/migrations/0010_auto_20150919_1228.py
recipes/migrations/0010_auto_20150919_1228.py
from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage") for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): u = IngredientUsage(recipe=r, ingredient=i, quantity=1) u.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_auto_20150919_1226'), ] operations = [ migrations.RunPython(change_to_usage), ]
from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage") for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): u = IngredientUsage(recipe=recipe, ingredient=ingredient, quantity=1) u.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_auto_20150919_1226'), ] operations = [ migrations.RunPython(change_to_usage), ]
Make the data migration actually work
Make the data migration actually work
Python
agpl-3.0
XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd
from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage") for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): - u = IngredientUsage(recipe=r, ingredient=i, quantity=1) + u = IngredientUsage(recipe=recipe, ingredient=ingredient, + quantity=1) u.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_auto_20150919_1226'), ] operations = [ migrations.RunPython(change_to_usage), ]
Make the data migration actually work
## Code Before: from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage") for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): u = IngredientUsage(recipe=r, ingredient=i, quantity=1) u.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_auto_20150919_1226'), ] operations = [ migrations.RunPython(change_to_usage), ] ## Instruction: Make the data migration actually work ## Code After: from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage") for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): u = IngredientUsage(recipe=recipe, ingredient=ingredient, quantity=1) u.save() class Migration(migrations.Migration): dependencies = [ ('recipes', '0009_auto_20150919_1226'), ] operations = [ migrations.RunPython(change_to_usage), ]
# ... existing code ... for recipe in Recipe.objects.all(): for ingredient in recipe.ingredient_set.all(): u = IngredientUsage(recipe=recipe, ingredient=ingredient, quantity=1) u.save() # ... rest of the code ...
a5cd2110283ba699f36548c42b83aa86e6b50aab
configuration.py
configuration.py
from trytond.model import fields, ModelSingleton, ModelSQL, ModelView __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Integer('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
from trytond import backend from trytond.model import fields, ModelSingleton, ModelSQL, ModelView from trytond.transaction import Transaction __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Char('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) @classmethod def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor # Migration from 3.4.0.6 : Migrate account_id field to string if backend.name() == 'postgresql': cursor.execute( 'SELECT pg_typeof("account_id") ' 'FROM endicia_configuration ' 'LIMIT 1', ) # Check if account_id is integer field is_integer = cursor.fetchone()[0] == 'integer' if is_integer: # Migrate integer field to string table = TableHandler(cursor, cls, module_name) table.alter_type('account_id', 'varchar') super(EndiciaConfiguration, cls).__register__(module_name) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
Migrate account_id from integer field to char field
Migrate account_id from integer field to char field
Python
bsd-3-clause
priyankarani/trytond-shipping-endicia,fulfilio/trytond-shipping-endicia,prakashpp/trytond-shipping-endicia
+ from trytond import backend from trytond.model import fields, ModelSingleton, ModelSQL, ModelView + from trytond.transaction import Transaction __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' - account_id = fields.Integer('Account Id') + account_id = fields.Char('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) + + @classmethod + def __register__(cls, module_name): + TableHandler = backend.get('TableHandler') + cursor = Transaction().cursor + + # Migration from 3.4.0.6 : Migrate account_id field to string + if backend.name() == 'postgresql': + cursor.execute( + 'SELECT pg_typeof("account_id") ' + 'FROM endicia_configuration ' + 'LIMIT 1', + ) + + # Check if account_id is integer field + is_integer = cursor.fetchone()[0] == 'integer' + + if is_integer: + # Migrate integer field to string + table = TableHandler(cursor, cls, module_name) + table.alter_type('account_id', 'varchar') + + super(EndiciaConfiguration, cls).__register__(module_name) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
Migrate account_id from integer field to char field
## Code Before: from trytond.model import fields, ModelSingleton, ModelSQL, ModelView __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Integer('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self ## Instruction: Migrate account_id from integer field to char field ## Code After: from trytond import backend from trytond.model import fields, ModelSingleton, ModelSQL, ModelView from trytond.transaction import Transaction __all__ = ['EndiciaConfiguration'] class EndiciaConfiguration(ModelSingleton, ModelSQL, ModelView): """ Configuration settings for Endicia. """ __name__ = 'endicia.configuration' account_id = fields.Char('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') is_test = fields.Boolean('Is Test') @classmethod def __setup__(cls): super(EndiciaConfiguration, cls).__setup__() cls._error_messages.update({ 'endicia_credentials_required': 'Endicia settings on endicia configuration are incomplete.', }) @classmethod def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor # Migration from 3.4.0.6 : Migrate account_id field to string if backend.name() == 'postgresql': cursor.execute( 'SELECT pg_typeof("account_id") ' 'FROM endicia_configuration ' 'LIMIT 1', ) # Check if account_id is integer field is_integer = cursor.fetchone()[0] == 'integer' if is_integer: # Migrate integer field to string table = TableHandler(cursor, cls, module_name) table.alter_type('account_id', 'varchar') super(EndiciaConfiguration, cls).__register__(module_name) def get_endicia_credentials(self): """Validate if endicia credentials are complete. """ if not all([ self.account_id, self.requester_id, self.passphrase ]): self.raise_user_error('endicia_credentials_required') return self
# ... existing code ... from trytond import backend from trytond.model import fields, ModelSingleton, ModelSQL, ModelView from trytond.transaction import Transaction __all__ = ['EndiciaConfiguration'] # ... modified code ... __name__ = 'endicia.configuration' account_id = fields.Char('Account Id') requester_id = fields.Char('Requester Id') passphrase = fields.Char('Passphrase') ... }) @classmethod def __register__(cls, module_name): TableHandler = backend.get('TableHandler') cursor = Transaction().cursor # Migration from 3.4.0.6 : Migrate account_id field to string if backend.name() == 'postgresql': cursor.execute( 'SELECT pg_typeof("account_id") ' 'FROM endicia_configuration ' 'LIMIT 1', ) # Check if account_id is integer field is_integer = cursor.fetchone()[0] == 'integer' if is_integer: # Migrate integer field to string table = TableHandler(cursor, cls, module_name) table.alter_type('account_id', 'varchar') super(EndiciaConfiguration, cls).__register__(module_name) def get_endicia_credentials(self): """Validate if endicia credentials are complete. # ... rest of the code ...
0041b029cc9b55084c89a9875de5e85728b9083c
src/birding/spout.py
src/birding/spout.py
from __future__ import absolute_import, print_function import datetime import itertools from streamparse.spout import Spout class SimpleSimulationSpout(Spout): urls = [ 'http://www.parsely.com/', 'http://streamparse.readthedocs.org/', 'https://pypi.python.org/pypi/streamparse', ] def initialize(self, stormconf, context): self.url_seq = itertools.cycle(self.urls) def next_tuple(self): url = next(self.url_seq) timestamp = datetime.datetime.now().isoformat() self.emit([url, timestamp])
from __future__ import absolute_import, print_function import datetime import itertools from streamparse.spout import Spout class SimpleSimulationSpout(Spout): terms = [ 'real-time analytics', 'apache storm', 'pypi', ] def initialize(self, stormconf, context): self.term_seq = itertools.cycle(self.terms) def next_tuple(self): term = next(self.term_seq) timestamp = datetime.datetime.now().isoformat() self.emit([term, timestamp])
Change simulation to search terms.
Change simulation to search terms.
Python
apache-2.0
Parsely/birding,Parsely/birding
from __future__ import absolute_import, print_function import datetime import itertools from streamparse.spout import Spout class SimpleSimulationSpout(Spout): - urls = [ + terms = [ - 'http://www.parsely.com/', - 'http://streamparse.readthedocs.org/', - 'https://pypi.python.org/pypi/streamparse', + 'real-time analytics', + 'apache storm', + 'pypi', ] def initialize(self, stormconf, context): - self.url_seq = itertools.cycle(self.urls) + self.term_seq = itertools.cycle(self.terms) def next_tuple(self): - url = next(self.url_seq) + term = next(self.term_seq) timestamp = datetime.datetime.now().isoformat() - self.emit([url, timestamp]) + self.emit([term, timestamp])
Change simulation to search terms.
## Code Before: from __future__ import absolute_import, print_function import datetime import itertools from streamparse.spout import Spout class SimpleSimulationSpout(Spout): urls = [ 'http://www.parsely.com/', 'http://streamparse.readthedocs.org/', 'https://pypi.python.org/pypi/streamparse', ] def initialize(self, stormconf, context): self.url_seq = itertools.cycle(self.urls) def next_tuple(self): url = next(self.url_seq) timestamp = datetime.datetime.now().isoformat() self.emit([url, timestamp]) ## Instruction: Change simulation to search terms. ## Code After: from __future__ import absolute_import, print_function import datetime import itertools from streamparse.spout import Spout class SimpleSimulationSpout(Spout): terms = [ 'real-time analytics', 'apache storm', 'pypi', ] def initialize(self, stormconf, context): self.term_seq = itertools.cycle(self.terms) def next_tuple(self): term = next(self.term_seq) timestamp = datetime.datetime.now().isoformat() self.emit([term, timestamp])
# ... existing code ... class SimpleSimulationSpout(Spout): terms = [ 'real-time analytics', 'apache storm', 'pypi', ] def initialize(self, stormconf, context): self.term_seq = itertools.cycle(self.terms) def next_tuple(self): term = next(self.term_seq) timestamp = datetime.datetime.now().isoformat() self.emit([term, timestamp]) # ... rest of the code ...
8df7c4b2c008ce6c7735106c28bad1f7326f7012
tests/smoketests/test_twisted.py
tests/smoketests/test_twisted.py
from twisted.internet import reactor, task def test_deferred(): return task.deferLater(reactor, 0.05, lambda: None)
from twisted.internet import reactor, task from twisted.internet.defer import Deferred, succeed from twisted.python.failure import Failure def test_deferred(): return task.deferLater(reactor, 0.05, lambda: None) def test_failure(): """ Test that we can check for a failure in an asynchronously-called function. """ # Create one Deferred for the result of the test function. deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails) # Create another Deferred, which will give the opposite result of # deferredThatFails (that is, which will succeed if deferredThatFails fails # and vice versa). deferredThatSucceeds = Deferred() # It's tempting to just write something like: # # deferredThatFails.addCallback(deferredThatSucceeds.errback) # deferredThatFails.addErrback (deferredThatSucceeds.callback) # # Unfortunately, that doesn't work. The problem is that each callbacks or # errbacks in a Deferred's callback/errback chain is passed the result of # the previous callback/errback, and execution switches between those # chains depending on whether that result is a failure or not. So if a # callback returns a failure, we switch to the errbacks, and if an errback # doesn't return a failure, we switch to the callbacks. If we use the # above, then when deferredThatFails fails, the following will happen: # # - deferredThatFails' first (and only) errback is called: the function # deferredThatSucceeds.callback. It is passed some sort of failure # object. # - This causes deferredThatSucceeds to fire. We start its callback # chain, passing in that same failure object that was passed to # deferredThatFails' errback chain. # - Since this is a failure object, we switch to the errback chain of # deferredThatSucceeds. I believe this happens before the first # callback is executed, because that callback is probably something # setup by pytest that would cause the test to pass. So it looks like # what's happening is we're bypassing that function entirely, and going # straight to the errback, which causes the test to fail. # # The solution is to instead create two functions of our own, which call # deferredThatSucceeds.callback and .errback but change whether the # argument is a failure so that it won't cause us to switch between the # callback and errback chains. def passTest(arg): # arg is a failure object of some sort. Don't pass it to callback # because otherwise it'll trigger the errback, which will cause the # test to fail. deferredThatSucceeds.callback(None) def failTest(arg): # Manufacture a failure to pass to errback because otherwise twisted # will switch to the callback chain, causing the test to pass. theFailure = Failure(AssertionError("functionThatFails didn't fail")) deferredThatSucceeds.errback(theFailure) deferredThatFails.addCallbacks(failTest, passTest) return deferredThatSucceeds def functionThatFails(): assert False
Add an example Twisted test that expects failure.
Add an example Twisted test that expects failure.
Python
mit
CheeseLord/warts,CheeseLord/warts
from twisted.internet import reactor, task + from twisted.internet.defer import Deferred, succeed + from twisted.python.failure import Failure def test_deferred(): return task.deferLater(reactor, 0.05, lambda: None) + def test_failure(): + """ + Test that we can check for a failure in an asynchronously-called function. + """ + + # Create one Deferred for the result of the test function. + deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails) + + # Create another Deferred, which will give the opposite result of + # deferredThatFails (that is, which will succeed if deferredThatFails fails + # and vice versa). + deferredThatSucceeds = Deferred() + + # It's tempting to just write something like: + # + # deferredThatFails.addCallback(deferredThatSucceeds.errback) + # deferredThatFails.addErrback (deferredThatSucceeds.callback) + # + # Unfortunately, that doesn't work. The problem is that each callbacks or + # errbacks in a Deferred's callback/errback chain is passed the result of + # the previous callback/errback, and execution switches between those + # chains depending on whether that result is a failure or not. So if a + # callback returns a failure, we switch to the errbacks, and if an errback + # doesn't return a failure, we switch to the callbacks. If we use the + # above, then when deferredThatFails fails, the following will happen: + # + # - deferredThatFails' first (and only) errback is called: the function + # deferredThatSucceeds.callback. It is passed some sort of failure + # object. + # - This causes deferredThatSucceeds to fire. We start its callback + # chain, passing in that same failure object that was passed to + # deferredThatFails' errback chain. + # - Since this is a failure object, we switch to the errback chain of + # deferredThatSucceeds. I believe this happens before the first + # callback is executed, because that callback is probably something + # setup by pytest that would cause the test to pass. So it looks like + # what's happening is we're bypassing that function entirely, and going + # straight to the errback, which causes the test to fail. + # + # The solution is to instead create two functions of our own, which call + # deferredThatSucceeds.callback and .errback but change whether the + # argument is a failure so that it won't cause us to switch between the + # callback and errback chains. + + def passTest(arg): + # arg is a failure object of some sort. Don't pass it to callback + # because otherwise it'll trigger the errback, which will cause the + # test to fail. + deferredThatSucceeds.callback(None) + def failTest(arg): + # Manufacture a failure to pass to errback because otherwise twisted + # will switch to the callback chain, causing the test to pass. + theFailure = Failure(AssertionError("functionThatFails didn't fail")) + deferredThatSucceeds.errback(theFailure) + + deferredThatFails.addCallbacks(failTest, passTest) + + return deferredThatSucceeds + + def functionThatFails(): + assert False + +
Add an example Twisted test that expects failure.
## Code Before: from twisted.internet import reactor, task def test_deferred(): return task.deferLater(reactor, 0.05, lambda: None) ## Instruction: Add an example Twisted test that expects failure. ## Code After: from twisted.internet import reactor, task from twisted.internet.defer import Deferred, succeed from twisted.python.failure import Failure def test_deferred(): return task.deferLater(reactor, 0.05, lambda: None) def test_failure(): """ Test that we can check for a failure in an asynchronously-called function. """ # Create one Deferred for the result of the test function. deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails) # Create another Deferred, which will give the opposite result of # deferredThatFails (that is, which will succeed if deferredThatFails fails # and vice versa). deferredThatSucceeds = Deferred() # It's tempting to just write something like: # # deferredThatFails.addCallback(deferredThatSucceeds.errback) # deferredThatFails.addErrback (deferredThatSucceeds.callback) # # Unfortunately, that doesn't work. The problem is that each callbacks or # errbacks in a Deferred's callback/errback chain is passed the result of # the previous callback/errback, and execution switches between those # chains depending on whether that result is a failure or not. So if a # callback returns a failure, we switch to the errbacks, and if an errback # doesn't return a failure, we switch to the callbacks. If we use the # above, then when deferredThatFails fails, the following will happen: # # - deferredThatFails' first (and only) errback is called: the function # deferredThatSucceeds.callback. It is passed some sort of failure # object. # - This causes deferredThatSucceeds to fire. We start its callback # chain, passing in that same failure object that was passed to # deferredThatFails' errback chain. # - Since this is a failure object, we switch to the errback chain of # deferredThatSucceeds. I believe this happens before the first # callback is executed, because that callback is probably something # setup by pytest that would cause the test to pass. So it looks like # what's happening is we're bypassing that function entirely, and going # straight to the errback, which causes the test to fail. # # The solution is to instead create two functions of our own, which call # deferredThatSucceeds.callback and .errback but change whether the # argument is a failure so that it won't cause us to switch between the # callback and errback chains. def passTest(arg): # arg is a failure object of some sort. Don't pass it to callback # because otherwise it'll trigger the errback, which will cause the # test to fail. deferredThatSucceeds.callback(None) def failTest(arg): # Manufacture a failure to pass to errback because otherwise twisted # will switch to the callback chain, causing the test to pass. theFailure = Failure(AssertionError("functionThatFails didn't fail")) deferredThatSucceeds.errback(theFailure) deferredThatFails.addCallbacks(failTest, passTest) return deferredThatSucceeds def functionThatFails(): assert False
// ... existing code ... from twisted.internet import reactor, task from twisted.internet.defer import Deferred, succeed from twisted.python.failure import Failure // ... modified code ... return task.deferLater(reactor, 0.05, lambda: None) def test_failure(): """ Test that we can check for a failure in an asynchronously-called function. """ # Create one Deferred for the result of the test function. deferredThatFails = task.deferLater(reactor, 0.05, functionThatFails) # Create another Deferred, which will give the opposite result of # deferredThatFails (that is, which will succeed if deferredThatFails fails # and vice versa). deferredThatSucceeds = Deferred() # It's tempting to just write something like: # # deferredThatFails.addCallback(deferredThatSucceeds.errback) # deferredThatFails.addErrback (deferredThatSucceeds.callback) # # Unfortunately, that doesn't work. The problem is that each callbacks or # errbacks in a Deferred's callback/errback chain is passed the result of # the previous callback/errback, and execution switches between those # chains depending on whether that result is a failure or not. So if a # callback returns a failure, we switch to the errbacks, and if an errback # doesn't return a failure, we switch to the callbacks. If we use the # above, then when deferredThatFails fails, the following will happen: # # - deferredThatFails' first (and only) errback is called: the function # deferredThatSucceeds.callback. It is passed some sort of failure # object. # - This causes deferredThatSucceeds to fire. We start its callback # chain, passing in that same failure object that was passed to # deferredThatFails' errback chain. # - Since this is a failure object, we switch to the errback chain of # deferredThatSucceeds. I believe this happens before the first # callback is executed, because that callback is probably something # setup by pytest that would cause the test to pass. So it looks like # what's happening is we're bypassing that function entirely, and going # straight to the errback, which causes the test to fail. # # The solution is to instead create two functions of our own, which call # deferredThatSucceeds.callback and .errback but change whether the # argument is a failure so that it won't cause us to switch between the # callback and errback chains. def passTest(arg): # arg is a failure object of some sort. Don't pass it to callback # because otherwise it'll trigger the errback, which will cause the # test to fail. deferredThatSucceeds.callback(None) def failTest(arg): # Manufacture a failure to pass to errback because otherwise twisted # will switch to the callback chain, causing the test to pass. theFailure = Failure(AssertionError("functionThatFails didn't fail")) deferredThatSucceeds.errback(theFailure) deferredThatFails.addCallbacks(failTest, passTest) return deferredThatSucceeds def functionThatFails(): assert False // ... rest of the code ...
63ce9ac2a46f74704810d62e22c0b75ca071442a
minesweeper/minesweeper.py
minesweeper/minesweeper.py
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) return bool(r.match("".join(b)))
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) # bool is technically redundant here, but I'd rather that this function # return an explicit True/False return bool(r.match("".join(b)))
Add note regarding use of bool in validation
Add note regarding use of bool in validation
Python
agpl-3.0
CubicComet/exercism-python-solutions
import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) + # bool is technically redundant here, but I'd rather that this function + # return an explicit True/False return bool(r.match("".join(b)))
Add note regarding use of bool in validation
## Code Before: import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) return bool(r.match("".join(b))) ## Instruction: Add note regarding use of bool in validation ## Code After: import re class InvalidBoard(ValueError): pass def board(b): if not is_valid_board(b): raise InvalidBoard("Board is malformed and thus invalid") b = [[ch for ch in row] for row in b] for i in range(1, len(b)-1): for j in range(1, len(b[0])-1): if b[i][j] == " ": m = "".join(b[i-1][j-1:j+2] + b[i][j-1:j+2] + b[i+1][j-1:j+2]) count = m.count("*") if count: b[i][j] = str(count) return list(map("".join, b)) def is_valid_board(b): width = "{" + str(len(b[0]) - 2) + "}" height = "{" + str(len(b) - 2) + "}" r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) # bool is technically redundant here, but I'd rather that this function # return an explicit True/False return bool(r.match("".join(b)))
# ... existing code ... r = re.compile("^(\+-{w}\+)(\|[ *]{w}\|){h}(\+-{w}\+)$".format(w=width, h=height)) # bool is technically redundant here, but I'd rather that this function # return an explicit True/False return bool(r.match("".join(b))) # ... rest of the code ...
8d0c87b21b17f0567dc4ce642437860cdf35bc6b
linter.py
linter.py
"""This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syntax = 'lua' tempfile_suffix = 'lua' defaults = { '--ignore:,': ['channel'], '--only:,': [], '--limit=': None, '--globals:,': [], } comment_re = r'\s*--' inline_settings = 'limit' inline_overrides = ('ignore', 'only', 'globals') config_file = ('--config', '.luacheckrc', '~') cmd = 'luacheck @ *' regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$' def build_args(self, settings): """Return args, transforming --ignore, --only, and --globals args into a format luacheck understands.""" args = super().build_args(settings) for arg in ('--ignore', '--only', '--globals'): try: index = args.index(arg) values = args[index + 1].split(',') args[index + 1:index + 2] = values except ValueError: pass return args
"""This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syntax = 'lua' cmd = 'luacheck - --formatter=plain --codes --ranges --filename @' version_args = '--help' version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.11.0, < 1.0.0' regex = ( r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): ' r'\((?:(?P<error>E)|(?P<warning>W))\d+\) ' r'(?P<message>.+)' ) def split_match(self, match): """Patch regex matches to highlight token correctly.""" match, line, col, error, warning, msg, _ = super().split_match(match) col_end = int(match.group(3)) token_len = col_end - col return match, line, col, error, warning, msg, "." * token_len
Update for luacheck >= 0.11.0
Update for luacheck >= 0.11.0 * Remove 'channel' from default ignore list. * Remove SublimeLinter inline options, use luacheck inline options. * Use `--ranges` to highlight tokens correctly. * Use `--codes` to distinguish warnings from errors. * Use `--filename` to apply per-path config overrides correctly. * Add version requirement.
Python
mit
SublimeLinter/SublimeLinter-luacheck
"""This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syntax = 'lua' + cmd = 'luacheck - --formatter=plain --codes --ranges --filename @' - tempfile_suffix = 'lua' - defaults = { - '--ignore:,': ['channel'], - '--only:,': [], - '--limit=': None, - '--globals:,': [], - } - comment_re = r'\s*--' - inline_settings = 'limit' - inline_overrides = ('ignore', 'only', 'globals') - config_file = ('--config', '.luacheckrc', '~') - cmd = 'luacheck @ *' - regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$' - def build_args(self, settings): - """Return args, transforming --ignore, --only, and --globals args into a format luacheck understands.""" - args = super().build_args(settings) + version_args = '--help' + version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)' + version_requirement = '>= 0.11.0, < 1.0.0' + regex = ( + r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): ' + r'\((?:(?P<error>E)|(?P<warning>W))\d+\) ' + r'(?P<message>.+)' + ) - for arg in ('--ignore', '--only', '--globals'): - try: - index = args.index(arg) - values = args[index + 1].split(',') - args[index + 1:index + 2] = values - except ValueError: - pass - return args + def split_match(self, match): + """Patch regex matches to highlight token correctly.""" + match, line, col, error, warning, msg, _ = super().split_match(match) + col_end = int(match.group(3)) + token_len = col_end - col + return match, line, col, error, warning, msg, "." * token_len
Update for luacheck >= 0.11.0
## Code Before: """This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syntax = 'lua' tempfile_suffix = 'lua' defaults = { '--ignore:,': ['channel'], '--only:,': [], '--limit=': None, '--globals:,': [], } comment_re = r'\s*--' inline_settings = 'limit' inline_overrides = ('ignore', 'only', 'globals') config_file = ('--config', '.luacheckrc', '~') cmd = 'luacheck @ *' regex = r'^(?P<filename>.+):(?P<line>\d+):(?P<col>\d+): (?P<message>.*)$' def build_args(self, settings): """Return args, transforming --ignore, --only, and --globals args into a format luacheck understands.""" args = super().build_args(settings) for arg in ('--ignore', '--only', '--globals'): try: index = args.index(arg) values = args[index + 1].split(',') args[index + 1:index + 2] = values except ValueError: pass return args ## Instruction: Update for luacheck >= 0.11.0 ## Code After: """This module exports the Luacheck plugin class.""" from SublimeLinter.lint import Linter class Luacheck(Linter): """Provides an interface to luacheck.""" syntax = 'lua' cmd = 'luacheck - --formatter=plain --codes --ranges --filename @' version_args = '--help' version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.11.0, < 1.0.0' regex = ( r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): ' r'\((?:(?P<error>E)|(?P<warning>W))\d+\) ' r'(?P<message>.+)' ) def split_match(self, match): """Patch regex matches to highlight token correctly.""" match, line, col, error, warning, msg, _ = super().split_match(match) col_end = int(match.group(3)) token_len = col_end - col return match, line, col, error, warning, msg, "." * token_len
... syntax = 'lua' cmd = 'luacheck - --formatter=plain --codes --ranges --filename @' version_args = '--help' version_re = r'[Ll]uacheck (?P<version>\d+\.\d+\.\d+)' version_requirement = '>= 0.11.0, < 1.0.0' regex = ( r'^.+:(?P<line>\d+):(?P<col>\d+)\-(?P<col_end>\d+): ' r'\((?:(?P<error>E)|(?P<warning>W))\d+\) ' r'(?P<message>.+)' ) def split_match(self, match): """Patch regex matches to highlight token correctly.""" match, line, col, error, warning, msg, _ = super().split_match(match) col_end = int(match.group(3)) token_len = col_end - col return match, line, col, error, warning, msg, "." * token_len ...
fb3abf0d1cf27d23c78dd8101dd0c54cf589c2ef
corehq/apps/locations/resources/v0_6.py
corehq/apps/locations/resources/v0_6.py
from corehq.apps.api.resources.auth import RequirePermissionAuthentication from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import HqPermissions from corehq.apps.locations.resources import v0_5 class LocationResource(v0_5.LocationResource): resource_name = 'location' class Meta: queryset = SQLLocation.objects.filter(is_archived=False).all() detail_uri_name = 'location_id' authentication = RequirePermissionAuthentication(HqPermissions.edit_locations) allowed_methods = ['get'] include_resource_uri = False fields = { 'domain', 'location_id', 'name', 'site_code', 'last_modified', 'latitude', 'longitude', 'location_data', } filtering = { "domain": ('exact',), } def dehydrate(self, bundle): if bundle.obj.parent: bundle.data['parent_location_id'] = bundle.obj.parent.location_id else: bundle.data['parent_location_id'] = '' bundle.data['location_type_name'] = bundle.obj.location_type.name bundle.data['location_type_code'] = bundle.obj.location_type.code return bundle
from corehq.apps.api.resources.auth import RequirePermissionAuthentication from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import HqPermissions from corehq.apps.locations.resources import v0_5 class LocationResource(v0_5.LocationResource): resource_name = 'location' class Meta: queryset = SQLLocation.active_objects.all() detail_uri_name = 'location_id' authentication = RequirePermissionAuthentication(HqPermissions.edit_locations) allowed_methods = ['get'] include_resource_uri = False fields = { 'domain', 'location_id', 'name', 'site_code', 'last_modified', 'latitude', 'longitude', 'location_data', } filtering = { "domain": ('exact',), } def dehydrate(self, bundle): if bundle.obj.parent: bundle.data['parent_location_id'] = bundle.obj.parent.location_id else: bundle.data['parent_location_id'] = '' bundle.data['location_type_name'] = bundle.obj.location_type.name bundle.data['location_type_code'] = bundle.obj.location_type.code return bundle
Use objects manager that automatically filters out archived forms
Use objects manager that automatically filters out archived forms Co-authored-by: Ethan Soergel <c1732a0c832c5c8cbfae77286e6475129315f488@users.noreply.github.com>
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from corehq.apps.api.resources.auth import RequirePermissionAuthentication from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import HqPermissions from corehq.apps.locations.resources import v0_5 class LocationResource(v0_5.LocationResource): resource_name = 'location' class Meta: - queryset = SQLLocation.objects.filter(is_archived=False).all() + queryset = SQLLocation.active_objects.all() detail_uri_name = 'location_id' authentication = RequirePermissionAuthentication(HqPermissions.edit_locations) allowed_methods = ['get'] include_resource_uri = False fields = { 'domain', 'location_id', 'name', 'site_code', 'last_modified', 'latitude', 'longitude', 'location_data', } filtering = { "domain": ('exact',), } def dehydrate(self, bundle): if bundle.obj.parent: bundle.data['parent_location_id'] = bundle.obj.parent.location_id else: bundle.data['parent_location_id'] = '' bundle.data['location_type_name'] = bundle.obj.location_type.name bundle.data['location_type_code'] = bundle.obj.location_type.code return bundle
Use objects manager that automatically filters out archived forms
## Code Before: from corehq.apps.api.resources.auth import RequirePermissionAuthentication from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import HqPermissions from corehq.apps.locations.resources import v0_5 class LocationResource(v0_5.LocationResource): resource_name = 'location' class Meta: queryset = SQLLocation.objects.filter(is_archived=False).all() detail_uri_name = 'location_id' authentication = RequirePermissionAuthentication(HqPermissions.edit_locations) allowed_methods = ['get'] include_resource_uri = False fields = { 'domain', 'location_id', 'name', 'site_code', 'last_modified', 'latitude', 'longitude', 'location_data', } filtering = { "domain": ('exact',), } def dehydrate(self, bundle): if bundle.obj.parent: bundle.data['parent_location_id'] = bundle.obj.parent.location_id else: bundle.data['parent_location_id'] = '' bundle.data['location_type_name'] = bundle.obj.location_type.name bundle.data['location_type_code'] = bundle.obj.location_type.code return bundle ## Instruction: Use objects manager that automatically filters out archived forms ## Code After: from corehq.apps.api.resources.auth import RequirePermissionAuthentication from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import HqPermissions from corehq.apps.locations.resources import v0_5 class LocationResource(v0_5.LocationResource): resource_name = 'location' class Meta: queryset = SQLLocation.active_objects.all() detail_uri_name = 'location_id' authentication = RequirePermissionAuthentication(HqPermissions.edit_locations) allowed_methods = ['get'] include_resource_uri = False fields = { 'domain', 'location_id', 'name', 'site_code', 'last_modified', 'latitude', 'longitude', 'location_data', } filtering = { "domain": ('exact',), } def dehydrate(self, bundle): if bundle.obj.parent: bundle.data['parent_location_id'] = bundle.obj.parent.location_id else: bundle.data['parent_location_id'] = '' bundle.data['location_type_name'] = bundle.obj.location_type.name bundle.data['location_type_code'] = bundle.obj.location_type.code return bundle
# ... existing code ... class Meta: queryset = SQLLocation.active_objects.all() detail_uri_name = 'location_id' authentication = RequirePermissionAuthentication(HqPermissions.edit_locations) # ... rest of the code ...
e7c5e62da700f51e69662689758ffebf70fa1494
cms/djangoapps/contentstore/context_processors.py
cms/djangoapps/contentstore/context_processors.py
import ConfigParser from django.conf import settings def doc_url(request): config_file = open(settings.REPO_ROOT / "docs" / "config.ini") config = ConfigParser.ConfigParser() config.readfp(config_file) # in the future, we will detect the locale; for now, we will # hardcode en_us, since we only have English documentation locale = "en_us" def get_doc_url(token): try: return config.get(locale, token) except ConfigParser.NoOptionError: return config.get(locale, "default") return {"doc_url": get_doc_url}
import ConfigParser from django.conf import settings config_file = open(settings.REPO_ROOT / "docs" / "config.ini") config = ConfigParser.ConfigParser() config.readfp(config_file) def doc_url(request): # in the future, we will detect the locale; for now, we will # hardcode en_us, since we only have English documentation locale = "en_us" def get_doc_url(token): try: return config.get(locale, token) except ConfigParser.NoOptionError: return config.get(locale, "default") return {"doc_url": get_doc_url}
Read from doc url mapping file at load time, rather than once per request
Read from doc url mapping file at load time, rather than once per request
Python
agpl-3.0
ampax/edx-platform,Softmotions/edx-platform,dcosentino/edx-platform,chudaol/edx-platform,prarthitm/edxplatform,cyanna/edx-platform,jazztpt/edx-platform,motion2015/a3,nikolas/edx-platform,msegado/edx-platform,hkawasaki/kawasaki-aio8-0,LearnEra/LearnEraPlaftform,pabloborrego93/edx-platform,wwj718/ANALYSE,procangroup/edx-platform,ahmadiga/min_edx,wwj718/edx-platform,edx/edx-platform,morenopc/edx-platform,leansoft/edx-platform,cyanna/edx-platform,shubhdev/edxOnBaadal,leansoft/edx-platform,SivilTaram/edx-platform,shabab12/edx-platform,zadgroup/edx-platform,dsajkl/123,pku9104038/edx-platform,antoviaque/edx-platform,ovnicraft/edx-platform,mahendra-r/edx-platform,zhenzhai/edx-platform,eestay/edx-platform,abdoosh00/edraak,jjmiranda/edx-platform,leansoft/edx-platform,nikolas/edx-platform,longmen21/edx-platform,jruiperezv/ANALYSE,kamalx/edx-platform,Kalyzee/edx-platform,andyzsf/edx,CourseTalk/edx-platform,beacloudgenius/edx-platform,chauhanhardik/populo_2,fly19890211/edx-platform,rismalrv/edx-platform,hkawasaki/kawasaki-aio8-0,teltek/edx-platform,openfun/edx-platform,devs1991/test_edx_docmode,shubhdev/openedx,zadgroup/edx-platform,waheedahmed/edx-platform,Kalyzee/edx-platform,vasyarv/edx-platform,shubhdev/openedx,louyihua/edx-platform,Shrhawk/edx-platform,don-github/edx-platform,alu042/edx-platform,zhenzhai/edx-platform,mcgachey/edx-platform,mitocw/edx-platform,xuxiao19910803/edx-platform,LICEF/edx-platform,jswope00/griffinx,y12uc231/edx-platform,nanolearning/edx-platform,inares/edx-platform,benpatterson/edx-platform,ahmedaljazzar/edx-platform,mjirayu/sit_academy,gsehub/edx-platform,deepsrijit1105/edx-platform,Stanford-Online/edx-platform,zofuthan/edx-platform,playm2mboy/edx-platform,a-parhom/edx-platform,miptliot/edx-platform,playm2mboy/edx-platform,beni55/edx-platform,alu042/edx-platform,LICEF/edx-platform,naresh21/synergetics-edx-platform,bigdatauniversity/edx-platform,AkA84/edx-platform,caesar2164/edx-platform,WatanabeYasumasa/edx-platform,4eek/edx-platform,AkA84/edx-platform,UOMx/edx-platform,openfun/edx-platform,pku9104038/edx-platform,eestay/edx-platform,ampax/edx-platform,doganov/edx-platform,synergeticsedx/deployment-wipro,hkawasaki/kawasaki-aio8-0,jzoldak/edx-platform,franosincic/edx-platform,jswope00/griffinx,hkawasaki/kawasaki-aio8-2,proversity-org/edx-platform,dcosentino/edx-platform,dkarakats/edx-platform,tanmaykm/edx-platform,appliedx/edx-platform,nagyistoce/edx-platform,knehez/edx-platform,openfun/edx-platform,torchingloom/edx-platform,alu042/edx-platform,iivic/BoiseStateX,a-parhom/edx-platform,xuxiao19910803/edx-platform,etzhou/edx-platform,SravanthiSinha/edx-platform,pomegranited/edx-platform,EDUlib/edx-platform,cognitiveclass/edx-platform,arifsetiawan/edx-platform,cselis86/edx-platform,Ayub-Khan/edx-platform,vismartltd/edx-platform,unicri/edx-platform,kursitet/edx-platform,adoosii/edx-platform,fintech-circle/edx-platform,bitifirefly/edx-platform,mitocw/edx-platform,zerobatu/edx-platform,solashirai/edx-platform,doismellburning/edx-platform,proversity-org/edx-platform,xuxiao19910803/edx,ampax/edx-platform-backup,jazztpt/edx-platform,ak2703/edx-platform,cecep-edu/edx-platform,jelugbo/tundex,RPI-OPENEDX/edx-platform,chauhanhardik/populo_2,BehavioralInsightsTeam/edx-platform,rhndg/openedx,martynovp/edx-platform,tiagochiavericosta/edx-platform,jamiefolsom/edx-platform,nanolearning/edx-platform,BehavioralInsightsTeam/edx-platform,doganov/edx-platform,vasyarv/edx-platform,edry/edx-platform,tiagochiavericosta/edx-platform,fintech-circle/edx-platform,DefyVentures/edx-platform,OmarIthawi/edx-platform,jamesblunt/edx-platform,ZLLab-Mooc/edx-platform,alexthered/kienhoc-platform,devs1991/test_edx_docmode,cecep-edu/edx-platform,tiagochiavericosta/edx-platform,Edraak/edx-platform,jelugbo/tundex,motion2015/edx-platform,nanolearningllc/edx-platform-cypress-2,rismalrv/edx-platform,halvertoluke/edx-platform,mbareta/edx-platform-ft,marcore/edx-platform,miptliot/edx-platform,vikas1885/test1,B-MOOC/edx-platform,Kalyzee/edx-platform,dsajkl/reqiop,Livit/Livit.Learn.EdX,appsembler/edx-platform,amir-qayyum-khan/edx-platform,playm2mboy/edx-platform,nanolearningllc/edx-platform-cypress,procangroup/edx-platform,J861449197/edx-platform,nttks/jenkins-test,jbassen/edx-platform,ovnicraft/edx-platform,appliedx/edx-platform,gymnasium/edx-platform,mushtaqak/edx-platform,marcore/edx-platform,hkawasaki/kawasaki-aio8-2,ferabra/edx-platform,mbareta/edx-platform-ft,kursitet/edx-platform,nagyistoce/edx-platform,hkawasaki/kawasaki-aio8-1,ovnicraft/edx-platform,inares/edx-platform,jonathan-beard/edx-platform,IndonesiaX/edx-platform,UOMx/edx-platform,marcore/edx-platform,peterm-itr/edx-platform,shashank971/edx-platform,devs1991/test_edx_docmode,Shrhawk/edx-platform,naresh21/synergetics-edx-platform,morenopc/edx-platform,nanolearningllc/edx-platform-cypress-2,zofuthan/edx-platform,zhenzhai/edx-platform,EDUlib/edx-platform,polimediaupv/edx-platform,procangroup/edx-platform,jazztpt/edx-platform,atsolakid/edx-platform,stvstnfrd/edx-platform,doismellburning/edx-platform,xingyepei/edx-platform,jswope00/griffinx,hamzehd/edx-platform,motion2015/edx-platform,Edraak/circleci-edx-platform,sudheerchintala/LearnEraPlatForm,xinjiguaike/edx-platform,nttks/jenkins-test,mushtaqak/edx-platform,alu042/edx-platform,analyseuc3m/ANALYSE-v1,appliedx/edx-platform,chudaol/edx-platform,ahmadiga/min_edx,sameetb-cuelogic/edx-platform-test,romain-li/edx-platform,ESOedX/edx-platform,simbs/edx-platform,abdoosh00/edraak,chauhanhardik/populo,TeachAtTUM/edx-platform,shubhdev/edx-platform,gsehub/edx-platform,martynovp/edx-platform,ampax/edx-platform,appliedx/edx-platform,vikas1885/test1,IONISx/edx-platform,TeachAtTUM/edx-platform,shabab12/edx-platform,dsajkl/123,shubhdev/edxOnBaadal,hastexo/edx-platform,hkawasaki/kawasaki-aio8-2,prarthitm/edxplatform,cecep-edu/edx-platform,ubc/edx-platform,shurihell/testasia,kamalx/edx-platform,valtech-mooc/edx-platform,polimediaupv/edx-platform,motion2015/a3,antoviaque/edx-platform,JioEducation/edx-platform,prarthitm/edxplatform,benpatterson/edx-platform,defance/edx-platform,cognitiveclass/edx-platform,romain-li/edx-platform,hkawasaki/kawasaki-aio8-2,nanolearningllc/edx-platform-cypress,UXE/local-edx,zerobatu/edx-platform,xuxiao19910803/edx,peterm-itr/edx-platform,synergeticsedx/deployment-wipro,Stanford-Online/edx-platform,Semi-global/edx-platform,caesar2164/edx-platform,atsolakid/edx-platform,DNFcode/edx-platform,ahmadio/edx-platform,ahmadio/edx-platform,mahendra-r/edx-platform,polimediaupv/edx-platform,10clouds/edx-platform,rhndg/openedx,xuxiao19910803/edx-platform,kmoocdev2/edx-platform,shubhdev/edxOnBaadal,wwj718/edx-platform,vikas1885/test1,ahmedaljazzar/edx-platform,J861449197/edx-platform,inares/edx-platform,atsolakid/edx-platform,abdoosh00/edraak,UOMx/edx-platform,jazkarta/edx-platform-for-isc,simbs/edx-platform,nanolearningllc/edx-platform-cypress-2,OmarIthawi/edx-platform,shubhdev/openedx,ampax/edx-platform-backup,stvstnfrd/edx-platform,synergeticsedx/deployment-wipro,itsjeyd/edx-platform,romain-li/edx-platform,analyseuc3m/ANALYSE-v1,chand3040/cloud_that,SivilTaram/edx-platform,mushtaqak/edx-platform,msegado/edx-platform,beni55/edx-platform,hamzehd/edx-platform,Ayub-Khan/edx-platform,vikas1885/test1,kamalx/edx-platform,eduNEXT/edunext-platform,jazkarta/edx-platform,mahendra-r/edx-platform,OmarIthawi/edx-platform,defance/edx-platform,andyzsf/edx,CourseTalk/edx-platform,arifsetiawan/edx-platform,JioEducation/edx-platform,chrisndodge/edx-platform,openfun/edx-platform,kmoocdev2/edx-platform,IONISx/edx-platform,yokose-ks/edx-platform,shurihell/testasia,wwj718/ANALYSE,alexthered/kienhoc-platform,solashirai/edx-platform,tanmaykm/edx-platform,mjirayu/sit_academy,chudaol/edx-platform,cognitiveclass/edx-platform,kxliugang/edx-platform,ahmadiga/min_edx,Edraak/edraak-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,knehez/edx-platform,fly19890211/edx-platform,jonathan-beard/edx-platform,sameetb-cuelogic/edx-platform-test,AkA84/edx-platform,cyanna/edx-platform,zhenzhai/edx-platform,kmoocdev/edx-platform,etzhou/edx-platform,jelugbo/tundex,iivic/BoiseStateX,msegado/edx-platform,angelapper/edx-platform,jolyonb/edx-platform,zofuthan/edx-platform,itsjeyd/edx-platform,rhndg/openedx,chudaol/edx-platform,mtlchun/edx,ESOedX/edx-platform,xuxiao19910803/edx-platform,jamiefolsom/edx-platform,CourseTalk/edx-platform,rue89-tech/edx-platform,ZLLab-Mooc/edx-platform,jazztpt/edx-platform,UXE/local-edx,Semi-global/edx-platform,unicri/edx-platform,raccoongang/edx-platform,polimediaupv/edx-platform,MSOpenTech/edx-platform,Kalyzee/edx-platform,jbassen/edx-platform,pomegranited/edx-platform,arifsetiawan/edx-platform,Softmotions/edx-platform,IndonesiaX/edx-platform,ovnicraft/edx-platform,SivilTaram/edx-platform,longmen21/edx-platform,jamiefolsom/edx-platform,hmcmooc/muddx-platform,ubc/edx-platform,valtech-mooc/edx-platform,JCBarahona/edX,halvertoluke/edx-platform,jswope00/griffinx,DefyVentures/edx-platform,kmoocdev/edx-platform,zerobatu/edx-platform,Stanford-Online/edx-platform,cecep-edu/edx-platform,utecuy/edx-platform,Edraak/edraak-platform,nanolearningllc/edx-platform-cypress-2,defance/edx-platform,pku9104038/edx-platform,jswope00/GAI,stvstnfrd/edx-platform,chand3040/cloud_that,OmarIthawi/edx-platform,openfun/edx-platform,playm2mboy/edx-platform,adoosii/edx-platform,ampax/edx-platform-backup,olexiim/edx-platform,don-github/edx-platform,DefyVentures/edx-platform,appliedx/edx-platform,edry/edx-platform,dsajkl/reqiop,fintech-circle/edx-platform,martynovp/edx-platform,angelapper/edx-platform,SivilTaram/edx-platform,leansoft/edx-platform,edx/edx-platform,hkawasaki/kawasaki-aio8-1,doganov/edx-platform,ak2703/edx-platform,pomegranited/edx-platform,philanthropy-u/edx-platform,pomegranited/edx-platform,hamzehd/edx-platform,jbassen/edx-platform,dsajkl/123,franosincic/edx-platform,tanmaykm/edx-platform,hmcmooc/muddx-platform,mcgachey/edx-platform,SravanthiSinha/edx-platform,gsehub/edx-platform,louyihua/edx-platform,eemirtekin/edx-platform,sudheerchintala/LearnEraPlatForm,ampax/edx-platform-backup,bdero/edx-platform,xinjiguaike/edx-platform,jolyonb/edx-platform,nttks/jenkins-test,J861449197/edx-platform,jjmiranda/edx-platform,Shrhawk/edx-platform,jonathan-beard/edx-platform,antonve/s4-project-mooc,hamzehd/edx-platform,antoviaque/edx-platform,RPI-OPENEDX/edx-platform,solashirai/edx-platform,chauhanhardik/populo_2,jbzdak/edx-platform,nttks/edx-platform,ESOedX/edx-platform,EDUlib/edx-platform,edx-solutions/edx-platform,jamesblunt/edx-platform,xingyepei/edx-platform,mcgachey/edx-platform,kmoocdev2/edx-platform,dcosentino/edx-platform,rue89-tech/edx-platform,xuxiao19910803/edx,ampax/edx-platform,4eek/edx-platform,ahmadiga/min_edx,deepsrijit1105/edx-platform,jolyonb/edx-platform,unicri/edx-platform,ubc/edx-platform,rismalrv/edx-platform,MakeHer/edx-platform,motion2015/edx-platform,CredoReference/edx-platform,solashirai/edx-platform,jbzdak/edx-platform,Livit/Livit.Learn.EdX,RPI-OPENEDX/edx-platform,eduNEXT/edx-platform,hkawasaki/kawasaki-aio8-1,kmoocdev/edx-platform,devs1991/test_edx_docmode,Softmotions/edx-platform,morenopc/edx-platform,beni55/edx-platform,J861449197/edx-platform,jolyonb/edx-platform,itsjeyd/edx-platform,morenopc/edx-platform,shubhdev/edxOnBaadal,jazkarta/edx-platform,dkarakats/edx-platform,simbs/edx-platform,Lektorium-LLC/edx-platform,zadgroup/edx-platform,TeachAtTUM/edx-platform,RPI-OPENEDX/edx-platform,sameetb-cuelogic/edx-platform-test,nagyistoce/edx-platform,kursitet/edx-platform,jswope00/GAI,unicri/edx-platform,nikolas/edx-platform,Softmotions/edx-platform,LICEF/edx-platform,cognitiveclass/edx-platform,atsolakid/edx-platform,MSOpenTech/edx-platform,ahmadio/edx-platform,bitifirefly/edx-platform,carsongee/edx-platform,beacloudgenius/edx-platform,ak2703/edx-platform,defance/edx-platform,pepeportela/edx-platform,amir-qayyum-khan/edx-platform,JCBarahona/edX,carsongee/edx-platform,rhndg/openedx,gymnasium/edx-platform,beacloudgenius/edx-platform,kxliugang/edx-platform,longmen21/edx-platform,4eek/edx-platform,bitifirefly/edx-platform,mbareta/edx-platform-ft,ferabra/edx-platform,doganov/edx-platform,jonathan-beard/edx-platform,abdoosh00/edraak,vikas1885/test1,cecep-edu/edx-platform,franosincic/edx-platform,beni55/edx-platform,cpennington/edx-platform,Semi-global/edx-platform,B-MOOC/edx-platform,angelapper/edx-platform,ak2703/edx-platform,MakeHer/edx-platform,utecuy/edx-platform,zadgroup/edx-platform,jbzdak/edx-platform,olexiim/edx-platform,adoosii/edx-platform,cselis86/edx-platform,deepsrijit1105/edx-platform,bdero/edx-platform,angelapper/edx-platform,knehez/edx-platform,xingyepei/edx-platform,mbareta/edx-platform-ft,shubhdev/edx-platform,fly19890211/edx-platform,shashank971/edx-platform,xuxiao19910803/edx,edx/edx-platform,caesar2164/edx-platform,simbs/edx-platform,mahendra-r/edx-platform,Edraak/circleci-edx-platform,lduarte1991/edx-platform,jswope00/GAI,B-MOOC/edx-platform,chand3040/cloud_that,valtech-mooc/edx-platform,amir-qayyum-khan/edx-platform,B-MOOC/edx-platform,martynovp/edx-platform,vasyarv/edx-platform,zerobatu/edx-platform,jzoldak/edx-platform,mitocw/edx-platform,alexthered/kienhoc-platform,lduarte1991/edx-platform,motion2015/a3,alexthered/kienhoc-platform,BehavioralInsightsTeam/edx-platform,edx-solutions/edx-platform,shurihell/testasia,wwj718/ANALYSE,mtlchun/edx,philanthropy-u/edx-platform,olexiim/edx-platform,tiagochiavericosta/edx-platform,jelugbo/tundex,IONISx/edx-platform,mtlchun/edx,doismellburning/edx-platform,xinjiguaike/edx-platform,eemirtekin/edx-platform,vasyarv/edx-platform,MSOpenTech/edx-platform,Livit/Livit.Learn.EdX,knehez/edx-platform,bdero/edx-platform,raccoongang/edx-platform,mcgachey/edx-platform,shashank971/edx-platform,jzoldak/edx-platform,EDUlib/edx-platform,dkarakats/edx-platform,ZLLab-Mooc/edx-platform,itsjeyd/edx-platform,shabab12/edx-platform,J861449197/edx-platform,antonve/s4-project-mooc,jamesblunt/edx-platform,hmcmooc/muddx-platform,gymnasium/edx-platform,zubair-arbi/edx-platform,doismellburning/edx-platform,xuxiao19910803/edx-platform,appsembler/edx-platform,kamalx/edx-platform,zubair-arbi/edx-platform,LearnEra/LearnEraPlaftform,mcgachey/edx-platform,edry/edx-platform,shubhdev/openedx,JioEducation/edx-platform,solashirai/edx-platform,nanolearningllc/edx-platform-cypress,jruiperezv/ANALYSE,halvertoluke/edx-platform,analyseuc3m/ANALYSE-v1,arifsetiawan/edx-platform,appsembler/edx-platform,lduarte1991/edx-platform,Stanford-Online/edx-platform,ovnicraft/edx-platform,vismartltd/edx-platform,nagyistoce/edx-platform,LICEF/edx-platform,Lektorium-LLC/edx-platform,chauhanhardik/populo,chand3040/cloud_that,chrisndodge/edx-platform,cyanna/edx-platform,benpatterson/edx-platform,franosincic/edx-platform,Ayub-Khan/edx-platform,cselis86/edx-platform,mtlchun/edx,Lektorium-LLC/edx-platform,CredoReference/edx-platform,dcosentino/edx-platform,cognitiveclass/edx-platform,bigdatauniversity/edx-platform,JCBarahona/edX,jazztpt/edx-platform,antonve/s4-project-mooc,Edraak/edx-platform,shashank971/edx-platform,nanolearning/edx-platform,nanolearning/edx-platform,rue89-tech/edx-platform,miptliot/edx-platform,jonathan-beard/edx-platform,beni55/edx-platform,edx/edx-platform,devs1991/test_edx_docmode,nttks/edx-platform,dsajkl/reqiop,proversity-org/edx-platform,devs1991/test_edx_docmode,yokose-ks/edx-platform,antonve/s4-project-mooc,arbrandes/edx-platform,mahendra-r/edx-platform,y12uc231/edx-platform,zofuthan/edx-platform,sudheerchintala/LearnEraPlatForm,Ayub-Khan/edx-platform,ferabra/edx-platform,halvertoluke/edx-platform,beacloudgenius/edx-platform,inares/edx-platform,olexiim/edx-platform,beacloudgenius/edx-platform,hkawasaki/kawasaki-aio8-1,B-MOOC/edx-platform,vasyarv/edx-platform,wwj718/ANALYSE,arbrandes/edx-platform,4eek/edx-platform,WatanabeYasumasa/edx-platform,waheedahmed/edx-platform,ahmadio/edx-platform,a-parhom/edx-platform,valtech-mooc/edx-platform,eemirtekin/edx-platform,jruiperezv/ANALYSE,eduNEXT/edunext-platform,eduNEXT/edx-platform,bitifirefly/edx-platform,don-github/edx-platform,nttks/edx-platform,a-parhom/edx-platform,mjirayu/sit_academy,rismalrv/edx-platform,etzhou/edx-platform,inares/edx-platform,teltek/edx-platform,chauhanhardik/populo,kxliugang/edx-platform,IndonesiaX/edx-platform,jruiperezv/ANALYSE,shubhdev/edx-platform,Lektorium-LLC/edx-platform,ubc/edx-platform,ZLLab-Mooc/edx-platform,tanmaykm/edx-platform,jruiperezv/ANALYSE,devs1991/test_edx_docmode,jbzdak/edx-platform,rue89-tech/edx-platform,edx-solutions/edx-platform,doganov/edx-platform,edry/edx-platform,jamiefolsom/edx-platform,pabloborrego93/edx-platform,chrisndodge/edx-platform,SravanthiSinha/edx-platform,antonve/s4-project-mooc,proversity-org/edx-platform,jelugbo/tundex,auferack08/edx-platform,synergeticsedx/deployment-wipro,arifsetiawan/edx-platform,cselis86/edx-platform,marcore/edx-platform,jamesblunt/edx-platform,SravanthiSinha/edx-platform,hkawasaki/kawasaki-aio8-0,shurihell/testasia,UXE/local-edx,LearnEra/LearnEraPlaftform,LearnEra/LearnEraPlaftform,naresh21/synergetics-edx-platform,xinjiguaike/edx-platform,jazkarta/edx-platform,vismartltd/edx-platform,msegado/edx-platform,nikolas/edx-platform,jazkarta/edx-platform-for-isc,torchingloom/edx-platform,olexiim/edx-platform,wwj718/edx-platform,jazkarta/edx-platform,peterm-itr/edx-platform,louyihua/edx-platform,xinjiguaike/edx-platform,fly19890211/edx-platform,pepeportela/edx-platform,MakeHer/edx-platform,Edraak/edx-platform,yokose-ks/edx-platform,etzhou/edx-platform,BehavioralInsightsTeam/edx-platform,Endika/edx-platform,utecuy/edx-platform,waheedahmed/edx-platform,don-github/edx-platform,auferack08/edx-platform,hamzehd/edx-platform,utecuy/edx-platform,jbassen/edx-platform,chauhanhardik/populo,kamalx/edx-platform,atsolakid/edx-platform,bitifirefly/edx-platform,kursitet/edx-platform,chrisndodge/edx-platform,Shrhawk/edx-platform,UXE/local-edx,Unow/edx-platform,Endika/edx-platform,valtech-mooc/edx-platform,bigdatauniversity/edx-platform,eemirtekin/edx-platform,jamiefolsom/edx-platform,MakeHer/edx-platform,Ayub-Khan/edx-platform,jjmiranda/edx-platform,kxliugang/edx-platform,SravanthiSinha/edx-platform,10clouds/edx-platform,y12uc231/edx-platform,ZLLab-Mooc/edx-platform,ahmadiga/min_edx,Kalyzee/edx-platform,sameetb-cuelogic/edx-platform-test,ampax/edx-platform-backup,miptliot/edx-platform,jzoldak/edx-platform,cpennington/edx-platform,hastexo/edx-platform,ahmedaljazzar/edx-platform,eduNEXT/edunext-platform,don-github/edx-platform,arbrandes/edx-platform,10clouds/edx-platform,DefyVentures/edx-platform,yokose-ks/edx-platform,unicri/edx-platform,chudaol/edx-platform,chand3040/cloud_that,10clouds/edx-platform,eestay/edx-platform,jswope00/GAI,etzhou/edx-platform,zubair-arbi/edx-platform,analyseuc3m/ANALYSE-v1,morenopc/edx-platform,JCBarahona/edX,carsongee/edx-platform,kmoocdev/edx-platform,simbs/edx-platform,utecuy/edx-platform,deepsrijit1105/edx-platform,shabab12/edx-platform,yokose-ks/edx-platform,jswope00/griffinx,lduarte1991/edx-platform,romain-li/edx-platform,wwj718/edx-platform,zadgroup/edx-platform,fly19890211/edx-platform,Edraak/edx-platform,Edraak/edx-platform,WatanabeYasumasa/edx-platform,sameetb-cuelogic/edx-platform-test,jazkarta/edx-platform-for-isc,arbrandes/edx-platform,prarthitm/edxplatform,mushtaqak/edx-platform,CourseTalk/edx-platform,bdero/edx-platform,kmoocdev2/edx-platform,IONISx/edx-platform,cpennington/edx-platform,cyanna/edx-platform,4eek/edx-platform,polimediaupv/edx-platform,adoosii/edx-platform,nanolearningllc/edx-platform-cypress,amir-qayyum-khan/edx-platform,devs1991/test_edx_docmode,UOMx/edx-platform,torchingloom/edx-platform,bigdatauniversity/edx-platform,andyzsf/edx,stvstnfrd/edx-platform,antoviaque/edx-platform,edx-solutions/edx-platform,andyzsf/edx,Shrhawk/edx-platform,dkarakats/edx-platform,ferabra/edx-platform,motion2015/a3,iivic/BoiseStateX,eemirtekin/edx-platform,teltek/edx-platform,WatanabeYasumasa/edx-platform,Endika/edx-platform,franosincic/edx-platform,romain-li/edx-platform,chauhanhardik/populo_2,mjirayu/sit_academy,ak2703/edx-platform,kmoocdev2/edx-platform,gsehub/edx-platform,halvertoluke/edx-platform,LICEF/edx-platform,fintech-circle/edx-platform,SivilTaram/edx-platform,Unow/edx-platform,waheedahmed/edx-platform,kxliugang/edx-platform,jjmiranda/edx-platform,benpatterson/edx-platform,Endika/edx-platform,nttks/edx-platform,teltek/edx-platform,xuxiao19910803/edx,peterm-itr/edx-platform,nttks/edx-platform,jazkarta/edx-platform,caesar2164/edx-platform,torchingloom/edx-platform,CredoReference/edx-platform,dsajkl/123,edry/edx-platform,Edraak/circleci-edx-platform,shubhdev/edxOnBaadal,iivic/BoiseStateX,chauhanhardik/populo_2,raccoongang/edx-platform,y12uc231/edx-platform,nttks/jenkins-test,pabloborrego93/edx-platform,playm2mboy/edx-platform,AkA84/edx-platform,nanolearning/edx-platform,xingyepei/edx-platform,martynovp/edx-platform,sudheerchintala/LearnEraPlatForm,mitocw/edx-platform,ferabra/edx-platform,Softmotions/edx-platform,zerobatu/edx-platform,DefyVentures/edx-platform,iivic/BoiseStateX,CredoReference/edx-platform,eduNEXT/edx-platform,doismellburning/edx-platform,shubhdev/openedx,DNFcode/edx-platform,waheedahmed/edx-platform,shurihell/testasia,y12uc231/edx-platform,dsajkl/123,gymnasium/edx-platform,eestay/edx-platform,dsajkl/reqiop,raccoongang/edx-platform,alexthered/kienhoc-platform,chauhanhardik/populo,Unow/edx-platform,kursitet/edx-platform,kmoocdev/edx-platform,ahmedaljazzar/edx-platform,philanthropy-u/edx-platform,hmcmooc/muddx-platform,dcosentino/edx-platform,auferack08/edx-platform,nikolas/edx-platform,adoosii/edx-platform,ubc/edx-platform,auferack08/edx-platform,MSOpenTech/edx-platform,mushtaqak/edx-platform,eduNEXT/edx-platform,MSOpenTech/edx-platform,Edraak/edraak-platform,zubair-arbi/edx-platform,motion2015/edx-platform,vismartltd/edx-platform,carsongee/edx-platform,mjirayu/sit_academy,TeachAtTUM/edx-platform,JCBarahona/edX,rue89-tech/edx-platform,ESOedX/edx-platform,shubhdev/edx-platform,Unow/edx-platform,nanolearningllc/edx-platform-cypress-2,cpennington/edx-platform,pku9104038/edx-platform,eduNEXT/edunext-platform,shubhdev/edx-platform,philanthropy-u/edx-platform,hastexo/edx-platform,motion2015/edx-platform,jbassen/edx-platform,longmen21/edx-platform,Edraak/edraak-platform,rismalrv/edx-platform,MakeHer/edx-platform,xingyepei/edx-platform,jamesblunt/edx-platform,RPI-OPENEDX/edx-platform,zhenzhai/edx-platform,zubair-arbi/edx-platform,pepeportela/edx-platform,nagyistoce/edx-platform,benpatterson/edx-platform,vismartltd/edx-platform,Semi-global/edx-platform,jazkarta/edx-platform-for-isc,DNFcode/edx-platform,procangroup/edx-platform,ahmadio/edx-platform,naresh21/synergetics-edx-platform,IONISx/edx-platform,torchingloom/edx-platform,leansoft/edx-platform,shashank971/edx-platform,msegado/edx-platform,longmen21/edx-platform,zofuthan/edx-platform,appsembler/edx-platform,AkA84/edx-platform,IndonesiaX/edx-platform,dkarakats/edx-platform,IndonesiaX/edx-platform,DNFcode/edx-platform,eestay/edx-platform,nanolearningllc/edx-platform-cypress,pabloborrego93/edx-platform,motion2015/a3,tiagochiavericosta/edx-platform,Semi-global/edx-platform,louyihua/edx-platform,knehez/edx-platform,wwj718/edx-platform,JioEducation/edx-platform,pomegranited/edx-platform,cselis86/edx-platform,nttks/jenkins-test,mtlchun/edx,jazkarta/edx-platform-for-isc,jbzdak/edx-platform,Livit/Livit.Learn.EdX,bigdatauniversity/edx-platform,pepeportela/edx-platform,wwj718/ANALYSE,DNFcode/edx-platform,rhndg/openedx,hastexo/edx-platform
import ConfigParser from django.conf import settings + config_file = open(settings.REPO_ROOT / "docs" / "config.ini") + config = ConfigParser.ConfigParser() + config.readfp(config_file) + def doc_url(request): - config_file = open(settings.REPO_ROOT / "docs" / "config.ini") - config = ConfigParser.ConfigParser() - config.readfp(config_file) - # in the future, we will detect the locale; for now, we will # hardcode en_us, since we only have English documentation locale = "en_us" def get_doc_url(token): try: return config.get(locale, token) except ConfigParser.NoOptionError: return config.get(locale, "default") return {"doc_url": get_doc_url}
Read from doc url mapping file at load time, rather than once per request
## Code Before: import ConfigParser from django.conf import settings def doc_url(request): config_file = open(settings.REPO_ROOT / "docs" / "config.ini") config = ConfigParser.ConfigParser() config.readfp(config_file) # in the future, we will detect the locale; for now, we will # hardcode en_us, since we only have English documentation locale = "en_us" def get_doc_url(token): try: return config.get(locale, token) except ConfigParser.NoOptionError: return config.get(locale, "default") return {"doc_url": get_doc_url} ## Instruction: Read from doc url mapping file at load time, rather than once per request ## Code After: import ConfigParser from django.conf import settings config_file = open(settings.REPO_ROOT / "docs" / "config.ini") config = ConfigParser.ConfigParser() config.readfp(config_file) def doc_url(request): # in the future, we will detect the locale; for now, we will # hardcode en_us, since we only have English documentation locale = "en_us" def get_doc_url(token): try: return config.get(locale, token) except ConfigParser.NoOptionError: return config.get(locale, "default") return {"doc_url": get_doc_url}
# ... existing code ... from django.conf import settings config_file = open(settings.REPO_ROOT / "docs" / "config.ini") config = ConfigParser.ConfigParser() config.readfp(config_file) def doc_url(request): # in the future, we will detect the locale; for now, we will # hardcode en_us, since we only have English documentation # ... rest of the code ...
198f070f15a234aee75a89a8fbc6ed1c712a9d6b
probfit/py23_compat.py
probfit/py23_compat.py
import sys py_ver = sys.version_info PY2 = False PY3 = False if py_ver[0] == 2: PY2 = True else: # just in case PY4 PY3 = True if PY2: range = xrange else: range = range
import sys py_ver = sys.version_info PY2 = False PY3 = False if py_ver[0] == 2: PY2 = True else: # just in case PY4 PY3 = True if PY2: range = xrange # pylint: disable=undefined-variable else: range = range
Disable pylint warning for xrange.
Disable pylint warning for xrange. Pylint complains that xrange is an undefined variable when its run under Python 3. This is true, which is why the offending line is wrapped with an 'if PY3' clause.
Python
mit
iminuit/probfit,iminuit/probfit
import sys py_ver = sys.version_info PY2 = False PY3 = False if py_ver[0] == 2: PY2 = True else: # just in case PY4 PY3 = True if PY2: - range = xrange + range = xrange # pylint: disable=undefined-variable else: range = range
Disable pylint warning for xrange.
## Code Before: import sys py_ver = sys.version_info PY2 = False PY3 = False if py_ver[0] == 2: PY2 = True else: # just in case PY4 PY3 = True if PY2: range = xrange else: range = range ## Instruction: Disable pylint warning for xrange. ## Code After: import sys py_ver = sys.version_info PY2 = False PY3 = False if py_ver[0] == 2: PY2 = True else: # just in case PY4 PY3 = True if PY2: range = xrange # pylint: disable=undefined-variable else: range = range
// ... existing code ... if PY2: range = xrange # pylint: disable=undefined-variable else: range = range // ... rest of the code ...
17ab8c01a88bda8dba4aaa5e57c857babfeb9444
debtcollector/fixtures/disable.py
debtcollector/fixtures/disable.py
from __future__ import absolute_import import fixtures from debtcollector import _utils class DisableFixture(fixtures.Fixture): """Fixture that disables debtcollector triggered warnings. This does **not** disable warnings calls emitted by other libraries. This can be used like:: from debtcollector.fixtures import disable with disable.DisableFixture(): <some code that calls into depreciated code> """ def _setUp(self): self.addCleanup(setattr, _utils, "_enabled", True) _utils._enabled = False
import fixtures from debtcollector import _utils class DisableFixture(fixtures.Fixture): """Fixture that disables debtcollector triggered warnings. This does **not** disable warnings calls emitted by other libraries. This can be used like:: from debtcollector.fixtures import disable with disable.DisableFixture(): <some code that calls into depreciated code> """ def _setUp(self): self.addCleanup(setattr, _utils, "_enabled", True) _utils._enabled = False
Stop to use the __future__ module.
Stop to use the __future__ module. The __future__ module [1] was used in this context to ensure compatibility between python 2 and python 3. We previously dropped the support of python 2.7 [2] and now we only support python 3 so we don't need to continue to use this module and the imports listed below. Imports commonly used and their related PEPs: - `division` is related to PEP 238 [3] - `print_function` is related to PEP 3105 [4] - `unicode_literals` is related to PEP 3112 [5] - `with_statement` is related to PEP 343 [6] - `absolute_import` is related to PEP 328 [7] [1] https://docs.python.org/3/library/__future__.html [2] https://governance.openstack.org/tc/goals/selected/ussuri/drop-py27.html [3] https://www.python.org/dev/peps/pep-0238 [4] https://www.python.org/dev/peps/pep-3105 [5] https://www.python.org/dev/peps/pep-3112 [6] https://www.python.org/dev/peps/pep-0343 [7] https://www.python.org/dev/peps/pep-0328 Change-Id: I2b2f006e0ec145730bec843add4147345797b920
Python
apache-2.0
openstack/debtcollector
- - from __future__ import absolute_import import fixtures from debtcollector import _utils class DisableFixture(fixtures.Fixture): """Fixture that disables debtcollector triggered warnings. This does **not** disable warnings calls emitted by other libraries. This can be used like:: from debtcollector.fixtures import disable with disable.DisableFixture(): <some code that calls into depreciated code> """ def _setUp(self): self.addCleanup(setattr, _utils, "_enabled", True) _utils._enabled = False
Stop to use the __future__ module.
## Code Before: from __future__ import absolute_import import fixtures from debtcollector import _utils class DisableFixture(fixtures.Fixture): """Fixture that disables debtcollector triggered warnings. This does **not** disable warnings calls emitted by other libraries. This can be used like:: from debtcollector.fixtures import disable with disable.DisableFixture(): <some code that calls into depreciated code> """ def _setUp(self): self.addCleanup(setattr, _utils, "_enabled", True) _utils._enabled = False ## Instruction: Stop to use the __future__ module. ## Code After: import fixtures from debtcollector import _utils class DisableFixture(fixtures.Fixture): """Fixture that disables debtcollector triggered warnings. This does **not** disable warnings calls emitted by other libraries. This can be used like:: from debtcollector.fixtures import disable with disable.DisableFixture(): <some code that calls into depreciated code> """ def _setUp(self): self.addCleanup(setattr, _utils, "_enabled", True) _utils._enabled = False
... import fixtures ...
d120e092c2e6422e63500666947aea43891908c2
progress_bar.py
progress_bar.py
import sys import time index = 0 for url_dict in range(100): time.sleep(0.1) index += 1 percentual = "%.2f%%" % index sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index, ' ' * (100-index), percentual)) sys.stdout.flush() print("")
import sys import time import math n_messages = 650 for index, url_dict in enumerate(range(n_messages)): index += 1 time.sleep(0.01) progress_index = math.floor(index/n_messages*100) percentual = "%.2f%%" % progress_index sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index, ' ' * (100-progress_index), percentual)) sys.stdout.flush() print("")
Make it work properly with every number
Make it work properly with every number
Python
mit
victorpantoja/python-progress-bar
import sys import time + import math - index = 0 - for url_dict in range(100): - time.sleep(0.1) + n_messages = 650 + + for index, url_dict in enumerate(range(n_messages)): index += 1 + time.sleep(0.01) + + progress_index = math.floor(index/n_messages*100) - percentual = "%.2f%%" % index + percentual = "%.2f%%" % progress_index - sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index, + sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index, - ' ' * (100-index), + ' ' * (100-progress_index), - percentual)) + percentual)) sys.stdout.flush() print("")
Make it work properly with every number
## Code Before: import sys import time index = 0 for url_dict in range(100): time.sleep(0.1) index += 1 percentual = "%.2f%%" % index sys.stdout.write('\r[{0}{1}] {2}'.format('#' * index, ' ' * (100-index), percentual)) sys.stdout.flush() print("") ## Instruction: Make it work properly with every number ## Code After: import sys import time import math n_messages = 650 for index, url_dict in enumerate(range(n_messages)): index += 1 time.sleep(0.01) progress_index = math.floor(index/n_messages*100) percentual = "%.2f%%" % progress_index sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index, ' ' * (100-progress_index), percentual)) sys.stdout.flush() print("")
// ... existing code ... import sys import time import math n_messages = 650 for index, url_dict in enumerate(range(n_messages)): index += 1 time.sleep(0.01) progress_index = math.floor(index/n_messages*100) percentual = "%.2f%%" % progress_index sys.stdout.write('\r[{0}{1}] {2}'.format('#' * progress_index, ' ' * (100-progress_index), percentual)) sys.stdout.flush() // ... rest of the code ...
bccfc6d3c0035e2a5668607ebb7dd6047ee1942f
kokki/cookbooks/mdadm/recipes/default.py
kokki/cookbooks/mdadm/recipes/default.py
from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: env.cookbooks.mdadm.Array(**array) if array.get('fstype'): if array['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if array.get('mount_point'): Mount(array['mount_point'], device = array['name'], fstype = array['fstype'], options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"], action = ["mount", "enable"])
from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: fstype = array.pop('fstype', None) fsoptions = array.pop('fsoptions', None) mount_point = array.pop('mount_point', None) env.cookbooks.mdadm.Array(**array) if fstype: if fstype == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if mount_point: Mount(mount_point, device = array['name'], fstype = fstype, options = fsoptions if fsoptions is not None else ["noatime"], action = ["mount", "enable"])
Fix to mounting mdadm raid arrays
Fix to mounting mdadm raid arrays
Python
bsd-3-clause
samuel/kokki
from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: + fstype = array.pop('fstype', None) + fsoptions = array.pop('fsoptions', None) + mount_point = array.pop('mount_point', None) + env.cookbooks.mdadm.Array(**array) - if array.get('fstype'): + if fstype: - if array['fstype'] == "xfs": + if fstype == "xfs": Package("xfsprogs") - Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']), + Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) - if array.get('mount_point'): + if mount_point: - Mount(array['mount_point'], + Mount(mount_point, device = array['name'], - fstype = array['fstype'], + fstype = fstype, - options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"], + options = fsoptions if fsoptions is not None else ["noatime"], action = ["mount", "enable"])
Fix to mounting mdadm raid arrays
## Code Before: from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: env.cookbooks.mdadm.Array(**array) if array.get('fstype'): if array['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if array.get('mount_point'): Mount(array['mount_point'], device = array['name'], fstype = array['fstype'], options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"], action = ["mount", "enable"]) ## Instruction: Fix to mounting mdadm raid arrays ## Code After: from kokki import * if env.config.mdadm.arrays: Package("mdadm") Execute("mdadm-update-conf", action = "nothing", command = ("(" "echo DEVICE partitions > /etc/mdadm/mdadm.conf" "; mdadm --detail --scan >> /etc/mdadm/mdadm.conf" ")" )) for array in env.config.mdadm.arrays: fstype = array.pop('fstype', None) fsoptions = array.pop('fsoptions', None) mount_point = array.pop('mount_point', None) env.cookbooks.mdadm.Array(**array) if fstype: if fstype == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if mount_point: Mount(mount_point, device = array['name'], fstype = fstype, options = fsoptions if fsoptions is not None else ["noatime"], action = ["mount", "enable"])
... for array in env.config.mdadm.arrays: fstype = array.pop('fstype', None) fsoptions = array.pop('fsoptions', None) mount_point = array.pop('mount_point', None) env.cookbooks.mdadm.Array(**array) if fstype: if fstype == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=fstype, device=array['name']), not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name'])) if mount_point: Mount(mount_point, device = array['name'], fstype = fstype, options = fsoptions if fsoptions is not None else ["noatime"], action = ["mount", "enable"]) ...
7dd723874ac5bae83039b313abd00393636f1d80
modernrpc/tests/test_entry_points.py
modernrpc/tests/test_entry_points.py
import requests def test_forbidden_get(live_server): r = requests.get(live_server.url + '/all-rpc/') assert r.status_code == 405 r2 = requests.post(live_server.url + '/all-rpc/') assert r2.status_code == 200 def test_allowed_get(live_server): r = requests.get(live_server.url + '/all-rpc-doc/') assert r.status_code == 200 r2 = requests.post(live_server.url + '/all-rpc-doc/') assert r2.status_code == 405
import requests from django.core.exceptions import ImproperlyConfigured from pytest import raises from modernrpc.views import RPCEntryPoint def test_forbidden_get(live_server): r = requests.get(live_server.url + '/all-rpc/') assert r.status_code == 405 r2 = requests.post(live_server.url + '/all-rpc/') assert r2.status_code == 200 def test_allowed_get(live_server): r = requests.get(live_server.url + '/all-rpc-doc/') assert r.status_code == 200 r2 = requests.post(live_server.url + '/all-rpc-doc/') assert r2.status_code == 405 def test_invalid_entry_point(settings, rf): settings.MODERNRPC_HANDLERS = [] entry_point = RPCEntryPoint.as_view() with raises(ImproperlyConfigured) as e: entry_point(rf.post('xxx')) assert 'handler' in str(e.value)
Test for bad setting value
Test for bad setting value
Python
mit
alorence/django-modern-rpc,alorence/django-modern-rpc
import requests + from django.core.exceptions import ImproperlyConfigured + from pytest import raises + + from modernrpc.views import RPCEntryPoint def test_forbidden_get(live_server): r = requests.get(live_server.url + '/all-rpc/') assert r.status_code == 405 r2 = requests.post(live_server.url + '/all-rpc/') assert r2.status_code == 200 def test_allowed_get(live_server): r = requests.get(live_server.url + '/all-rpc-doc/') assert r.status_code == 200 r2 = requests.post(live_server.url + '/all-rpc-doc/') assert r2.status_code == 405 + + def test_invalid_entry_point(settings, rf): + settings.MODERNRPC_HANDLERS = [] + + entry_point = RPCEntryPoint.as_view() + with raises(ImproperlyConfigured) as e: + entry_point(rf.post('xxx')) + + assert 'handler' in str(e.value) +
Test for bad setting value
## Code Before: import requests def test_forbidden_get(live_server): r = requests.get(live_server.url + '/all-rpc/') assert r.status_code == 405 r2 = requests.post(live_server.url + '/all-rpc/') assert r2.status_code == 200 def test_allowed_get(live_server): r = requests.get(live_server.url + '/all-rpc-doc/') assert r.status_code == 200 r2 = requests.post(live_server.url + '/all-rpc-doc/') assert r2.status_code == 405 ## Instruction: Test for bad setting value ## Code After: import requests from django.core.exceptions import ImproperlyConfigured from pytest import raises from modernrpc.views import RPCEntryPoint def test_forbidden_get(live_server): r = requests.get(live_server.url + '/all-rpc/') assert r.status_code == 405 r2 = requests.post(live_server.url + '/all-rpc/') assert r2.status_code == 200 def test_allowed_get(live_server): r = requests.get(live_server.url + '/all-rpc-doc/') assert r.status_code == 200 r2 = requests.post(live_server.url + '/all-rpc-doc/') assert r2.status_code == 405 def test_invalid_entry_point(settings, rf): settings.MODERNRPC_HANDLERS = [] entry_point = RPCEntryPoint.as_view() with raises(ImproperlyConfigured) as e: entry_point(rf.post('xxx')) assert 'handler' in str(e.value)
# ... existing code ... import requests from django.core.exceptions import ImproperlyConfigured from pytest import raises from modernrpc.views import RPCEntryPoint # ... modified code ... r2 = requests.post(live_server.url + '/all-rpc-doc/') assert r2.status_code == 405 def test_invalid_entry_point(settings, rf): settings.MODERNRPC_HANDLERS = [] entry_point = RPCEntryPoint.as_view() with raises(ImproperlyConfigured) as e: entry_point(rf.post('xxx')) assert 'handler' in str(e.value) # ... rest of the code ...
e893a860f4a8ad9682f400507948ee20fce1c328
healthcheck/contrib/django/status_endpoint/views.py
healthcheck/contrib/django/status_endpoint/views.py
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse, HttpResponseServerError from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr( settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append( FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if not ok: return HttpResponseServerError((json.dumps(details))) return HttpResponse(json.dumps(details))
import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if not ok: return JsonResponseServerError(json.dumps(details)) return JsonResponse(details)
Fix content_type for JSON responses
Fix content_type for JSON responses
Python
mit
yola/healthcheck
import json from django.conf import settings from django.views.decorators.http import require_http_methods - from django.http import HttpResponse, HttpResponseServerError + from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) + + + class JsonResponse(HttpResponse): + def __init__(self, data, **kwargs): + kwargs.setdefault('content_type', 'application/json') + data = json.dumps(data) + super(JsonResponse, self).__init__(content=data, **kwargs) + + + class JsonResponseServerError(JsonResponse): + status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) + files_to_check = getattr(settings, 'STATUS_CHECK_FILES') - files_to_check = getattr( - settings, 'STATUS_CHECK_FILES') if files_to_check: - checks.append( - FilesDontExistHealthCheck( + checks.append(FilesDontExistHealthCheck( - files_to_check, check_id="quiesce file doesn't exist")) + files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if not ok: - return HttpResponseServerError((json.dumps(details))) + return JsonResponseServerError(json.dumps(details)) - return HttpResponse(json.dumps(details)) + return JsonResponse(details)
Fix content_type for JSON responses
## Code Before: import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse, HttpResponseServerError from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr( settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append( FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if not ok: return HttpResponseServerError((json.dumps(details))) return HttpResponse(json.dumps(details)) ## Instruction: Fix content_type for JSON responses ## Code After: import json from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 @require_http_methods(['GET']) def status(request): checks = [] if getattr(settings, 'STATUS_CHECK_DBS', True): checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() if not ok: return JsonResponseServerError(json.dumps(details)) return JsonResponse(details)
... from django.conf import settings from django.views.decorators.http import require_http_methods from django.http import HttpResponse from healthcheck.healthcheck import ( DjangoDBsHealthCheck, FilesDontExistHealthCheck, HealthChecker) class JsonResponse(HttpResponse): def __init__(self, data, **kwargs): kwargs.setdefault('content_type', 'application/json') data = json.dumps(data) super(JsonResponse, self).__init__(content=data, **kwargs) class JsonResponseServerError(JsonResponse): status_code = 500 ... checks.append(DjangoDBsHealthCheck()) files_to_check = getattr(settings, 'STATUS_CHECK_FILES') if files_to_check: checks.append(FilesDontExistHealthCheck( files_to_check, check_id="quiesce file doesn't exist")) ok, details = HealthChecker(checks)() ... if not ok: return JsonResponseServerError(json.dumps(details)) return JsonResponse(details) ...
7d2277685a125e4ee2b57ed7782bcae62f64464b
matrix/example.py
matrix/example.py
class Matrix(object): def __init__(self, s): self.rows = [[int(n) for n in row.split()] for row in s.split('\n')] @property def columns(self): return map(list, zip(*self.rows))
class Matrix(object): def __init__(self, s): self.rows = [[int(n) for n in row.split()] for row in s.split('\n')] @property def columns(self): return [list(tup) for tup in zip(*self.rows)]
Make matrix exercise compatible with Python3
Make matrix exercise compatible with Python3
Python
mit
exercism/python,pombredanne/xpython,outkaj/xpython,behrtam/xpython,smalley/python,orozcoadrian/xpython,orozcoadrian/xpython,exercism/xpython,ZacharyRSmith/xpython,de2Zotjes/xpython,oalbe/xpython,jmluy/xpython,N-Parsons/exercism-python,pheanex/xpython,behrtam/xpython,exercism/python,pombredanne/xpython,wobh/xpython,jmluy/xpython,smalley/python,Peque/xpython,Peque/xpython,rootulp/xpython,exercism/xpython,rootulp/xpython,de2Zotjes/xpython,wobh/xpython,mweb/python,pheanex/xpython,N-Parsons/exercism-python,oalbe/xpython,ZacharyRSmith/xpython,mweb/python,outkaj/xpython
class Matrix(object): def __init__(self, s): self.rows = [[int(n) for n in row.split()] for row in s.split('\n')] @property def columns(self): - return map(list, zip(*self.rows)) + return [list(tup) for tup in zip(*self.rows)]
Make matrix exercise compatible with Python3
## Code Before: class Matrix(object): def __init__(self, s): self.rows = [[int(n) for n in row.split()] for row in s.split('\n')] @property def columns(self): return map(list, zip(*self.rows)) ## Instruction: Make matrix exercise compatible with Python3 ## Code After: class Matrix(object): def __init__(self, s): self.rows = [[int(n) for n in row.split()] for row in s.split('\n')] @property def columns(self): return [list(tup) for tup in zip(*self.rows)]
... @property def columns(self): return [list(tup) for tup in zip(*self.rows)] ...
2752c9880934aed1f02ab5e9cc111b07cb449c46
async_messages/middleware.py
async_messages/middleware.py
from django.contrib import messages from async_messages import get_message class AsyncMiddleware(object): def process_request(self, request): # Check for message for this user and, if it exists, # call the messages API with it if not request.user.is_authenticated(): return msg, level = get_message(request.user) if msg: messages.add_message(request, level, msg)
from django.contrib import messages from async_messages import get_message class AsyncMiddleware(object): def process_response(self, request, response): # Check for message for this user and, if it exists, # call the messages API with it if not request.user.is_authenticated(): return msg, level = get_message(request.user) if msg: messages.add_message(request, level, msg)
Add the message during the processing of the response.
Add the message during the processing of the response.
Python
mit
codeinthehole/django-async-messages
from django.contrib import messages from async_messages import get_message class AsyncMiddleware(object): - def process_request(self, request): + def process_response(self, request, response): # Check for message for this user and, if it exists, # call the messages API with it if not request.user.is_authenticated(): return msg, level = get_message(request.user) if msg: messages.add_message(request, level, msg)
Add the message during the processing of the response.
## Code Before: from django.contrib import messages from async_messages import get_message class AsyncMiddleware(object): def process_request(self, request): # Check for message for this user and, if it exists, # call the messages API with it if not request.user.is_authenticated(): return msg, level = get_message(request.user) if msg: messages.add_message(request, level, msg) ## Instruction: Add the message during the processing of the response. ## Code After: from django.contrib import messages from async_messages import get_message class AsyncMiddleware(object): def process_response(self, request, response): # Check for message for this user and, if it exists, # call the messages API with it if not request.user.is_authenticated(): return msg, level = get_message(request.user) if msg: messages.add_message(request, level, msg)
// ... existing code ... class AsyncMiddleware(object): def process_response(self, request, response): # Check for message for this user and, if it exists, # call the messages API with it // ... rest of the code ...
a0f31dc83ce36823022b5e26c85ad03fe639e79f
src/main/python/alppaca/compat.py
src/main/python/alppaca/compat.py
from __future__ import print_function, absolute_import, unicode_literals, division """ Compatability module for different Python versions. """ try: import unittest2 as unittest except ImportError: # pragma: no cover import unittest try: from ordereddict import OrderedDict except ImportError: # pragma: no cover from collections import OrderedDict
""" Compatability module for different Python versions. """ from __future__ import print_function, absolute_import, unicode_literals, division try: import unittest2 as unittest except ImportError: # pragma: no cover import unittest try: from ordereddict import OrderedDict except ImportError: # pragma: no cover from collections import OrderedDict
Move string above the import so it becomes a docstring
Move string above the import so it becomes a docstring
Python
apache-2.0
ImmobilienScout24/afp-alppaca,ImmobilienScout24/afp-alppaca,ImmobilienScout24/alppaca,ImmobilienScout24/alppaca
+ """ Compatability module for different Python versions. """ + from __future__ import print_function, absolute_import, unicode_literals, division - - """ Compatability module for different Python versions. """ try: import unittest2 as unittest except ImportError: # pragma: no cover import unittest try: from ordereddict import OrderedDict except ImportError: # pragma: no cover from collections import OrderedDict
Move string above the import so it becomes a docstring
## Code Before: from __future__ import print_function, absolute_import, unicode_literals, division """ Compatability module for different Python versions. """ try: import unittest2 as unittest except ImportError: # pragma: no cover import unittest try: from ordereddict import OrderedDict except ImportError: # pragma: no cover from collections import OrderedDict ## Instruction: Move string above the import so it becomes a docstring ## Code After: """ Compatability module for different Python versions. """ from __future__ import print_function, absolute_import, unicode_literals, division try: import unittest2 as unittest except ImportError: # pragma: no cover import unittest try: from ordereddict import OrderedDict except ImportError: # pragma: no cover from collections import OrderedDict
... """ Compatability module for different Python versions. """ from __future__ import print_function, absolute_import, unicode_literals, division try: ...
7b3faffb655a3d4b44b52bd907b7e17f952a9f43
src/pve_exporter/cli.py
src/pve_exporter/cli.py
import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [port]") sys.exit(1) if len(args) >= 2: config = args[1] else: config = "pve.yml" if len(args) >= 3: port = int(args[2]) else: port = 9221 start_http_server(config, port)
import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port)
Add argparse and provide usage/command line help
Add argparse and provide usage/command line help
Python
apache-2.0
znerol/prometheus-pve-exporter
import sys + from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ - if args is None: - args = sys.argv + parser = ArgumentParser() + parser.add_argument('config', nargs='?', default='pve.yml', + help='Path to configuration file (pve.yml)') + parser.add_argument('port', nargs='?', type=int, default='9221', + help='Port on which the exporter is listening (9221)') + params = parser.parse_args(args if args is None else sys.argv[1:]) - if len(args) not in [1, 2, 3]: - print("Usage: pve_exporter [config_file] [port]") - sys.exit(1) + start_http_server(params.config, params.port) - if len(args) >= 2: - config = args[1] - else: - config = "pve.yml" - if len(args) >= 3: - port = int(args[2]) - else: - port = 9221 - - start_http_server(config, port) -
Add argparse and provide usage/command line help
## Code Before: import sys from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ if args is None: args = sys.argv if len(args) not in [1, 2, 3]: print("Usage: pve_exporter [config_file] [port]") sys.exit(1) if len(args) >= 2: config = args[1] else: config = "pve.yml" if len(args) >= 3: port = int(args[2]) else: port = 9221 start_http_server(config, port) ## Instruction: Add argparse and provide usage/command line help ## Code After: import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port)
# ... existing code ... import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server # ... modified code ... """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', help='Path to configuration file (pve.yml)') parser.add_argument('port', nargs='?', type=int, default='9221', help='Port on which the exporter is listening (9221)') params = parser.parse_args(args if args is None else sys.argv[1:]) start_http_server(params.config, params.port) # ... rest of the code ...
a7058352df6cd8c0e411df5e1b0948729f8ffe60
dezede/__init__.py
dezede/__init__.py
from __future__ import unicode_literals __version__ = 1, 8, 3 get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède'
from __future__ import unicode_literals __version__ = 2, 0, 0, 'pre' get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède'
Change le numéro de version pour 2.0.0.pre
Change le numéro de version pour 2.0.0.pre
Python
bsd-3-clause
dezede/dezede,dezede/dezede,dezede/dezede,dezede/dezede
from __future__ import unicode_literals - __version__ = 1, 8, 3 + __version__ = 2, 0, 0, 'pre' get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède'
Change le numéro de version pour 2.0.0.pre
## Code Before: from __future__ import unicode_literals __version__ = 1, 8, 3 get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède' ## Instruction: Change le numéro de version pour 2.0.0.pre ## Code After: from __future__ import unicode_literals __version__ = 2, 0, 0, 'pre' get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède'
// ... existing code ... __version__ = 2, 0, 0, 'pre' get_version = lambda: '.'.join(str(i) for i in __version__) __verbose_name__ = 'Dezède' // ... rest of the code ...
9185d882dc5fc7131b90d3b93dff8b6603538a3d
app/cogs/twitch_emotes.py
app/cogs/twitch_emotes.py
from io import BytesIO import requests from discord.ext import commands from discord.ext.commands import Bot TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json' class TwitchEmotes: def __init__(self, bot: Bot): self.bot = bot r = requests.get(TWITCH_EMOTES_API) emote_data = r.json() emote_template = emote_data['template']['small'] emote_ids = {name: info['image_id'] for name, info in emote_data['emotes'].items()} emote_cache = {} @bot.listen('on_message') async def respond(message): if message.author == bot.user: return text = message.content if text in emote_ids: if text not in emote_cache: url = emote_template.replace('{image_id}', str(emote_ids[text])) emote_img = requests.get(url).content emote_cache[text] = emote_img data = BytesIO(emote_cache[text]) filename = '%s.png' % text await bot.send_file(message.channel, data, filename=filename) def setup(bot: Bot): bot.add_cog(TwitchEmotes(bot))
from io import BytesIO import logging import requests from discord.ext import commands from discord.ext.commands import Bot TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json' logger = logging.getLogger(__name__) class TwitchEmotes: def __init__(self, bot: Bot): self.bot = bot r = requests.get(TWITCH_EMOTES_API) emote_data = r.json() emote_template = emote_data['template']['small'] emote_ids = {name: info['image_id'] for name, info in emote_data['emotes'].items()} emote_cache = {} logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids)) logger.info('Using template: %s' % emote_template) @bot.listen('on_message') async def respond(message): if message.author == bot.user: return text = message.content if text in emote_ids: if text not in emote_cache: url = emote_template.replace('{image_id}', str(emote_ids[text])) logger.info('Fetching emote %s from %s' % (text, url)) emote_img = requests.get(url).content emote_cache[text] = emote_img data = BytesIO(emote_cache[text]) filename = '%s.png' % text await bot.send_file(message.channel, data, filename=filename) def setup(bot: Bot): bot.add_cog(TwitchEmotes(bot))
Add logging to Twitch emotes module
Add logging to Twitch emotes module
Python
mit
andrewlin16/duckbot,andrewlin16/duckbot
from io import BytesIO + import logging import requests from discord.ext import commands from discord.ext.commands import Bot TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json' + + + logger = logging.getLogger(__name__) class TwitchEmotes: def __init__(self, bot: Bot): self.bot = bot r = requests.get(TWITCH_EMOTES_API) emote_data = r.json() emote_template = emote_data['template']['small'] emote_ids = {name: info['image_id'] for name, info in emote_data['emotes'].items()} emote_cache = {} + logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids)) + logger.info('Using template: %s' % emote_template) @bot.listen('on_message') async def respond(message): if message.author == bot.user: return text = message.content if text in emote_ids: if text not in emote_cache: url = emote_template.replace('{image_id}', str(emote_ids[text])) + logger.info('Fetching emote %s from %s' % (text, url)) emote_img = requests.get(url).content emote_cache[text] = emote_img data = BytesIO(emote_cache[text]) filename = '%s.png' % text await bot.send_file(message.channel, data, filename=filename) def setup(bot: Bot): bot.add_cog(TwitchEmotes(bot))
Add logging to Twitch emotes module
## Code Before: from io import BytesIO import requests from discord.ext import commands from discord.ext.commands import Bot TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json' class TwitchEmotes: def __init__(self, bot: Bot): self.bot = bot r = requests.get(TWITCH_EMOTES_API) emote_data = r.json() emote_template = emote_data['template']['small'] emote_ids = {name: info['image_id'] for name, info in emote_data['emotes'].items()} emote_cache = {} @bot.listen('on_message') async def respond(message): if message.author == bot.user: return text = message.content if text in emote_ids: if text not in emote_cache: url = emote_template.replace('{image_id}', str(emote_ids[text])) emote_img = requests.get(url).content emote_cache[text] = emote_img data = BytesIO(emote_cache[text]) filename = '%s.png' % text await bot.send_file(message.channel, data, filename=filename) def setup(bot: Bot): bot.add_cog(TwitchEmotes(bot)) ## Instruction: Add logging to Twitch emotes module ## Code After: from io import BytesIO import logging import requests from discord.ext import commands from discord.ext.commands import Bot TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json' logger = logging.getLogger(__name__) class TwitchEmotes: def __init__(self, bot: Bot): self.bot = bot r = requests.get(TWITCH_EMOTES_API) emote_data = r.json() emote_template = emote_data['template']['small'] emote_ids = {name: info['image_id'] for name, info in emote_data['emotes'].items()} emote_cache = {} logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids)) logger.info('Using template: %s' % emote_template) @bot.listen('on_message') async def respond(message): if message.author == bot.user: return text = message.content if text in emote_ids: if text not in emote_cache: url = emote_template.replace('{image_id}', str(emote_ids[text])) logger.info('Fetching emote %s from %s' % (text, url)) emote_img = requests.get(url).content emote_cache[text] = emote_img data = BytesIO(emote_cache[text]) filename = '%s.png' % text await bot.send_file(message.channel, data, filename=filename) def setup(bot: Bot): bot.add_cog(TwitchEmotes(bot))
... from io import BytesIO import logging import requests ... TWITCH_EMOTES_API = 'https://twitchemotes.com/api_cache/v2/global.json' logger = logging.getLogger(__name__) ... emote_data['emotes'].items()} emote_cache = {} logger.info('Got %d emotes from Twitchemotes.com API' % len(emote_ids)) logger.info('Using template: %s' % emote_template) @bot.listen('on_message') ... url = emote_template.replace('{image_id}', str(emote_ids[text])) logger.info('Fetching emote %s from %s' % (text, url)) emote_img = requests.get(url).content ...
cfb9838349a076e8fa3afe9a69db74581b13d296
labsys/auth/decorators.py
labsys/auth/decorators.py
from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) and \ not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f)
from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f)
Remove test condition for permissions
:bug: Remove test condition for permissions Otherwise I would not be able to test them properly
Python
mit
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): - if not current_user.can(permission) and \ + if not current_user.can(permission): - not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): - return permission_required(Permission.ADMINISTER) (f) + return permission_required(Permission.ADMINISTER)(f)
Remove test condition for permissions
## Code Before: from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission) and \ not current_app.config['TESTING'] == True: abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER) (f) ## Instruction: Remove test condition for permissions ## Code After: from functools import wraps from flask import abort, current_app from flask_login import current_user from labsys.auth.models import Permission def permission_required(permission): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) return decorated_function return decorator def admin_required(f): return permission_required(Permission.ADMINISTER)(f)
... @wraps(f) def decorated_function(*args, **kwargs): if not current_user.can(permission): abort(403) return f(*args, **kwargs) ... def admin_required(f): return permission_required(Permission.ADMINISTER)(f) ...
81a0239812d01e9e876989d2334afe746e09f5da
chartflo/tests.py
chartflo/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from .views import ChartsView # Create your tests here. class TestVegaLiteChartsView(TestCase): def setUpTestCase(self): self.chart_view = ChartsView() # Set Vega Lite as template engine self.chart_view.engine = "vegalite" def test_vega_lite_template(self): # URL for Vega Lite chart URL vega_lite_template_url = "chartflo/vegalite/chart.html" # Get chart view template URL chart_view_template_url = self.chart_view._get_template_url() # Make sure Chart View URL matches Vega Lite chart URL self.assertEqual(chart_view_template_url, vega_lite_template_url)
Add Vega Lite template test
Add Vega Lite template test
Python
mit
synw/django-chartflo,synw/django-chartflo,synw/django-chartflo
from django.test import TestCase + from .views import ChartsView # Create your tests here. + class TestVegaLiteChartsView(TestCase): + def setUpTestCase(self): + self.chart_view = ChartsView() + # Set Vega Lite as template engine + self.chart_view.engine = "vegalite" + + def test_vega_lite_template(self): + # URL for Vega Lite chart URL + vega_lite_template_url = "chartflo/vegalite/chart.html" + + # Get chart view template URL + chart_view_template_url = self.chart_view._get_template_url() + + # Make sure Chart View URL matches Vega Lite chart URL + self.assertEqual(chart_view_template_url, vega_lite_template_url) +
Add Vega Lite template test
## Code Before: from django.test import TestCase # Create your tests here. ## Instruction: Add Vega Lite template test ## Code After: from django.test import TestCase from .views import ChartsView # Create your tests here. class TestVegaLiteChartsView(TestCase): def setUpTestCase(self): self.chart_view = ChartsView() # Set Vega Lite as template engine self.chart_view.engine = "vegalite" def test_vega_lite_template(self): # URL for Vega Lite chart URL vega_lite_template_url = "chartflo/vegalite/chart.html" # Get chart view template URL chart_view_template_url = self.chart_view._get_template_url() # Make sure Chart View URL matches Vega Lite chart URL self.assertEqual(chart_view_template_url, vega_lite_template_url)
# ... existing code ... from django.test import TestCase from .views import ChartsView # Create your tests here. class TestVegaLiteChartsView(TestCase): def setUpTestCase(self): self.chart_view = ChartsView() # Set Vega Lite as template engine self.chart_view.engine = "vegalite" def test_vega_lite_template(self): # URL for Vega Lite chart URL vega_lite_template_url = "chartflo/vegalite/chart.html" # Get chart view template URL chart_view_template_url = self.chart_view._get_template_url() # Make sure Chart View URL matches Vega Lite chart URL self.assertEqual(chart_view_template_url, vega_lite_template_url) # ... rest of the code ...
b702569c800953eb3476c927fbc1085e67c88dbd
ghettoq/messaging.py
ghettoq/messaging.py
from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queues = map(self.backend.Queue, queues) self.cycle = cycle(self.queues) def get(self): while True: try: return self.cycle.next().get() except QueueEmpty: pass
from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queue_names = queues self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) self.all = frozenset(self.queue_names) def get(self): tried = set() while True: queue = self.cycle.next() try: return queue.get() except QueueEmpty: tried.add(queue) if tried == self.all: raise
Raise QueueEmpty when all queues has been tried.
QueueSet: Raise QueueEmpty when all queues has been tried.
Python
bsd-3-clause
ask/ghettoq
from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend + self.queue_names = queues - self.queues = map(self.backend.Queue, queues) + self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) + self.all = frozenset(self.queue_names) def get(self): + tried = set() + while True: + queue = self.cycle.next() try: - return self.cycle.next().get() + return queue.get() except QueueEmpty: + tried.add(queue) + if tried == self.all: - pass + raise
Raise QueueEmpty when all queues has been tried.
## Code Before: from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queues = map(self.backend.Queue, queues) self.cycle = cycle(self.queues) def get(self): while True: try: return self.cycle.next().get() except QueueEmpty: pass ## Instruction: Raise QueueEmpty when all queues has been tried. ## Code After: from Queue import Empty from itertools import cycle class Queue(object): def __init__(self, backend, name): self.name = name self.backend = backend def put(self, payload): self.backend.put(self.name, payload) def get(self): payload = self.backend.get(self.name) if payload is not None: return payload raise Empty class QueueSet(object): def __init__(self, backend, queues): self.backend = backend self.queue_names = queues self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) self.all = frozenset(self.queue_names) def get(self): tried = set() while True: queue = self.cycle.next() try: return queue.get() except QueueEmpty: tried.add(queue) if tried == self.all: raise
# ... existing code ... def __init__(self, backend, queues): self.backend = backend self.queue_names = queues self.queues = map(self.backend.Queue, self.queue_names) self.cycle = cycle(self.queues) self.all = frozenset(self.queue_names) def get(self): tried = set() while True: queue = self.cycle.next() try: return queue.get() except QueueEmpty: tried.add(queue) if tried == self.all: raise # ... rest of the code ...
8fd65190a2a68a7afeab91b0a02c83309f72ccd6
tests/test_testing.py
tests/test_testing.py
import greenado from greenado.testing import gen_test from tornado.testing import AsyncTestCase from tornado import gen @gen.coroutine def coroutine(): raise gen.Return(1234) class GreenadoTests(AsyncTestCase): @gen_test def test_without_timeout(self): assert greenado.gyield(coroutine()) == 1234 @gen_test(timeout=5) def test_with_timeout(self): assert greenado.gyield(coroutine()) == 1234
import greenado from greenado.testing import gen_test from tornado.testing import AsyncTestCase from tornado import gen @gen.coroutine def coroutine(): raise gen.Return(1234) class GreenadoTests(AsyncTestCase): @gen_test def test_without_timeout1(self): assert greenado.gyield(coroutine()) == 1234 @gen_test @greenado.generator def test_without_timeout2(self): assert (yield coroutine()) == 1234 @gen_test(timeout=5) def test_with_timeout1(self): assert greenado.gyield(coroutine()) == 1234 @gen_test(timeout=5) @greenado.generator def test_with_timeout2(self): assert (yield coroutine()) == 1234
Add tests to gen_test for generator, seems to work
Add tests to gen_test for generator, seems to work
Python
apache-2.0
virtuald/greenado,virtuald/greenado
import greenado from greenado.testing import gen_test from tornado.testing import AsyncTestCase from tornado import gen @gen.coroutine def coroutine(): raise gen.Return(1234) class GreenadoTests(AsyncTestCase): @gen_test - def test_without_timeout(self): + def test_without_timeout1(self): assert greenado.gyield(coroutine()) == 1234 + + @gen_test + @greenado.generator + def test_without_timeout2(self): + assert (yield coroutine()) == 1234 @gen_test(timeout=5) - def test_with_timeout(self): + def test_with_timeout1(self): assert greenado.gyield(coroutine()) == 1234 + + @gen_test(timeout=5) + @greenado.generator + def test_with_timeout2(self): + assert (yield coroutine()) == 1234
Add tests to gen_test for generator, seems to work
## Code Before: import greenado from greenado.testing import gen_test from tornado.testing import AsyncTestCase from tornado import gen @gen.coroutine def coroutine(): raise gen.Return(1234) class GreenadoTests(AsyncTestCase): @gen_test def test_without_timeout(self): assert greenado.gyield(coroutine()) == 1234 @gen_test(timeout=5) def test_with_timeout(self): assert greenado.gyield(coroutine()) == 1234 ## Instruction: Add tests to gen_test for generator, seems to work ## Code After: import greenado from greenado.testing import gen_test from tornado.testing import AsyncTestCase from tornado import gen @gen.coroutine def coroutine(): raise gen.Return(1234) class GreenadoTests(AsyncTestCase): @gen_test def test_without_timeout1(self): assert greenado.gyield(coroutine()) == 1234 @gen_test @greenado.generator def test_without_timeout2(self): assert (yield coroutine()) == 1234 @gen_test(timeout=5) def test_with_timeout1(self): assert greenado.gyield(coroutine()) == 1234 @gen_test(timeout=5) @greenado.generator def test_with_timeout2(self): assert (yield coroutine()) == 1234
// ... existing code ... @gen_test def test_without_timeout1(self): assert greenado.gyield(coroutine()) == 1234 @gen_test @greenado.generator def test_without_timeout2(self): assert (yield coroutine()) == 1234 @gen_test(timeout=5) def test_with_timeout1(self): assert greenado.gyield(coroutine()) == 1234 @gen_test(timeout=5) @greenado.generator def test_with_timeout2(self): assert (yield coroutine()) == 1234 // ... rest of the code ...
56b5b4d49973702bcb95bb36dcd1e35f40b57a1d
hyper/http20/exceptions.py
hyper/http20/exceptions.py
class HTTP20Error(Exception): """ The base class for all of ``hyper``'s HTTP/2-related exceptions. """ pass class HPACKEncodingError(HTTP20Error): """ An error has been encountered while performing HPACK encoding. """ pass class HPACKDecodingError(HTTP20Error): """ An error has been encountered while performing HPACK decoding. """ pass class ConnectionError(HTTP20Error): """ The remote party signalled an error affecting the entire HTTP/2 connection, and the connection has been closed. """ pass class ProtocolError(HTTP20Error): """ The remote party violated the HTTP/2 protocol. """ pass
class HTTP20Error(Exception): """ The base class for all of ``hyper``'s HTTP/2-related exceptions. """ pass class HPACKEncodingError(HTTP20Error): """ An error has been encountered while performing HPACK encoding. """ pass class HPACKDecodingError(HTTP20Error): """ An error has been encountered while performing HPACK decoding. """ pass class ConnectionError(HTTP20Error): """ The remote party signalled an error affecting the entire HTTP/2 connection, and the connection has been closed. """ pass class ProtocolError(HTTP20Error): """ The remote party violated the HTTP/2 protocol. """ pass class StreamResetError(HTTP20Error): """ A stream was forcefully reset by the remote party. """ pass
Add exception for streams forcefully reset
Add exception for streams forcefully reset
Python
mit
Lukasa/hyper,plucury/hyper,fredthomsen/hyper,irvind/hyper,fredthomsen/hyper,lawnmowerlatte/hyper,lawnmowerlatte/hyper,Lukasa/hyper,plucury/hyper,irvind/hyper
class HTTP20Error(Exception): """ The base class for all of ``hyper``'s HTTP/2-related exceptions. """ pass class HPACKEncodingError(HTTP20Error): """ An error has been encountered while performing HPACK encoding. """ pass class HPACKDecodingError(HTTP20Error): """ An error has been encountered while performing HPACK decoding. """ pass class ConnectionError(HTTP20Error): """ The remote party signalled an error affecting the entire HTTP/2 connection, and the connection has been closed. """ pass class ProtocolError(HTTP20Error): """ The remote party violated the HTTP/2 protocol. """ pass + + class StreamResetError(HTTP20Error): + """ + A stream was forcefully reset by the remote party. + """ + pass +
Add exception for streams forcefully reset
## Code Before: class HTTP20Error(Exception): """ The base class for all of ``hyper``'s HTTP/2-related exceptions. """ pass class HPACKEncodingError(HTTP20Error): """ An error has been encountered while performing HPACK encoding. """ pass class HPACKDecodingError(HTTP20Error): """ An error has been encountered while performing HPACK decoding. """ pass class ConnectionError(HTTP20Error): """ The remote party signalled an error affecting the entire HTTP/2 connection, and the connection has been closed. """ pass class ProtocolError(HTTP20Error): """ The remote party violated the HTTP/2 protocol. """ pass ## Instruction: Add exception for streams forcefully reset ## Code After: class HTTP20Error(Exception): """ The base class for all of ``hyper``'s HTTP/2-related exceptions. """ pass class HPACKEncodingError(HTTP20Error): """ An error has been encountered while performing HPACK encoding. """ pass class HPACKDecodingError(HTTP20Error): """ An error has been encountered while performing HPACK decoding. """ pass class ConnectionError(HTTP20Error): """ The remote party signalled an error affecting the entire HTTP/2 connection, and the connection has been closed. """ pass class ProtocolError(HTTP20Error): """ The remote party violated the HTTP/2 protocol. """ pass class StreamResetError(HTTP20Error): """ A stream was forcefully reset by the remote party. """ pass
# ... existing code ... """ pass class StreamResetError(HTTP20Error): """ A stream was forcefully reset by the remote party. """ pass # ... rest of the code ...
8c1f303d4cc04c95170dea268ab836a23d626064
thezombies/management/commands/crawl_agency_datasets.py
thezombies/management/commands/crawl_agency_datasets.py
from django.core.management.base import BaseCommand from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background""" args = '<agency_id ...>' def handle(self, *args, **options): if len(args) > 0: agency_id = args[0] if agency_id: task = crawl_agency_datasets.delay(agency_id) self.stdout.write(u'Running task with id {0}'.format(task.id)) self.stdout.write(u'This can take many minutes...') else: self.stderr.write(u"Didn't get an agency_id!")
from django.core.management.base import BaseCommand from thezombies.models import Agency from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background""" args = '<agency_id ...>' def handle(self, *args, **options): if len(args) > 0: agency_id = args[0] if agency_id: task = crawl_agency_datasets.delay(agency_id) self.stdout.write(u'Running task with id {0}'.format(task.id)) self.stdout.write(u'This can take many minutes...') else: self.stderr.write(u"Didn't get an agency_id!") else: self.stdout.write(u'Please provide an agency id:\n') agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()]) self.stdout.write(agency_list) self.stdout.write(u'\n')
Add message for when command is not supplied any arguments.
Add message for when command is not supplied any arguments.
Python
bsd-3-clause
sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies
from django.core.management.base import BaseCommand + from thezombies.models import Agency from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background""" args = '<agency_id ...>' def handle(self, *args, **options): if len(args) > 0: agency_id = args[0] if agency_id: task = crawl_agency_datasets.delay(agency_id) self.stdout.write(u'Running task with id {0}'.format(task.id)) self.stdout.write(u'This can take many minutes...') else: self.stderr.write(u"Didn't get an agency_id!") + else: + self.stdout.write(u'Please provide an agency id:\n') + agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()]) + self.stdout.write(agency_list) + self.stdout.write(u'\n')
Add message for when command is not supplied any arguments.
## Code Before: from django.core.management.base import BaseCommand from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background""" args = '<agency_id ...>' def handle(self, *args, **options): if len(args) > 0: agency_id = args[0] if agency_id: task = crawl_agency_datasets.delay(agency_id) self.stdout.write(u'Running task with id {0}'.format(task.id)) self.stdout.write(u'This can take many minutes...') else: self.stderr.write(u"Didn't get an agency_id!") ## Instruction: Add message for when command is not supplied any arguments. ## Code After: from django.core.management.base import BaseCommand from thezombies.models import Agency from thezombies.tasks.main import crawl_agency_datasets class Command(BaseCommand): """Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background""" args = '<agency_id ...>' def handle(self, *args, **options): if len(args) > 0: agency_id = args[0] if agency_id: task = crawl_agency_datasets.delay(agency_id) self.stdout.write(u'Running task with id {0}'.format(task.id)) self.stdout.write(u'This can take many minutes...') else: self.stderr.write(u"Didn't get an agency_id!") else: self.stdout.write(u'Please provide an agency id:\n') agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()]) self.stdout.write(agency_list) self.stdout.write(u'\n')
# ... existing code ... from django.core.management.base import BaseCommand from thezombies.models import Agency from thezombies.tasks.main import crawl_agency_datasets # ... modified code ... else: self.stderr.write(u"Didn't get an agency_id!") else: self.stdout.write(u'Please provide an agency id:\n') agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()]) self.stdout.write(agency_list) self.stdout.write(u'\n') # ... rest of the code ...
852ce5cee8171fdf4a33f3267de34042cb066bf3
tests/routine/test_config.py
tests/routine/test_config.py
import unittest from performance.routine import Config from performance.web import Request class ConfigTestCase(unittest.TestCase): def setUp(self): self.host = 'http://www.google.com' def test_init(self): config = Config(host=self.host) self.assertEqual(self.host, config.host) self.assertEqual([], config.requests) def test_add_request(self): config = Config(host=self.host) requestA = Request(url='/', type=Request.GET) requestB = Request(url='/about', type=Request.POST) config.add_request(requestA) config.add_request(requestB) self.assertEqual([requestA, requestB], config.requests) with self.assertRaises(TypeError) as error: config.add_request('no_request_type') self.assertEqual('No performance.web.Request object', error.exception.__str__())
import unittest from performance.routine import Config from performance.web import Request class ConfigTestCase(unittest.TestCase): def setUp(self): self.host = 'http://www.google.com' def test_init(self): config = Config(host=self.host) self.assertEqual(self.host, config.host) self.assertListEqual([], config.requests) self.assertEqual(10, config.do_requests_count) self.assertEqual(1, config.clients_count) def test_add_request(self): config = Config(host='config_host') request_a = Request(url='/', type=Request.GET) request_b = Request(url='/about', type=Request.POST) config.add_request(request_a) config.add_request(request_b) self.assertListEqual([request_a, request_b], config.requests) with self.assertRaises(TypeError) as error: config.add_request('no_request_type') self.assertEqual('No performance.web.Request object', error.exception.__str__())
Update test to for Config.add_request and config-counts
Update test to for Config.add_request and config-counts
Python
mit
BakeCode/performance-testing,BakeCode/performance-testing
import unittest from performance.routine import Config from performance.web import Request class ConfigTestCase(unittest.TestCase): def setUp(self): self.host = 'http://www.google.com' def test_init(self): config = Config(host=self.host) self.assertEqual(self.host, config.host) - self.assertEqual([], config.requests) + self.assertListEqual([], config.requests) + self.assertEqual(10, config.do_requests_count) + self.assertEqual(1, config.clients_count) def test_add_request(self): - config = Config(host=self.host) + config = Config(host='config_host') - requestA = Request(url='/', type=Request.GET) + request_a = Request(url='/', type=Request.GET) - requestB = Request(url='/about', type=Request.POST) + request_b = Request(url='/about', type=Request.POST) - config.add_request(requestA) + config.add_request(request_a) - config.add_request(requestB) + config.add_request(request_b) - self.assertEqual([requestA, requestB], config.requests) + self.assertListEqual([request_a, request_b], config.requests) with self.assertRaises(TypeError) as error: config.add_request('no_request_type') self.assertEqual('No performance.web.Request object', error.exception.__str__())
Update test to for Config.add_request and config-counts
## Code Before: import unittest from performance.routine import Config from performance.web import Request class ConfigTestCase(unittest.TestCase): def setUp(self): self.host = 'http://www.google.com' def test_init(self): config = Config(host=self.host) self.assertEqual(self.host, config.host) self.assertEqual([], config.requests) def test_add_request(self): config = Config(host=self.host) requestA = Request(url='/', type=Request.GET) requestB = Request(url='/about', type=Request.POST) config.add_request(requestA) config.add_request(requestB) self.assertEqual([requestA, requestB], config.requests) with self.assertRaises(TypeError) as error: config.add_request('no_request_type') self.assertEqual('No performance.web.Request object', error.exception.__str__()) ## Instruction: Update test to for Config.add_request and config-counts ## Code After: import unittest from performance.routine import Config from performance.web import Request class ConfigTestCase(unittest.TestCase): def setUp(self): self.host = 'http://www.google.com' def test_init(self): config = Config(host=self.host) self.assertEqual(self.host, config.host) self.assertListEqual([], config.requests) self.assertEqual(10, config.do_requests_count) self.assertEqual(1, config.clients_count) def test_add_request(self): config = Config(host='config_host') request_a = Request(url='/', type=Request.GET) request_b = Request(url='/about', type=Request.POST) config.add_request(request_a) config.add_request(request_b) self.assertListEqual([request_a, request_b], config.requests) with self.assertRaises(TypeError) as error: config.add_request('no_request_type') self.assertEqual('No performance.web.Request object', error.exception.__str__())
// ... existing code ... config = Config(host=self.host) self.assertEqual(self.host, config.host) self.assertListEqual([], config.requests) self.assertEqual(10, config.do_requests_count) self.assertEqual(1, config.clients_count) def test_add_request(self): config = Config(host='config_host') request_a = Request(url='/', type=Request.GET) request_b = Request(url='/about', type=Request.POST) config.add_request(request_a) config.add_request(request_b) self.assertListEqual([request_a, request_b], config.requests) with self.assertRaises(TypeError) as error: config.add_request('no_request_type') // ... rest of the code ...
3856b48af3e83f49a66c0c29b81e0a80ad3248d9
nubes/connectors/aws/connector.py
nubes/connectors/aws/connector.py
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): ec2_resource = self.connection.resource("ec2") server = ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): ec2_client = self.connection.client("ec2") desc = ec2_client.describe_instances() return desc def delete_server(self, instance_id): ec2_resource = self.connection.resource("ec2") ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) self.ec2_resource = self.connection.resource("ec2") self.ec2_client = self.connection.client("ec2") @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): server = self.ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
Move client and resource to __init__
Move client and resource to __init__ * moved the calls to create the ec2 session resource session client to the init
Python
apache-2.0
omninubes/nubes
import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) + self.ec2_resource = self.connection.resource("ec2") + self.ec2_client = self.connection.client("ec2") + @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): - ec2_resource = self.connection.resource("ec2") - server = ec2_resource.create_instances(ImageId=image_id, + server = self.ec2_resource.create_instances(ImageId=image_id, - MinCount=min_count, + MinCount=min_count, - MaxCount=max_count, + MaxCount=max_count, - **kwargs) + **kwargs) return server def list_servers(self): - ec2_client = self.connection.client("ec2") - desc = ec2_client.describe_instances() + desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): - ec2_resource = self.connection.resource("ec2") - ec2_resource.instances.filter( + self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() - ec2_resource.instances.filter( + self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
Move client and resource to __init__
## Code Before: import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): ec2_resource = self.connection.resource("ec2") server = ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): ec2_client = self.connection.client("ec2") desc = ec2_client.describe_instances() return desc def delete_server(self, instance_id): ec2_resource = self.connection.resource("ec2") ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate() ## Instruction: Move client and resource to __init__ ## Code After: import boto3.session from nubes.connectors import base class AWSConnector(base.BaseConnector): def __init__(self, aws_access_key_id, aws_secret_access_key, region_name): self.connection = boto3.session.Session( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region_name) self.ec2_resource = self.connection.resource("ec2") self.ec2_client = self.connection.client("ec2") @classmethod def name(cls): return "aws" def create_server(self, image_id, min_count, max_count, **kwargs): server = self.ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate()
... region_name=region_name) self.ec2_resource = self.connection.resource("ec2") self.ec2_client = self.connection.client("ec2") @classmethod def name(cls): ... def create_server(self, image_id, min_count, max_count, **kwargs): server = self.ec2_resource.create_instances(ImageId=image_id, MinCount=min_count, MaxCount=max_count, **kwargs) return server def list_servers(self): desc = self.ec2_client.describe_instances() return desc def delete_server(self, instance_id): self.ec2_resource.instances.filter( InstanceIds=[instance_id]).stop() self.ec2_resource.instances.filter( InstanceIds=[instance_id]).terminate() ...
836fd354037a6aca6898b41a9d62ada31f1ee6ba
rasterio/tool.py
rasterio/tool.py
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.start_ipython(argv=[], user_ns=locals) return 0
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
Print the banner in IPython
Print the banner in IPython
Python
bsd-3-clause
clembou/rasterio,brendan-ward/rasterio,kapadia/rasterio,clembou/rasterio,njwilson23/rasterio,perrygeo/rasterio,brendan-ward/rasterio,perrygeo/rasterio,youngpm/rasterio,johanvdw/rasterio,clembou/rasterio,kapadia/rasterio,njwilson23/rasterio,perrygeo/rasterio,youngpm/rasterio,brendan-ward/rasterio,njwilson23/rasterio,johanvdw/rasterio,kapadia/rasterio,johanvdw/rasterio,youngpm/rasterio
import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) + IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
Print the banner in IPython
## Code Before: import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.start_ipython(argv=[], user_ns=locals) return 0 ## Instruction: Print the banner in IPython ## Code After: import code import collections import logging import sys try: import matplotlib.pyplot as plt except ImportError: plt = None import numpy import rasterio logger = logging.getLogger('rasterio') Stats = collections.namedtuple('Stats', ['min', 'max', 'mean']) # Collect dictionary of functions for use in the interpreter in main() funcs = locals() def show(source, cmap='gray'): """Show a raster using matplotlib. The raster may be either an ndarray or a (dataset, bidx) tuple. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source if plt is not None: plt.imshow(arr, cmap=cmap) plt.show() else: raise ImportError("matplotlib could not be imported") def stats(source): """Return a tuple with raster min, max, and mean. """ if isinstance(source, tuple): arr = source[0].read(source[1]) else: arr = source return Stats(numpy.min(arr), numpy.max(arr), numpy.mean(arr)) def main(banner, dataset): """ Main entry point for use with IPython interpreter """ import IPython locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) return 0
// ... existing code ... locals = dict(funcs, src=dataset, np=numpy, rio=rasterio, plt=plt) IPython.InteractiveShell.banner1 = banner IPython.start_ipython(argv=[], user_ns=locals) // ... rest of the code ...
37e569bed66e18e0ae80222f2988277023e19916
tests/test_cli.py
tests/test_cli.py
from __future__ import unicode_literals import mock import pytest import pypi_cli as pypi @pytest.mark.usefixtures('mock_api') class TestStat: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['stat']) assert result.exit_code > 0 def test_with_package(self, runner): result = runner.invoke(pypi.cli, ['stat', 'webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output class TestBrowse: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['browse']) assert result.exit_code > 0 @mock.patch('pypi_cli.click.termui.launch') def test_with_package(self, mock_launch, runner): result = runner.invoke(pypi.cli, ['browse', 'webargs']) assert result.exit_code == 0 assert mock_launch.called is True def test_version(runner): result = runner.invoke(pypi.cli, ['-v']) assert result.output == pypi.__version__ + '\n' result = runner.invoke(pypi.cli, ['--version']) assert result.output == pypi.__version__ + '\n'
from __future__ import unicode_literals import mock import pytest import pypi_cli as pypi @pytest.mark.usefixtures('mock_api') class TestStat: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['stat']) assert result.exit_code > 0 def test_with_package(self, runner): result = runner.invoke(pypi.cli, ['stat', 'webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output def test_with_package_url(self, runner): result = runner.invoke(pypi.cli, ['stat', 'http://pypi.python.org/pypi/webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output @pytest.mark.usefixtures('mock_api') class TestBrowse: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['browse']) assert result.exit_code > 0 @mock.patch('pypi_cli.click.termui.launch') def test_with_package(self, mock_launch, runner): result = runner.invoke(pypi.cli, ['browse', 'webargs']) assert result.exit_code == 0 assert mock_launch.called is True def test_version(runner): result = runner.invoke(pypi.cli, ['-v']) assert result.output == pypi.__version__ + '\n' result = runner.invoke(pypi.cli, ['--version']) assert result.output == pypi.__version__ + '\n'
Add test for inputting package URL
Add test for inputting package URL
Python
mit
pombredanne/pypi-cli,sloria/pypi-cli,mindw/pypi-cli
from __future__ import unicode_literals import mock import pytest import pypi_cli as pypi @pytest.mark.usefixtures('mock_api') class TestStat: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['stat']) assert result.exit_code > 0 def test_with_package(self, runner): result = runner.invoke(pypi.cli, ['stat', 'webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output + def test_with_package_url(self, runner): + result = runner.invoke(pypi.cli, ['stat', 'http://pypi.python.org/pypi/webargs']) + assert result.exit_code == 0 + assert 'Download statistics for webargs' in result.output + + @pytest.mark.usefixtures('mock_api') class TestBrowse: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['browse']) assert result.exit_code > 0 @mock.patch('pypi_cli.click.termui.launch') def test_with_package(self, mock_launch, runner): result = runner.invoke(pypi.cli, ['browse', 'webargs']) assert result.exit_code == 0 assert mock_launch.called is True - def test_version(runner): result = runner.invoke(pypi.cli, ['-v']) assert result.output == pypi.__version__ + '\n' result = runner.invoke(pypi.cli, ['--version']) assert result.output == pypi.__version__ + '\n'
Add test for inputting package URL
## Code Before: from __future__ import unicode_literals import mock import pytest import pypi_cli as pypi @pytest.mark.usefixtures('mock_api') class TestStat: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['stat']) assert result.exit_code > 0 def test_with_package(self, runner): result = runner.invoke(pypi.cli, ['stat', 'webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output class TestBrowse: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['browse']) assert result.exit_code > 0 @mock.patch('pypi_cli.click.termui.launch') def test_with_package(self, mock_launch, runner): result = runner.invoke(pypi.cli, ['browse', 'webargs']) assert result.exit_code == 0 assert mock_launch.called is True def test_version(runner): result = runner.invoke(pypi.cli, ['-v']) assert result.output == pypi.__version__ + '\n' result = runner.invoke(pypi.cli, ['--version']) assert result.output == pypi.__version__ + '\n' ## Instruction: Add test for inputting package URL ## Code After: from __future__ import unicode_literals import mock import pytest import pypi_cli as pypi @pytest.mark.usefixtures('mock_api') class TestStat: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['stat']) assert result.exit_code > 0 def test_with_package(self, runner): result = runner.invoke(pypi.cli, ['stat', 'webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output def test_with_package_url(self, runner): result = runner.invoke(pypi.cli, ['stat', 'http://pypi.python.org/pypi/webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output @pytest.mark.usefixtures('mock_api') class TestBrowse: def test_missing_package_arg(self, runner): result = runner.invoke(pypi.cli, ['browse']) assert result.exit_code > 0 @mock.patch('pypi_cli.click.termui.launch') def test_with_package(self, mock_launch, runner): result = runner.invoke(pypi.cli, ['browse', 'webargs']) assert result.exit_code == 0 assert mock_launch.called is True def test_version(runner): result = runner.invoke(pypi.cli, ['-v']) assert result.output == pypi.__version__ + '\n' result = runner.invoke(pypi.cli, ['--version']) assert result.output == pypi.__version__ + '\n'
// ... existing code ... assert 'Download statistics for webargs' in result.output def test_with_package_url(self, runner): result = runner.invoke(pypi.cli, ['stat', 'http://pypi.python.org/pypi/webargs']) assert result.exit_code == 0 assert 'Download statistics for webargs' in result.output @pytest.mark.usefixtures('mock_api') class TestBrowse: // ... modified code ... assert mock_launch.called is True def test_version(runner): result = runner.invoke(pypi.cli, ['-v']) // ... rest of the code ...
310553e1282231c35093ff355c61129e9f073a0a
src/lib/verify_email_google.py
src/lib/verify_email_google.py
import DNS from validate_email import validate_email from DNS.Lib import PackError def is_google_apps_email(email): hostname = email[email.find('@')+1:] try: mx_hosts = DNS.mxlookup(hostname) except DNS.ServerError as e: return False except PackError as e: return False for mx in mx_hosts: if len(mx) == 2: priority, host_server = mx else: host_server = mx if 'google' in str(host_server).lower() and 'aspmx' in str(host_server).lower(): return True return False
import DNS import re from validate_email import validate_email from DNS.Lib import PackError EMAIL_RE = re.compile('^[a-zA-Z0-9\.\@]+$') def is_valid_email(email): if email.count('@') != 1: return False return bool(EMAIL_RE.match(email)) def is_google_apps_email(email): if not is_valid_email(email): return False hostname = email[email.find('@')+1:] try: mx_hosts = DNS.mxlookup(hostname) except DNS.ServerError as e: return False except PackError as e: return False for mx in mx_hosts: if len(mx) == 2: priority, host_server = mx else: host_server = mx if 'google' in str(host_server).lower() and 'aspmx' in str(host_server).lower(): return True return False
Add Google Apps email address validation
Add Google Apps email address validation
Python
agpl-3.0
juposocial/jupo,juposocial/jupo,juposocial/jupo,juposocial/jupo
import DNS + import re from validate_email import validate_email from DNS.Lib import PackError + EMAIL_RE = re.compile('^[a-zA-Z0-9\.\@]+$') + + def is_valid_email(email): + if email.count('@') != 1: + return False + return bool(EMAIL_RE.match(email)) + def is_google_apps_email(email): + if not is_valid_email(email): + return False + hostname = email[email.find('@')+1:] try: mx_hosts = DNS.mxlookup(hostname) except DNS.ServerError as e: return False except PackError as e: return False for mx in mx_hosts: if len(mx) == 2: priority, host_server = mx else: host_server = mx if 'google' in str(host_server).lower() and 'aspmx' in str(host_server).lower(): return True return False
Add Google Apps email address validation
## Code Before: import DNS from validate_email import validate_email from DNS.Lib import PackError def is_google_apps_email(email): hostname = email[email.find('@')+1:] try: mx_hosts = DNS.mxlookup(hostname) except DNS.ServerError as e: return False except PackError as e: return False for mx in mx_hosts: if len(mx) == 2: priority, host_server = mx else: host_server = mx if 'google' in str(host_server).lower() and 'aspmx' in str(host_server).lower(): return True return False ## Instruction: Add Google Apps email address validation ## Code After: import DNS import re from validate_email import validate_email from DNS.Lib import PackError EMAIL_RE = re.compile('^[a-zA-Z0-9\.\@]+$') def is_valid_email(email): if email.count('@') != 1: return False return bool(EMAIL_RE.match(email)) def is_google_apps_email(email): if not is_valid_email(email): return False hostname = email[email.find('@')+1:] try: mx_hosts = DNS.mxlookup(hostname) except DNS.ServerError as e: return False except PackError as e: return False for mx in mx_hosts: if len(mx) == 2: priority, host_server = mx else: host_server = mx if 'google' in str(host_server).lower() and 'aspmx' in str(host_server).lower(): return True return False
... import DNS import re from validate_email import validate_email from DNS.Lib import PackError ... EMAIL_RE = re.compile('^[a-zA-Z0-9\.\@]+$') def is_valid_email(email): if email.count('@') != 1: return False return bool(EMAIL_RE.match(email)) def is_google_apps_email(email): if not is_valid_email(email): return False hostname = email[email.find('@')+1:] ...
8278da2e22bc1a10ada43585685aa4a0841d14c5
apps/bluebottle_utils/tests.py
apps/bluebottle_utils/tests.py
import uuid from django.contrib.auth.models import User class UserTestsMixin(object): """ Mixin base class for tests requiring users. """ def create_user(self, username=None, password=None): """ Create, save and return a new user. """ if not username: # Generate a random username username = str(uuid.uuid4())[:30] user = User.objects.create_user(username=username) return user
import uuid from django.contrib.auth.models import User class UserTestsMixin(object): """ Mixin base class for tests requiring users. """ def create_user(self, username=None, password=None): """ Create, save and return a new user. """ # If no username is set, create a random unique username while not username or User.objects.filter(username=username).exists(): # Generate a random username username = str(uuid.uuid4())[:30] user = User.objects.create_user(username=username) return user
Make sure generated usernames are unique.
Make sure generated usernames are unique.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
import uuid from django.contrib.auth.models import User class UserTestsMixin(object): """ Mixin base class for tests requiring users. """ def create_user(self, username=None, password=None): """ Create, save and return a new user. """ - if not username: + # If no username is set, create a random unique username + while not username or User.objects.filter(username=username).exists(): # Generate a random username username = str(uuid.uuid4())[:30] user = User.objects.create_user(username=username) return user
Make sure generated usernames are unique.
## Code Before: import uuid from django.contrib.auth.models import User class UserTestsMixin(object): """ Mixin base class for tests requiring users. """ def create_user(self, username=None, password=None): """ Create, save and return a new user. """ if not username: # Generate a random username username = str(uuid.uuid4())[:30] user = User.objects.create_user(username=username) return user ## Instruction: Make sure generated usernames are unique. ## Code After: import uuid from django.contrib.auth.models import User class UserTestsMixin(object): """ Mixin base class for tests requiring users. """ def create_user(self, username=None, password=None): """ Create, save and return a new user. """ # If no username is set, create a random unique username while not username or User.objects.filter(username=username).exists(): # Generate a random username username = str(uuid.uuid4())[:30] user = User.objects.create_user(username=username) return user
// ... existing code ... """ Create, save and return a new user. """ # If no username is set, create a random unique username while not username or User.objects.filter(username=username).exists(): # Generate a random username username = str(uuid.uuid4())[:30] // ... rest of the code ...
583a32cd1e9e77d7648978d20a5b7631a4fe2334
tests/sentry/interfaces/tests.py
tests/sentry/interfaces/tests.py
from __future__ import absolute_import import pickle from sentry.interfaces import Interface from sentry.testutils import TestCase class InterfaceTests(TestCase): def test_init_sets_attrs(self): obj = Interface(foo=1) self.assertEqual(obj.attrs, ['foo']) def test_setstate_sets_attrs(self): data = pickle.dumps(Interface(foo=1)) obj = pickle.loads(data) self.assertEqual(obj.attrs, ['foo'])
from __future__ import absolute_import import pickle from sentry.interfaces import Interface, Message, Stacktrace from sentry.models import Event from sentry.testutils import TestCase, fixture class InterfaceBase(TestCase): @fixture def event(self): return Event( id=1, ) class InterfaceTest(InterfaceBase): @fixture def interface(self): return Interface(foo=1) def test_init_sets_attrs(self): assert self.interface.attrs == ['foo'] def test_setstate_sets_attrs(self): data = pickle.dumps(self.interface) obj = pickle.loads(data) assert obj.attrs == ['foo'] def test_to_html_default(self): assert self.interface.to_html(self.event) == '' def test_to_string_default(self): assert self.interface.to_string(self.event) == '' class MessageTest(InterfaceBase): @fixture def interface(self): return Message(message='Hello there %s!', params=('world',)) def test_serialize_behavior(self): assert self.interface.serialize() == { 'message': self.interface.message, 'params': self.interface.params, } def test_get_hash_uses_message(self): assert self.interface.get_hash() == [self.interface.message] def test_get_search_context_with_params_as_list(self): interface = self.interface interface.params = ['world'] assert interface.get_search_context(self.event) == { 'text': [interface.message] + list(interface.params) } def test_get_search_context_with_params_as_tuple(self): assert self.interface.get_search_context(self.event) == { 'text': [self.interface.message] + list(self.interface.params) } def test_get_search_context_with_params_as_dict(self): interface = self.interface interface.params = {'who': 'world'} interface.message = 'Hello there %(who)s!' assert self.interface.get_search_context(self.event) == { 'text': [interface.message] + interface.params.values() }
Improve test coverage on base Interface and Message classes
Improve test coverage on base Interface and Message classes
Python
bsd-3-clause
songyi199111/sentry,JTCunning/sentry,JackDanger/sentry,fotinakis/sentry,JamesMura/sentry,kevinlondon/sentry,mitsuhiko/sentry,felixbuenemann/sentry,fotinakis/sentry,jean/sentry,drcapulet/sentry,ifduyue/sentry,alexm92/sentry,pauloschilling/sentry,fuziontech/sentry,jokey2k/sentry,fotinakis/sentry,argonemyth/sentry,zenefits/sentry,Kryz/sentry,beeftornado/sentry,boneyao/sentry,pauloschilling/sentry,hongliang5623/sentry,fuziontech/sentry,imankulov/sentry,rdio/sentry,jean/sentry,BayanGroup/sentry,songyi199111/sentry,rdio/sentry,felixbuenemann/sentry,nicholasserra/sentry,looker/sentry,gg7/sentry,jokey2k/sentry,gg7/sentry,vperron/sentry,alexm92/sentry,mvaled/sentry,SilentCircle/sentry,BayanGroup/sentry,korealerts1/sentry,alexm92/sentry,ngonzalvez/sentry,fuziontech/sentry,BuildingLink/sentry,Natim/sentry,looker/sentry,boneyao/sentry,daevaorn/sentry,Natim/sentry,rdio/sentry,llonchj/sentry,kevinastone/sentry,kevinlondon/sentry,wong2/sentry,looker/sentry,beeftornado/sentry,JTCunning/sentry,JamesMura/sentry,JTCunning/sentry,BuildingLink/sentry,wong2/sentry,camilonova/sentry,gencer/sentry,BuildingLink/sentry,mvaled/sentry,gencer/sentry,BayanGroup/sentry,imankulov/sentry,beni55/sentry,gg7/sentry,felixbuenemann/sentry,Natim/sentry,wong2/sentry,kevinastone/sentry,looker/sentry,1tush/sentry,songyi199111/sentry,nicholasserra/sentry,wujuguang/sentry,SilentCircle/sentry,ifduyue/sentry,jean/sentry,camilonova/sentry,ifduyue/sentry,BuildingLink/sentry,wujuguang/sentry,wujuguang/sentry,TedaLIEz/sentry,pauloschilling/sentry,hongliang5623/sentry,beeftornado/sentry,mvaled/sentry,zenefits/sentry,beni55/sentry,daevaorn/sentry,1tush/sentry,jokey2k/sentry,korealerts1/sentry,gencer/sentry,rdio/sentry,ngonzalvez/sentry,JackDanger/sentry,BuildingLink/sentry,looker/sentry,1tush/sentry,gencer/sentry,TedaLIEz/sentry,JamesMura/sentry,vperron/sentry,argonemyth/sentry,ewdurbin/sentry,zenefits/sentry,jean/sentry,SilentCircle/sentry,drcapulet/sentry,gencer/sentry,NickPresta/sentry,zenefits/sentry,nicholasserra/sentry,ngonzalvez/sentry,drcapulet/sentry,NickPresta/sentry,daevaorn/sentry,ewdurbin/sentry,hongliang5623/sentry,fotinakis/sentry,ifduyue/sentry,kevinlondon/sentry,llonchj/sentry,mitsuhiko/sentry,zenefits/sentry,kevinastone/sentry,mvaled/sentry,JamesMura/sentry,ifduyue/sentry,mvaled/sentry,korealerts1/sentry,jean/sentry,NickPresta/sentry,daevaorn/sentry,beni55/sentry,SilentCircle/sentry,vperron/sentry,JamesMura/sentry,TedaLIEz/sentry,argonemyth/sentry,camilonova/sentry,ewdurbin/sentry,boneyao/sentry,llonchj/sentry,imankulov/sentry,Kryz/sentry,JackDanger/sentry,Kryz/sentry,mvaled/sentry,NickPresta/sentry
from __future__ import absolute_import import pickle - from sentry.interfaces import Interface + from sentry.interfaces import Interface, Message, Stacktrace - + from sentry.models import Event - from sentry.testutils import TestCase + from sentry.testutils import TestCase, fixture - class InterfaceTests(TestCase): + class InterfaceBase(TestCase): + @fixture + def event(self): + return Event( + id=1, + ) + + + class InterfaceTest(InterfaceBase): + @fixture + def interface(self): + return Interface(foo=1) def test_init_sets_attrs(self): + assert self.interface.attrs == ['foo'] - obj = Interface(foo=1) - self.assertEqual(obj.attrs, ['foo']) def test_setstate_sets_attrs(self): - data = pickle.dumps(Interface(foo=1)) + data = pickle.dumps(self.interface) obj = pickle.loads(data) - self.assertEqual(obj.attrs, ['foo']) + assert obj.attrs == ['foo'] + def test_to_html_default(self): + assert self.interface.to_html(self.event) == '' + + def test_to_string_default(self): + assert self.interface.to_string(self.event) == '' + + + class MessageTest(InterfaceBase): + @fixture + def interface(self): + return Message(message='Hello there %s!', params=('world',)) + + def test_serialize_behavior(self): + assert self.interface.serialize() == { + 'message': self.interface.message, + 'params': self.interface.params, + } + + def test_get_hash_uses_message(self): + assert self.interface.get_hash() == [self.interface.message] + + def test_get_search_context_with_params_as_list(self): + interface = self.interface + interface.params = ['world'] + assert interface.get_search_context(self.event) == { + 'text': [interface.message] + list(interface.params) + } + + def test_get_search_context_with_params_as_tuple(self): + assert self.interface.get_search_context(self.event) == { + 'text': [self.interface.message] + list(self.interface.params) + } + + def test_get_search_context_with_params_as_dict(self): + interface = self.interface + interface.params = {'who': 'world'} + interface.message = 'Hello there %(who)s!' + assert self.interface.get_search_context(self.event) == { + 'text': [interface.message] + interface.params.values() + } +
Improve test coverage on base Interface and Message classes
## Code Before: from __future__ import absolute_import import pickle from sentry.interfaces import Interface from sentry.testutils import TestCase class InterfaceTests(TestCase): def test_init_sets_attrs(self): obj = Interface(foo=1) self.assertEqual(obj.attrs, ['foo']) def test_setstate_sets_attrs(self): data = pickle.dumps(Interface(foo=1)) obj = pickle.loads(data) self.assertEqual(obj.attrs, ['foo']) ## Instruction: Improve test coverage on base Interface and Message classes ## Code After: from __future__ import absolute_import import pickle from sentry.interfaces import Interface, Message, Stacktrace from sentry.models import Event from sentry.testutils import TestCase, fixture class InterfaceBase(TestCase): @fixture def event(self): return Event( id=1, ) class InterfaceTest(InterfaceBase): @fixture def interface(self): return Interface(foo=1) def test_init_sets_attrs(self): assert self.interface.attrs == ['foo'] def test_setstate_sets_attrs(self): data = pickle.dumps(self.interface) obj = pickle.loads(data) assert obj.attrs == ['foo'] def test_to_html_default(self): assert self.interface.to_html(self.event) == '' def test_to_string_default(self): assert self.interface.to_string(self.event) == '' class MessageTest(InterfaceBase): @fixture def interface(self): return Message(message='Hello there %s!', params=('world',)) def test_serialize_behavior(self): assert self.interface.serialize() == { 'message': self.interface.message, 'params': self.interface.params, } def test_get_hash_uses_message(self): assert self.interface.get_hash() == [self.interface.message] def test_get_search_context_with_params_as_list(self): interface = self.interface interface.params = ['world'] assert interface.get_search_context(self.event) == { 'text': [interface.message] + list(interface.params) } def test_get_search_context_with_params_as_tuple(self): assert self.interface.get_search_context(self.event) == { 'text': [self.interface.message] + list(self.interface.params) } def test_get_search_context_with_params_as_dict(self): interface = self.interface interface.params = {'who': 'world'} interface.message = 'Hello there %(who)s!' assert self.interface.get_search_context(self.event) == { 'text': [interface.message] + interface.params.values() }
... import pickle from sentry.interfaces import Interface, Message, Stacktrace from sentry.models import Event from sentry.testutils import TestCase, fixture class InterfaceBase(TestCase): @fixture def event(self): return Event( id=1, ) class InterfaceTest(InterfaceBase): @fixture def interface(self): return Interface(foo=1) def test_init_sets_attrs(self): assert self.interface.attrs == ['foo'] def test_setstate_sets_attrs(self): data = pickle.dumps(self.interface) obj = pickle.loads(data) assert obj.attrs == ['foo'] def test_to_html_default(self): assert self.interface.to_html(self.event) == '' def test_to_string_default(self): assert self.interface.to_string(self.event) == '' class MessageTest(InterfaceBase): @fixture def interface(self): return Message(message='Hello there %s!', params=('world',)) def test_serialize_behavior(self): assert self.interface.serialize() == { 'message': self.interface.message, 'params': self.interface.params, } def test_get_hash_uses_message(self): assert self.interface.get_hash() == [self.interface.message] def test_get_search_context_with_params_as_list(self): interface = self.interface interface.params = ['world'] assert interface.get_search_context(self.event) == { 'text': [interface.message] + list(interface.params) } def test_get_search_context_with_params_as_tuple(self): assert self.interface.get_search_context(self.event) == { 'text': [self.interface.message] + list(self.interface.params) } def test_get_search_context_with_params_as_dict(self): interface = self.interface interface.params = {'who': 'world'} interface.message = 'Hello there %(who)s!' assert self.interface.get_search_context(self.event) == { 'text': [interface.message] + interface.params.values() } ...
24ca48098777d89835cf169ee2b4f06db50ec9f1
koans/triangle.py
koans/triangle.py
def triangle(a, b, c): if (a <= 0 or b <= 0 and c <= 0): raise TriangleError() if (a == b and b == c and c == a): return 'equilateral' elif (a == b or b == c or c == a): return 'isosceles' elif (a != b and b != c and c != a): return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
def triangle(a, b, c): if (a <= 0 or b <= 0 and c <= 0): raise TriangleError() if (a == b and b == c): return 'equilateral' elif (a == b or b == c or c == a): return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
Simplify logic conditionals as tests still pass.
Simplify logic conditionals as tests still pass.
Python
mit
javierjulio/python-koans-completed,javierjulio/python-koans-completed
def triangle(a, b, c): if (a <= 0 or b <= 0 and c <= 0): raise TriangleError() - if (a == b and b == c and c == a): + if (a == b and b == c): return 'equilateral' elif (a == b or b == c or c == a): return 'isosceles' - elif (a != b and b != c and c != a): + else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
Simplify logic conditionals as tests still pass.
## Code Before: def triangle(a, b, c): if (a <= 0 or b <= 0 and c <= 0): raise TriangleError() if (a == b and b == c and c == a): return 'equilateral' elif (a == b or b == c or c == a): return 'isosceles' elif (a != b and b != c and c != a): return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass ## Instruction: Simplify logic conditionals as tests still pass. ## Code After: def triangle(a, b, c): if (a <= 0 or b <= 0 and c <= 0): raise TriangleError() if (a == b and b == c): return 'equilateral' elif (a == b or b == c or c == a): return 'isosceles' else: return 'scalene' # Error class used in part 2. No need to change this code. class TriangleError(Exception): pass
// ... existing code ... raise TriangleError() if (a == b and b == c): return 'equilateral' elif (a == b or b == c or c == a): return 'isosceles' else: return 'scalene' // ... rest of the code ...
e43596395507c4606909087c0e77e84c1a232811
damn/__init__.py
damn/__init__.py
__version__ = '0.0.0'
__author__ = 'Romain Clement' __copyright__ = 'Copyright 2014, Romain Clement' __credits__ = [] __license__ = 'MIT' __version__ = "0.0.0" __maintainer__ = 'Romain Clement' __email__ = '[email protected]' __status__ = 'Development'
Add meta information for damn package
[DEV] Add meta information for damn package
Python
mit
rclement/yodel,rclement/yodel
+ __author__ = 'Romain Clement' + __copyright__ = 'Copyright 2014, Romain Clement' + __credits__ = [] + __license__ = 'MIT' - __version__ = '0.0.0' + __version__ = "0.0.0" + __maintainer__ = 'Romain Clement' + __email__ = '[email protected]' + __status__ = 'Development'
Add meta information for damn package
## Code Before: __version__ = '0.0.0' ## Instruction: Add meta information for damn package ## Code After: __author__ = 'Romain Clement' __copyright__ = 'Copyright 2014, Romain Clement' __credits__ = [] __license__ = 'MIT' __version__ = "0.0.0" __maintainer__ = 'Romain Clement' __email__ = '[email protected]' __status__ = 'Development'
# ... existing code ... __author__ = 'Romain Clement' __copyright__ = 'Copyright 2014, Romain Clement' __credits__ = [] __license__ = 'MIT' __version__ = "0.0.0" __maintainer__ = 'Romain Clement' __email__ = '[email protected]' __status__ = 'Development' # ... rest of the code ...
2a43183f5d2c14bacb92fe563d3c2ddf61b116da
tests/testMain.py
tests/testMain.py
import os import unittest import numpy import arcpy from utils import * # import our constants; # configure test data # XXX: use .ini files for these instead? used in other 'important' unit tests from config import * # import our local directory so we can use the internal modules import_paths = ['../Install/toolbox', '../Install'] addLocalPaths(import_paths) class TestBpiScript(unittest.TestCase): from scripts import bpi def testBpiImport(self, method=bpi): self.assertRaises(ValueError, method.main(), None) def testBpiRun(self): pass class TestStandardizeBpiGridsScript(unittest.TestCase): from scripts import standardize_bpi_grids def testStdImport(self, method=standardize_bpi_grids): pass def testStdRun(self): pass class TestBtmDocument(unittest.TestCase): # XXX this won't automatically get the right thing... how can we fix it? import utils def testXMLDocumentExists(self): self.assertTrue(os.path.exists(xml_doc)) if __name__ == '__main__': unittest.main()
import os import unittest import numpy import arcpy from utils import * # import our constants; # configure test data # XXX: use .ini files for these instead? used in other 'important' unit tests from config import * # import our local directory so we can use the internal modules import_paths = ['../Install/toolbox', '../Install'] addLocalPaths(import_paths) class TestBpiScript(unittest.TestCase): from scripts import bpi def testBpiImport(self, method=bpi): self.assertRaises(ValueError, method.main(), None) def testBpiRun(self): pass class TestStandardizeBpiGridsScript(unittest.TestCase): from scripts import standardize_bpi_grids def testStdImport(self, method=standardize_bpi_grids): pass def testStdRun(self): pass class TestBtmDocument(unittest.TestCase): # XXX this won't automatically get the right thing... how can we fix it? import utils def testXmlDocumentExists(self): self.assertTrue(os.path.exists(xml_doc)) def testCsvDocumentExists(self): self.assertTrue(os.path.exists(csv_doc)) if __name__ == '__main__': unittest.main()
Make naming consistent with our standard (camelcase always, even with acronymn)
Make naming consistent with our standard (camelcase always, even with acronymn)
Python
mpl-2.0
EsriOceans/btm
import os import unittest import numpy import arcpy from utils import * # import our constants; # configure test data # XXX: use .ini files for these instead? used in other 'important' unit tests from config import * # import our local directory so we can use the internal modules import_paths = ['../Install/toolbox', '../Install'] addLocalPaths(import_paths) class TestBpiScript(unittest.TestCase): from scripts import bpi def testBpiImport(self, method=bpi): self.assertRaises(ValueError, method.main(), None) def testBpiRun(self): pass class TestStandardizeBpiGridsScript(unittest.TestCase): from scripts import standardize_bpi_grids def testStdImport(self, method=standardize_bpi_grids): pass def testStdRun(self): pass class TestBtmDocument(unittest.TestCase): # XXX this won't automatically get the right thing... how can we fix it? import utils - def testXMLDocumentExists(self): + def testXmlDocumentExists(self): self.assertTrue(os.path.exists(xml_doc)) + + def testCsvDocumentExists(self): + self.assertTrue(os.path.exists(csv_doc)) if __name__ == '__main__': unittest.main()
Make naming consistent with our standard (camelcase always, even with acronymn)
## Code Before: import os import unittest import numpy import arcpy from utils import * # import our constants; # configure test data # XXX: use .ini files for these instead? used in other 'important' unit tests from config import * # import our local directory so we can use the internal modules import_paths = ['../Install/toolbox', '../Install'] addLocalPaths(import_paths) class TestBpiScript(unittest.TestCase): from scripts import bpi def testBpiImport(self, method=bpi): self.assertRaises(ValueError, method.main(), None) def testBpiRun(self): pass class TestStandardizeBpiGridsScript(unittest.TestCase): from scripts import standardize_bpi_grids def testStdImport(self, method=standardize_bpi_grids): pass def testStdRun(self): pass class TestBtmDocument(unittest.TestCase): # XXX this won't automatically get the right thing... how can we fix it? import utils def testXMLDocumentExists(self): self.assertTrue(os.path.exists(xml_doc)) if __name__ == '__main__': unittest.main() ## Instruction: Make naming consistent with our standard (camelcase always, even with acronymn) ## Code After: import os import unittest import numpy import arcpy from utils import * # import our constants; # configure test data # XXX: use .ini files for these instead? used in other 'important' unit tests from config import * # import our local directory so we can use the internal modules import_paths = ['../Install/toolbox', '../Install'] addLocalPaths(import_paths) class TestBpiScript(unittest.TestCase): from scripts import bpi def testBpiImport(self, method=bpi): self.assertRaises(ValueError, method.main(), None) def testBpiRun(self): pass class TestStandardizeBpiGridsScript(unittest.TestCase): from scripts import standardize_bpi_grids def testStdImport(self, method=standardize_bpi_grids): pass def testStdRun(self): pass class TestBtmDocument(unittest.TestCase): # XXX this won't automatically get the right thing... how can we fix it? import utils def testXmlDocumentExists(self): self.assertTrue(os.path.exists(xml_doc)) def testCsvDocumentExists(self): self.assertTrue(os.path.exists(csv_doc)) if __name__ == '__main__': unittest.main()
# ... existing code ... import utils def testXmlDocumentExists(self): self.assertTrue(os.path.exists(xml_doc)) def testCsvDocumentExists(self): self.assertTrue(os.path.exists(csv_doc)) # ... rest of the code ...
6947a38fd99447809870d82a425abd4db9d884fe
test/htmltoreadable.py
test/htmltoreadable.py
import codecs import os import grab from src import htmltoreadable as hr def test(): g = grab.Grab() g.go('http://habrahabr.ru/post/266293/') root_node = g.css('.post_show') text = hr.html_to_readable(root_node) path = 'out' if not os.path.exists(path): os.mkdir(path) outpath = os.path.join(path, 'out.log') with codecs.open(outpath, 'w', encoding='utf-8') as fh: fh.write(text) if __name__ == '__main__': test()
import codecs import os import grab from src import htmltoreadable as hr def test(): g = grab.Grab() g.go('http://habrahabr.ru/post/266293/') root_node = g.doc.tree.cssselect('.post_show')[0] text = hr.html_to_readable(root_node) path = 'out' if not os.path.exists(path): os.mkdir(path) outpath = os.path.join(path, 'out.log') with codecs.open(outpath, 'w', encoding='utf-8') as fh: fh.write(text) if __name__ == '__main__': test()
Delete using deprecated fnc in test
Delete using deprecated fnc in test
Python
mit
shigarus/NewsParser
import codecs import os import grab from src import htmltoreadable as hr def test(): g = grab.Grab() g.go('http://habrahabr.ru/post/266293/') - root_node = g.css('.post_show') + root_node = g.doc.tree.cssselect('.post_show')[0] text = hr.html_to_readable(root_node) path = 'out' if not os.path.exists(path): os.mkdir(path) outpath = os.path.join(path, 'out.log') with codecs.open(outpath, 'w', encoding='utf-8') as fh: fh.write(text) if __name__ == '__main__': test()
Delete using deprecated fnc in test
## Code Before: import codecs import os import grab from src import htmltoreadable as hr def test(): g = grab.Grab() g.go('http://habrahabr.ru/post/266293/') root_node = g.css('.post_show') text = hr.html_to_readable(root_node) path = 'out' if not os.path.exists(path): os.mkdir(path) outpath = os.path.join(path, 'out.log') with codecs.open(outpath, 'w', encoding='utf-8') as fh: fh.write(text) if __name__ == '__main__': test() ## Instruction: Delete using deprecated fnc in test ## Code After: import codecs import os import grab from src import htmltoreadable as hr def test(): g = grab.Grab() g.go('http://habrahabr.ru/post/266293/') root_node = g.doc.tree.cssselect('.post_show')[0] text = hr.html_to_readable(root_node) path = 'out' if not os.path.exists(path): os.mkdir(path) outpath = os.path.join(path, 'out.log') with codecs.open(outpath, 'w', encoding='utf-8') as fh: fh.write(text) if __name__ == '__main__': test()
# ... existing code ... g = grab.Grab() g.go('http://habrahabr.ru/post/266293/') root_node = g.doc.tree.cssselect('.post_show')[0] text = hr.html_to_readable(root_node) path = 'out' # ... rest of the code ...
1ee2e880872c4744f4159df7fc64bb64b3f35632
pygametemplate/button.py
pygametemplate/button.py
import time class Button(object): """Class representing keyboard keys.""" def __init__(self, game, number): self.game = game self.number = number self.event = None # The last event that caused the button press self.pressed = 0 # If the button was just pressed self.held = 0 # If the button is held self.released = 0 # If the button was just released self.press_time = 0.0 def press(self): self.pressed = 1 self.held = 1 self.press_time = time.time() def release(self): self.held = 0 self.released = 1 def reset(self): self.pressed = 0 self.released = 0 def time_held(self): if self.held: return time.time() - self.press_time else: return 0.0
import time class Button(object): """Class representing keyboard keys.""" def __init__(self, game, number): self.game = game self.number = number self.event = None # The last event that caused the button press self.pressed = 0 # If the button was just pressed self.held = 0 # If the button is held self.released = 0 # If the button was just released self.press_time = 0.0 def press(self): self.pressed = 1 self.held = 1 self.press_time = time.time() def release(self): self.held = 0 self.released = 1 def reset(self): self.pressed = 0 self.released = 0 def time_held(self) -> float: """Return the amount of time this button has been held for in seconds.""" if self.held: return time.time() - self.press_time else: return 0.0
Add docstring to Button.time_held() method
Add docstring to Button.time_held() method
Python
mit
AndyDeany/pygame-template
import time class Button(object): """Class representing keyboard keys.""" def __init__(self, game, number): self.game = game self.number = number self.event = None # The last event that caused the button press self.pressed = 0 # If the button was just pressed self.held = 0 # If the button is held self.released = 0 # If the button was just released self.press_time = 0.0 def press(self): self.pressed = 1 self.held = 1 self.press_time = time.time() def release(self): self.held = 0 self.released = 1 def reset(self): self.pressed = 0 self.released = 0 - def time_held(self): + def time_held(self) -> float: + """Return the amount of time this button has been held for in seconds.""" if self.held: return time.time() - self.press_time else: return 0.0
Add docstring to Button.time_held() method
## Code Before: import time class Button(object): """Class representing keyboard keys.""" def __init__(self, game, number): self.game = game self.number = number self.event = None # The last event that caused the button press self.pressed = 0 # If the button was just pressed self.held = 0 # If the button is held self.released = 0 # If the button was just released self.press_time = 0.0 def press(self): self.pressed = 1 self.held = 1 self.press_time = time.time() def release(self): self.held = 0 self.released = 1 def reset(self): self.pressed = 0 self.released = 0 def time_held(self): if self.held: return time.time() - self.press_time else: return 0.0 ## Instruction: Add docstring to Button.time_held() method ## Code After: import time class Button(object): """Class representing keyboard keys.""" def __init__(self, game, number): self.game = game self.number = number self.event = None # The last event that caused the button press self.pressed = 0 # If the button was just pressed self.held = 0 # If the button is held self.released = 0 # If the button was just released self.press_time = 0.0 def press(self): self.pressed = 1 self.held = 1 self.press_time = time.time() def release(self): self.held = 0 self.released = 1 def reset(self): self.pressed = 0 self.released = 0 def time_held(self) -> float: """Return the amount of time this button has been held for in seconds.""" if self.held: return time.time() - self.press_time else: return 0.0
... self.released = 0 def time_held(self) -> float: """Return the amount of time this button has been held for in seconds.""" if self.held: return time.time() - self.press_time ...
f0d3cf2bfcaa569f47eb888d5553659c5c57f07d
ajaximage/urls.py
ajaximage/urls.py
from django.conf.urls.defaults import url, patterns from ajaximage.views import ajaximage from ajaximage.forms import FileForm urlpatterns = patterns('', url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)', ajaximage, { 'form_class': FileForm, 'response': lambda name, url: url, }, name='ajaximage'), )
try:# pre 1.6 from django.conf.urls.defaults import url, patterns except ImportError: from django.conf.urls import url, patterns from ajaximage.views import ajaximage from ajaximage.forms import FileForm urlpatterns = patterns('', url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)', ajaximage, { 'form_class': FileForm, 'response': lambda name, url: url, }, name='ajaximage'), )
Fix import for 1.6 version.
Fix import for 1.6 version.
Python
mit
bradleyg/django-ajaximage,bradleyg/django-ajaximage,subhaoi/kioskuser,subhaoi/kioskuser,subhaoi/kioskuser,bradleyg/django-ajaximage
+ try:# pre 1.6 - from django.conf.urls.defaults import url, patterns + from django.conf.urls.defaults import url, patterns + except ImportError: + from django.conf.urls import url, patterns from ajaximage.views import ajaximage from ajaximage.forms import FileForm urlpatterns = patterns('', url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)', ajaximage, { 'form_class': FileForm, 'response': lambda name, url: url, }, name='ajaximage'), )
Fix import for 1.6 version.
## Code Before: from django.conf.urls.defaults import url, patterns from ajaximage.views import ajaximage from ajaximage.forms import FileForm urlpatterns = patterns('', url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)', ajaximage, { 'form_class': FileForm, 'response': lambda name, url: url, }, name='ajaximage'), ) ## Instruction: Fix import for 1.6 version. ## Code After: try:# pre 1.6 from django.conf.urls.defaults import url, patterns except ImportError: from django.conf.urls import url, patterns from ajaximage.views import ajaximage from ajaximage.forms import FileForm urlpatterns = patterns('', url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)', ajaximage, { 'form_class': FileForm, 'response': lambda name, url: url, }, name='ajaximage'), )
... try:# pre 1.6 from django.conf.urls.defaults import url, patterns except ImportError: from django.conf.urls import url, patterns from ajaximage.views import ajaximage ...
56bd6c6a0363323cc1f4b3fbbcd460ba446b0c6d
cubes/stores.py
cubes/stores.py
from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise CubesError("Unable to find store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise CubesError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise ConfigurationError("Unknown store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise ConfigurationError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
Raise ConfigurationError error that causes server to fail and dump whole stacktrace
Raise ConfigurationError error that causes server to fail and dump whole stacktrace
Python
mit
noyeitan/cubes,ubreddy/cubes,she11c0de/cubes,zejn/cubes,zejn/cubes,pombredanne/cubes,she11c0de/cubes,pombredanne/cubes,ubreddy/cubes,jell0720/cubes,cesarmarinhorj/cubes,noyeitan/cubes,ubreddy/cubes,cesarmarinhorj/cubes,cesarmarinhorj/cubes,zejn/cubes,jell0720/cubes,noyeitan/cubes,pombredanne/cubes,jell0720/cubes,she11c0de/cubes
from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: - raise CubesError("Unable to find store '%s'" % name) + raise ConfigurationError("Unknown store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: - raise CubesError("Unable to find browser of type '%s'" % type_) + raise ConfigurationError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
Raise ConfigurationError error that causes server to fail and dump whole stacktrace
## Code Before: from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise CubesError("Unable to find store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise CubesError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass ## Instruction: Raise ConfigurationError error that causes server to fail and dump whole stacktrace ## Code After: from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store") try: factory = ns[name] except KeyError: raise ConfigurationError("Unknown store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser") try: factory = ns[type_] except KeyError: raise ConfigurationError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass
# ... existing code ... factory = ns[name] except KeyError: raise ConfigurationError("Unknown store '%s'" % name) return factory(**options) # ... modified code ... factory = ns[type_] except KeyError: raise ConfigurationError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) # ... rest of the code ...
db9afab144c12391c9c54174b8973ec187455b9c
webpack/conf.py
webpack/conf.py
import os from optional_django import conf class Conf(conf.Conf): # Environment configuration STATIC_ROOT = None STATIC_URL = None BUILD_SERVER_URL = 'http://127.0.0.1:9009' OUTPUT_DIR = 'webpack_assets' CONFIG_DIRS = None CONTEXT = None # Watching WATCH = True # TODO: should default to False AGGREGATE_TIMEOUT = 200 POLL = None HMR = False # Caching CACHE = True CACHE_DIR = None def get_path_to_output_dir(self): return os.path.join(self.STATIC_ROOT, self.OUTPUT_DIR) def get_public_path(self): static_url = self.STATIC_URL if static_url and static_url.endswith('/'): static_url = static_url[0:-1] return '/'.join([static_url, self.OUTPUT_DIR]) settings = Conf()
import os from optional_django import conf class Conf(conf.Conf): # Environment configuration STATIC_ROOT = None STATIC_URL = None BUILD_SERVER_URL = 'http://127.0.0.1:9009' OUTPUT_DIR = 'webpack_assets' CONFIG_DIRS = None CONTEXT = None # Watching WATCH = False AGGREGATE_TIMEOUT = 200 POLL = None HMR = False # Caching CACHE = True CACHE_DIR = None def get_path_to_output_dir(self): return os.path.join(self.STATIC_ROOT, self.OUTPUT_DIR) def get_public_path(self): static_url = self.STATIC_URL if static_url and static_url.endswith('/'): static_url = static_url[0:-1] return '/'.join([static_url, self.OUTPUT_DIR]) settings = Conf()
WATCH now defaults to False
WATCH now defaults to False
Python
mit
markfinger/python-webpack,markfinger/python-webpack
import os from optional_django import conf class Conf(conf.Conf): # Environment configuration STATIC_ROOT = None STATIC_URL = None BUILD_SERVER_URL = 'http://127.0.0.1:9009' OUTPUT_DIR = 'webpack_assets' CONFIG_DIRS = None CONTEXT = None # Watching - WATCH = True # TODO: should default to False + WATCH = False AGGREGATE_TIMEOUT = 200 POLL = None HMR = False # Caching CACHE = True CACHE_DIR = None def get_path_to_output_dir(self): return os.path.join(self.STATIC_ROOT, self.OUTPUT_DIR) def get_public_path(self): static_url = self.STATIC_URL if static_url and static_url.endswith('/'): static_url = static_url[0:-1] return '/'.join([static_url, self.OUTPUT_DIR]) settings = Conf()
WATCH now defaults to False
## Code Before: import os from optional_django import conf class Conf(conf.Conf): # Environment configuration STATIC_ROOT = None STATIC_URL = None BUILD_SERVER_URL = 'http://127.0.0.1:9009' OUTPUT_DIR = 'webpack_assets' CONFIG_DIRS = None CONTEXT = None # Watching WATCH = True # TODO: should default to False AGGREGATE_TIMEOUT = 200 POLL = None HMR = False # Caching CACHE = True CACHE_DIR = None def get_path_to_output_dir(self): return os.path.join(self.STATIC_ROOT, self.OUTPUT_DIR) def get_public_path(self): static_url = self.STATIC_URL if static_url and static_url.endswith('/'): static_url = static_url[0:-1] return '/'.join([static_url, self.OUTPUT_DIR]) settings = Conf() ## Instruction: WATCH now defaults to False ## Code After: import os from optional_django import conf class Conf(conf.Conf): # Environment configuration STATIC_ROOT = None STATIC_URL = None BUILD_SERVER_URL = 'http://127.0.0.1:9009' OUTPUT_DIR = 'webpack_assets' CONFIG_DIRS = None CONTEXT = None # Watching WATCH = False AGGREGATE_TIMEOUT = 200 POLL = None HMR = False # Caching CACHE = True CACHE_DIR = None def get_path_to_output_dir(self): return os.path.join(self.STATIC_ROOT, self.OUTPUT_DIR) def get_public_path(self): static_url = self.STATIC_URL if static_url and static_url.endswith('/'): static_url = static_url[0:-1] return '/'.join([static_url, self.OUTPUT_DIR]) settings = Conf()
# ... existing code ... # Watching WATCH = False AGGREGATE_TIMEOUT = 200 POLL = None # ... rest of the code ...
0a850f935ce6cc48a68cffbef64c127daa22a42f
write.py
write.py
import colour import csv import json import os import pprint # write to file as json, csv, markdown, plaintext or print table def write_data(data, user, format=None): if format is not None: directory = './data/' if not os.path.exists(directory): os.makedirs(directory) f = open(directory + user + '.' + format, 'w') if format == 'json': f.write(json.dumps(data, indent=4)) elif format == 'csv': keys = data[0].keys() dw = csv.DictWriter(f, fieldnames=keys) dw.writeheader() dw.writerows(data) elif format == 'md': f.write('## %s - GitHub repositories\n' % user) for row in data: f.write( '#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) elif format == 'txt': f.write('%s - GitHub repositories\n\n' % user) for row in data: f.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) f.close()
import csv import json import os from tabulate import tabulate def write_data(d, u, f=None): if f is not None: directory = './data/' if not os.path.exists(directory): os.makedirs(directory) file = open(directory + u + '.' + f, 'w') if f == 'json': file.write(json.dumps(d, indent=4)) elif f == 'csv': keys = d[0].keys() dw = csv.DictWriter(file, fieldnames=keys) dw.writeheader() dw.writerows(d) elif f == 'md': file.write('## %s - GitHub repositories\n' % u) for row in d: file.write( '#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) elif f == 'txt': file.write('%s - GitHub repositories\n\n' % u) for row in d: file.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) file.close() else: print(tabulate(d, headers="keys"))
Print table if no file format provided
Print table if no file format provided
Python
mit
kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list
- import colour import csv import json import os - import pprint + from tabulate import tabulate - # write to file as json, csv, markdown, plaintext or print table - - - def write_data(data, user, format=None): + def write_data(d, u, f=None): - if format is not None: + if f is not None: directory = './data/' if not os.path.exists(directory): os.makedirs(directory) - f = open(directory + user + '.' + format, 'w') + file = open(directory + u + '.' + f, 'w') - if format == 'json': + if f == 'json': - f.write(json.dumps(data, indent=4)) + file.write(json.dumps(d, indent=4)) - elif format == 'csv': + elif f == 'csv': - keys = data[0].keys() + keys = d[0].keys() - dw = csv.DictWriter(f, fieldnames=keys) + dw = csv.DictWriter(file, fieldnames=keys) dw.writeheader() - dw.writerows(data) + dw.writerows(d) - elif format == 'md': + elif f == 'md': - f.write('## %s - GitHub repositories\n' % user) + file.write('## %s - GitHub repositories\n' % u) - for row in data: + for row in d: - f.write( + file.write( '#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) - elif format == 'txt': + elif f == 'txt': - f.write('%s - GitHub repositories\n\n' % user) + file.write('%s - GitHub repositories\n\n' % u) - for row in data: + for row in d: - f.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'], + file.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'], - row['desc'], + row['desc'], - row['lang'], + row['lang'], - row['stars'])) + row['stars'])) + file.close() + else: + print(tabulate(d, headers="keys")) - f.close() -
Print table if no file format provided
## Code Before: import colour import csv import json import os import pprint # write to file as json, csv, markdown, plaintext or print table def write_data(data, user, format=None): if format is not None: directory = './data/' if not os.path.exists(directory): os.makedirs(directory) f = open(directory + user + '.' + format, 'w') if format == 'json': f.write(json.dumps(data, indent=4)) elif format == 'csv': keys = data[0].keys() dw = csv.DictWriter(f, fieldnames=keys) dw.writeheader() dw.writerows(data) elif format == 'md': f.write('## %s - GitHub repositories\n' % user) for row in data: f.write( '#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) elif format == 'txt': f.write('%s - GitHub repositories\n\n' % user) for row in data: f.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) f.close() ## Instruction: Print table if no file format provided ## Code After: import csv import json import os from tabulate import tabulate def write_data(d, u, f=None): if f is not None: directory = './data/' if not os.path.exists(directory): os.makedirs(directory) file = open(directory + u + '.' + f, 'w') if f == 'json': file.write(json.dumps(d, indent=4)) elif f == 'csv': keys = d[0].keys() dw = csv.DictWriter(file, fieldnames=keys) dw.writeheader() dw.writerows(d) elif f == 'md': file.write('## %s - GitHub repositories\n' % u) for row in d: file.write( '#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) elif f == 'txt': file.write('%s - GitHub repositories\n\n' % u) for row in d: file.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) file.close() else: print(tabulate(d, headers="keys"))
# ... existing code ... import csv import json import os from tabulate import tabulate def write_data(d, u, f=None): if f is not None: directory = './data/' # ... modified code ... os.makedirs(directory) file = open(directory + u + '.' + f, 'w') if f == 'json': file.write(json.dumps(d, indent=4)) elif f == 'csv': keys = d[0].keys() dw = csv.DictWriter(file, fieldnames=keys) dw.writeheader() dw.writerows(d) elif f == 'md': file.write('## %s - GitHub repositories\n' % u) for row in d: file.write( '#### {}\n\n{} \n_{}_, {} star(s)\n\n'.format(row['name'], row['desc'], ... row['lang'], row['stars'])) elif f == 'txt': file.write('%s - GitHub repositories\n\n' % u) for row in d: file.write('{}\n{}\n{}, {} star(s)\n\n'.format(row['name'], row['desc'], row['lang'], row['stars'])) file.close() else: print(tabulate(d, headers="keys")) # ... rest of the code ...
0c753e644068439376493e4b23a1060d742770ae
tests/__main__.py
tests/__main__.py
import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') unittest.TextTestRunner().run(all_tests)
import sys import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() sys.exit(ret)
Fix an issue when unit tests always return 0 status.
Fix an issue when unit tests always return 0 status.
Python
mit
sergeymironov0001/twitch-chat-bot
+ import sys import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') - unittest.TextTestRunner().run(all_tests) + ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() + sys.exit(ret)
Fix an issue when unit tests always return 0 status.
## Code Before: import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') unittest.TextTestRunner().run(all_tests) ## Instruction: Fix an issue when unit tests always return 0 status. ## Code After: import sys import unittest if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() sys.exit(ret)
// ... existing code ... import sys import unittest // ... modified code ... if __name__ == '__main__': all_tests = unittest.TestLoader().discover('./', pattern='*_tests.py') ret = unittest.TextTestRunner().run(all_tests).wasSuccessful() sys.exit(ret) // ... rest of the code ...
e72ab305e2a90433c07300f37f7ae6fa2901b9cc
app/auth/views.py
app/auth/views.py
from flask import render_template, redirect, request, url_for, flash from flask.ext.login import login_user, logout_user, login_required, \ current_user from . import auth from .forms import LoginForm, RegistrationForm from .. import db from ..models import User @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None: login_user(user) return redirect(request.args.get('next') or url_for('main.index')) flash('Invalid username or password.') return render_template('login.html', form=form) @auth.route('/logout') # @login_required def logout(): logout_user() flash('You have been logged out.') return redirect(url_for('main.index')) @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() flash('You successfully registered. Welcome!') return redirect(url_for('auth.login')) return render_template('register.html', form=form)
from flask import render_template, redirect, request, url_for, flash from flask.ext.login import login_user, logout_user, login_required, \ current_user from . import auth from .forms import LoginForm, RegistrationForm from ..models import User @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None: login_user(user) return redirect(request.args.get('next') or url_for('main.index')) flash('Invalid username or password.') return render_template('login.html', form=form) @auth.route('/logout') # @login_required def logout(): logout_user() flash('You have been logged out.') return redirect(url_for('main.index')) @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) user.save() flash('You successfully registered. Welcome!') return redirect(url_for('auth.login')) return render_template('register.html', form=form)
Use newly added save on new users.
Use newly added save on new users.
Python
mit
guillaumededrie/flask-todolist,poulp/flask-todolist,guillaumededrie/flask-todolist,rtzll/flask-todolist,0xfoo/flask-todolist,polyfunc/flask-todolist,poulp/flask-todolist,rtzll/flask-todolist,polyfunc/flask-todolist,guillaumededrie/flask-todolist,0xfoo/flask-todolist,poulp/flask-todolist,0xfoo/flask-todolist,polyfunc/flask-todolist,rtzll/flask-todolist,rtzll/flask-todolist
from flask import render_template, redirect, request, url_for, flash from flask.ext.login import login_user, logout_user, login_required, \ current_user from . import auth from .forms import LoginForm, RegistrationForm - from .. import db from ..models import User @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None: login_user(user) return redirect(request.args.get('next') or url_for('main.index')) flash('Invalid username or password.') return render_template('login.html', form=form) @auth.route('/logout') # @login_required def logout(): logout_user() flash('You have been logged out.') return redirect(url_for('main.index')) @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) + user.save() - db.session.add(user) - db.session.commit() flash('You successfully registered. Welcome!') return redirect(url_for('auth.login')) return render_template('register.html', form=form)
Use newly added save on new users.
## Code Before: from flask import render_template, redirect, request, url_for, flash from flask.ext.login import login_user, logout_user, login_required, \ current_user from . import auth from .forms import LoginForm, RegistrationForm from .. import db from ..models import User @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None: login_user(user) return redirect(request.args.get('next') or url_for('main.index')) flash('Invalid username or password.') return render_template('login.html', form=form) @auth.route('/logout') # @login_required def logout(): logout_user() flash('You have been logged out.') return redirect(url_for('main.index')) @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) db.session.add(user) db.session.commit() flash('You successfully registered. Welcome!') return redirect(url_for('auth.login')) return render_template('register.html', form=form) ## Instruction: Use newly added save on new users. ## Code After: from flask import render_template, redirect, request, url_for, flash from flask.ext.login import login_user, logout_user, login_required, \ current_user from . import auth from .forms import LoginForm, RegistrationForm from ..models import User @auth.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None: login_user(user) return redirect(request.args.get('next') or url_for('main.index')) flash('Invalid username or password.') return render_template('login.html', form=form) @auth.route('/logout') # @login_required def logout(): logout_user() flash('You have been logged out.') return redirect(url_for('main.index')) @auth.route('/register', methods=['GET', 'POST']) def register(): form = RegistrationForm() if form.validate_on_submit(): user = User(email=form.email.data, username=form.username.data, password=form.password.data) user.save() flash('You successfully registered. Welcome!') return redirect(url_for('auth.login')) return render_template('register.html', form=form)
# ... existing code ... from . import auth from .forms import LoginForm, RegistrationForm from ..models import User # ... modified code ... username=form.username.data, password=form.password.data) user.save() flash('You successfully registered. Welcome!') return redirect(url_for('auth.login')) # ... rest of the code ...
1de05b64363d6a99cceb3b047813893915c0842b
pyetherscan/settings.py
pyetherscan/settings.py
import os TESTING_API_KEY = 'YourApiKeyToken' ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY)
import os HOME_DIR = os.path.expanduser('~') CONFIG_FILE = '.pyetherscan.ini' PATH = os.path.join(HOME_DIR, CONFIG_FILE) TESTING_API_KEY = 'YourApiKeyToken' if os.path.isfile(PATH): from configparser import ConfigParser config = ConfigParser() config.read(PATH) ETHERSCAN_API_KEY = config['Credentials']['ETHERSCAN_API_KEY'] else: ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY)
Add support for a configuration file
Add support for a configuration file
Python
mit
Marto32/pyetherscan
import os + HOME_DIR = os.path.expanduser('~') + CONFIG_FILE = '.pyetherscan.ini' + PATH = os.path.join(HOME_DIR, CONFIG_FILE) TESTING_API_KEY = 'YourApiKeyToken' - ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY) + if os.path.isfile(PATH): + from configparser import ConfigParser + config = ConfigParser() + config.read(PATH) + ETHERSCAN_API_KEY = config['Credentials']['ETHERSCAN_API_KEY'] + + else: + ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY) +
Add support for a configuration file
## Code Before: import os TESTING_API_KEY = 'YourApiKeyToken' ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY) ## Instruction: Add support for a configuration file ## Code After: import os HOME_DIR = os.path.expanduser('~') CONFIG_FILE = '.pyetherscan.ini' PATH = os.path.join(HOME_DIR, CONFIG_FILE) TESTING_API_KEY = 'YourApiKeyToken' if os.path.isfile(PATH): from configparser import ConfigParser config = ConfigParser() config.read(PATH) ETHERSCAN_API_KEY = config['Credentials']['ETHERSCAN_API_KEY'] else: ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY)
... import os HOME_DIR = os.path.expanduser('~') CONFIG_FILE = '.pyetherscan.ini' PATH = os.path.join(HOME_DIR, CONFIG_FILE) TESTING_API_KEY = 'YourApiKeyToken' if os.path.isfile(PATH): from configparser import ConfigParser config = ConfigParser() config.read(PATH) ETHERSCAN_API_KEY = config['Credentials']['ETHERSCAN_API_KEY'] else: ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY) ...
aa5bc77e78e82fbe63acf2fd8f6764a420f2e4e8
simuvex/procedures/stubs/caller.py
simuvex/procedures/stubs/caller.py
import simuvex ###################################### # Caller ###################################### class Caller(simuvex.SimProcedure): """ Caller stub. Creates a Ijk_Call exit to the specified function """ def run(self, target_addr=None): self.call(target_addr, [ ], self.after_call) def after_call(self): pass
import simuvex ###################################### # Caller ###################################### class Caller(simuvex.SimProcedure): """ Caller stub. Creates a Ijk_Call exit to the specified function """ NO_RET = True def run(self, target_addr=None): self.call(target_addr, [ ], self.after_call) def after_call(self): pass
Make sure Caller does not return
Make sure Caller does not return
Python
bsd-2-clause
axt/angr,chubbymaggie/angr,iamahuman/angr,tyb0807/angr,tyb0807/angr,chubbymaggie/angr,schieb/angr,iamahuman/angr,schieb/angr,angr/angr,angr/simuvex,iamahuman/angr,chubbymaggie/angr,axt/angr,angr/angr,chubbymaggie/simuvex,tyb0807/angr,angr/angr,f-prettyland/angr,f-prettyland/angr,axt/angr,schieb/angr,chubbymaggie/simuvex,chubbymaggie/simuvex,f-prettyland/angr
import simuvex ###################################### # Caller ###################################### class Caller(simuvex.SimProcedure): """ Caller stub. Creates a Ijk_Call exit to the specified function """ + NO_RET = True + def run(self, target_addr=None): self.call(target_addr, [ ], self.after_call) def after_call(self): pass
Make sure Caller does not return
## Code Before: import simuvex ###################################### # Caller ###################################### class Caller(simuvex.SimProcedure): """ Caller stub. Creates a Ijk_Call exit to the specified function """ def run(self, target_addr=None): self.call(target_addr, [ ], self.after_call) def after_call(self): pass ## Instruction: Make sure Caller does not return ## Code After: import simuvex ###################################### # Caller ###################################### class Caller(simuvex.SimProcedure): """ Caller stub. Creates a Ijk_Call exit to the specified function """ NO_RET = True def run(self, target_addr=None): self.call(target_addr, [ ], self.after_call) def after_call(self): pass
... """ NO_RET = True def run(self, target_addr=None): self.call(target_addr, [ ], self.after_call) ...
71c9235a7e48882fc8c1393e9527fea4531c536c
filter_plugins/fap.py
filter_plugins/fap.py
import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) class FilterModule(object): def filters(self): return {"site_code": site_code}
import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) # rest:https://restic.storage.tjoda.fap.no/rpi1.ldn.fap.no # rclone:Jotta:storage.tjoda.fap.no # /Volumes/storage/restic/kramacbook def restic_repo_friendly_name(repo: str) -> str: if "https://" in repo: repo = repo.replace("https://", "") print(repo) type_, address, *_ = repo.split(":") (r, *_) = address.split("/") return "_".join([type_, r]).replace(".", "_") elif ":" not in repo: # Most likely a file path type_ = "disk" path = list(filter(None, repo.split("/"))) if path[0] == "Volumes": return "_".join([type_, path[1]]) return "_".join([type_, repo.replace("/", "_")]) else: type_, *rest = repo.split(":") return "_".join([type_, rest[0]]) class FilterModule(object): def filters(self): return { "site_code": site_code, "restic_repo_friendly_name": restic_repo_friendly_name, }
Add really hacky way to reformat restic repos
Add really hacky way to reformat restic repos
Python
mit
kradalby/plays,kradalby/plays
import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) + # rest:https://restic.storage.tjoda.fap.no/rpi1.ldn.fap.no + # rclone:Jotta:storage.tjoda.fap.no + # /Volumes/storage/restic/kramacbook + def restic_repo_friendly_name(repo: str) -> str: + if "https://" in repo: + repo = repo.replace("https://", "") + print(repo) + type_, address, *_ = repo.split(":") + (r, *_) = address.split("/") + return "_".join([type_, r]).replace(".", "_") + elif ":" not in repo: + # Most likely a file path + type_ = "disk" + path = list(filter(None, repo.split("/"))) + if path[0] == "Volumes": + return "_".join([type_, path[1]]) + + return "_".join([type_, repo.replace("/", "_")]) + + else: + type_, *rest = repo.split(":") + return "_".join([type_, rest[0]]) + + class FilterModule(object): def filters(self): + return { - return {"site_code": site_code} + "site_code": site_code, + "restic_repo_friendly_name": restic_repo_friendly_name, + }
Add really hacky way to reformat restic repos
## Code Before: import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) class FilterModule(object): def filters(self): return {"site_code": site_code} ## Instruction: Add really hacky way to reformat restic repos ## Code After: import ipaddress def site_code(ipv4): # Verify IP address _ = ipaddress.ip_address(ipv4) segments = ipv4.split(".") return int(segments[1]) # rest:https://restic.storage.tjoda.fap.no/rpi1.ldn.fap.no # rclone:Jotta:storage.tjoda.fap.no # /Volumes/storage/restic/kramacbook def restic_repo_friendly_name(repo: str) -> str: if "https://" in repo: repo = repo.replace("https://", "") print(repo) type_, address, *_ = repo.split(":") (r, *_) = address.split("/") return "_".join([type_, r]).replace(".", "_") elif ":" not in repo: # Most likely a file path type_ = "disk" path = list(filter(None, repo.split("/"))) if path[0] == "Volumes": return "_".join([type_, path[1]]) return "_".join([type_, repo.replace("/", "_")]) else: type_, *rest = repo.split(":") return "_".join([type_, rest[0]]) class FilterModule(object): def filters(self): return { "site_code": site_code, "restic_repo_friendly_name": restic_repo_friendly_name, }
# ... existing code ... # rest:https://restic.storage.tjoda.fap.no/rpi1.ldn.fap.no # rclone:Jotta:storage.tjoda.fap.no # /Volumes/storage/restic/kramacbook def restic_repo_friendly_name(repo: str) -> str: if "https://" in repo: repo = repo.replace("https://", "") print(repo) type_, address, *_ = repo.split(":") (r, *_) = address.split("/") return "_".join([type_, r]).replace(".", "_") elif ":" not in repo: # Most likely a file path type_ = "disk" path = list(filter(None, repo.split("/"))) if path[0] == "Volumes": return "_".join([type_, path[1]]) return "_".join([type_, repo.replace("/", "_")]) else: type_, *rest = repo.split(":") return "_".join([type_, rest[0]]) class FilterModule(object): def filters(self): return { "site_code": site_code, "restic_repo_friendly_name": restic_repo_friendly_name, } # ... rest of the code ...
44a7c59d798d9a20d4d54b9cce7e56b8f88595cc
ch14/caesar.py
ch14/caesar.py
MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) key = int(input()) if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) try: key = int(input()) except ValueError: continue if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
Modify the code in the getKey() function so that it gracefully ignores non-integer input.
Modify the code in the getKey() function so that it gracefully ignores non-integer input.
Python
bsd-2-clause
aclogreco/InventGamesWP
MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) + try: - key = int(input()) + key = int(input()) + except ValueError: + continue if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
Modify the code in the getKey() function so that it gracefully ignores non-integer input.
## Code Before: MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) key = int(input()) if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key)) ## Instruction: Modify the code in the getKey() function so that it gracefully ignores non-integer input. ## Code After: MAX_KEY_SIZE = 26 def getMode(): while True: print('Do you wish to encrypt or decrypt a message?') mode = input().lower() if mode in 'encrypt e decrypt d'.split(): return mode else: print('Enter either "encrypt" or "e" or "decrypt" or "d".') def getMessage(): print('Enter your message:') return input() def getKey(): key = 0 while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) try: key = int(input()) except ValueError: continue if (key >= 1 and key <= MAX_KEY_SIZE): return key def getTranslatedMessage(mode, message, key): if mode[0] == 'd': key = -key translated = '' for symbol in message: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 translated += chr(num) else: translated += symbol return translated mode = getMode() message = getMessage() key = getKey() print('Your translated text is:') print(getTranslatedMessage(mode, message, key))
// ... existing code ... while True: print('Enter the key number (1-%s)' % (MAX_KEY_SIZE)) try: key = int(input()) except ValueError: continue if (key >= 1 and key <= MAX_KEY_SIZE): return key // ... rest of the code ...
7226e9ae349eadba10d8f23f81df0b4d70adb6a2
detectem/plugins/helpers.py
detectem/plugins/helpers.py
def meta_generator(name): return '//meta[@name="generator" and contains(@content, "{}")]' \ '/@content'.format(name)
def meta_generator(name): return '//meta[re:test(@name,"generator","i") and contains(@content, "{}")]' \ '/@content'.format(name)
Update meta_generator to match case insensitive
Update meta_generator to match case insensitive
Python
mit
spectresearch/detectem
def meta_generator(name): - return '//meta[@name="generator" and contains(@content, "{}")]' \ + return '//meta[re:test(@name,"generator","i") and contains(@content, "{}")]' \ '/@content'.format(name)
Update meta_generator to match case insensitive
## Code Before: def meta_generator(name): return '//meta[@name="generator" and contains(@content, "{}")]' \ '/@content'.format(name) ## Instruction: Update meta_generator to match case insensitive ## Code After: def meta_generator(name): return '//meta[re:test(@name,"generator","i") and contains(@content, "{}")]' \ '/@content'.format(name)
# ... existing code ... def meta_generator(name): return '//meta[re:test(@name,"generator","i") and contains(@content, "{}")]' \ '/@content'.format(name) # ... rest of the code ...
99bd91cac200f9e83ee710ac8758fd20ac1febfa
examples/find_facial_features_in_picture.py
examples/find_facial_features_in_picture.py
from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("biden.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) print("I found {} face(s) in this photograph.".format(len(face_landmarks_list))) for face_landmarks in face_landmarks_list: # Print the location of each facial feature in this image for facial_feature in face_landmarks.keys(): print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature])) # Let's trace out each facial feature in the image with a line! pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image) for facial_feature in face_landmarks.keys(): d.line(face_landmarks[facial_feature], width=5) pil_image.show()
from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("two_people.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) print("I found {} face(s) in this photograph.".format(len(face_landmarks_list))) # Create a PIL imagedraw object so we can draw on the picture pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image) for face_landmarks in face_landmarks_list: # Print the location of each facial feature in this image for facial_feature in face_landmarks.keys(): print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature])) # Let's trace out each facial feature in the image with a line! for facial_feature in face_landmarks.keys(): d.line(face_landmarks[facial_feature], width=5) # Show the picture pil_image.show()
Tweak demo to show multiple faces in one window instead of separate windows
Tweak demo to show multiple faces in one window instead of separate windows
Python
mit
ageitgey/face_recognition
from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array - image = face_recognition.load_image_file("biden.jpg") + image = face_recognition.load_image_file("two_people.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) print("I found {} face(s) in this photograph.".format(len(face_landmarks_list))) + + # Create a PIL imagedraw object so we can draw on the picture + pil_image = Image.fromarray(image) + d = ImageDraw.Draw(pil_image) for face_landmarks in face_landmarks_list: # Print the location of each facial feature in this image for facial_feature in face_landmarks.keys(): print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature])) # Let's trace out each facial feature in the image with a line! - pil_image = Image.fromarray(image) - d = ImageDraw.Draw(pil_image) - for facial_feature in face_landmarks.keys(): d.line(face_landmarks[facial_feature], width=5) + # Show the picture - pil_image.show() + pil_image.show()
Tweak demo to show multiple faces in one window instead of separate windows
## Code Before: from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("biden.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) print("I found {} face(s) in this photograph.".format(len(face_landmarks_list))) for face_landmarks in face_landmarks_list: # Print the location of each facial feature in this image for facial_feature in face_landmarks.keys(): print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature])) # Let's trace out each facial feature in the image with a line! pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image) for facial_feature in face_landmarks.keys(): d.line(face_landmarks[facial_feature], width=5) pil_image.show() ## Instruction: Tweak demo to show multiple faces in one window instead of separate windows ## Code After: from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("two_people.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) print("I found {} face(s) in this photograph.".format(len(face_landmarks_list))) # Create a PIL imagedraw object so we can draw on the picture pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image) for face_landmarks in face_landmarks_list: # Print the location of each facial feature in this image for facial_feature in face_landmarks.keys(): print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature])) # Let's trace out each facial feature in the image with a line! for facial_feature in face_landmarks.keys(): d.line(face_landmarks[facial_feature], width=5) # Show the picture pil_image.show()
// ... existing code ... # Load the jpg file into a numpy array image = face_recognition.load_image_file("two_people.jpg") # Find all facial features in all the faces in the image // ... modified code ... print("I found {} face(s) in this photograph.".format(len(face_landmarks_list))) # Create a PIL imagedraw object so we can draw on the picture pil_image = Image.fromarray(image) d = ImageDraw.Draw(pil_image) for face_landmarks in face_landmarks_list: ... # Let's trace out each facial feature in the image with a line! for facial_feature in face_landmarks.keys(): d.line(face_landmarks[facial_feature], width=5) # Show the picture pil_image.show() // ... rest of the code ...
359445fa4d554d3dd2ba2cb2850af4b892d7090e
binder/tests/testapp/models/animal.py
binder/tests/testapp/models/animal.py
from django.db import models from binder.models import BinderModel # From the api docs: an animal with a name. We don't use the # CaseInsensitiveCharField because it's so much simpler to use # memory-backed sqlite than Postgres in the tests. Eventually we # might switch and require Postgres for tests, if we need many # Postgres-specific things. class Animal(BinderModel): name = models.TextField(max_length=64) zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) deleted = models.BooleanField(default=False) # Softdelete def __str__(self): return 'animal %d: %s' % (self.pk or 0, self.name) class Binder: history = True
from django.db import models from binder.models import BinderModel from binder.exceptions import BinderValidationError # From the api docs: an animal with a name. We don't use the # CaseInsensitiveCharField because it's so much simpler to use # memory-backed sqlite than Postgres in the tests. Eventually we # might switch and require Postgres for tests, if we need many # Postgres-specific things. class Animal(BinderModel): name = models.TextField(max_length=64) zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) deleted = models.BooleanField(default=False) # Softdelete def __str__(self): return 'animal %d: %s' % (self.pk or 0, self.name) def _binder_unset_relation_caretaker(self): raise BinderValidationError({'animal': {self.pk: {'caretaker': [{ 'code': 'cant_unset', 'message': 'You can\'t unset zoo.', }]}}}) class Binder: history = True
Add overridden behaviour to testapp.
Add overridden behaviour to testapp.
Python
mit
CodeYellowBV/django-binder
from django.db import models from binder.models import BinderModel + from binder.exceptions import BinderValidationError # From the api docs: an animal with a name. We don't use the # CaseInsensitiveCharField because it's so much simpler to use # memory-backed sqlite than Postgres in the tests. Eventually we # might switch and require Postgres for tests, if we need many # Postgres-specific things. class Animal(BinderModel): name = models.TextField(max_length=64) zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) deleted = models.BooleanField(default=False) # Softdelete def __str__(self): return 'animal %d: %s' % (self.pk or 0, self.name) + def _binder_unset_relation_caretaker(self): + raise BinderValidationError({'animal': {self.pk: {'caretaker': [{ + 'code': 'cant_unset', + 'message': 'You can\'t unset zoo.', + }]}}}) + class Binder: history = True
Add overridden behaviour to testapp.
## Code Before: from django.db import models from binder.models import BinderModel # From the api docs: an animal with a name. We don't use the # CaseInsensitiveCharField because it's so much simpler to use # memory-backed sqlite than Postgres in the tests. Eventually we # might switch and require Postgres for tests, if we need many # Postgres-specific things. class Animal(BinderModel): name = models.TextField(max_length=64) zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) deleted = models.BooleanField(default=False) # Softdelete def __str__(self): return 'animal %d: %s' % (self.pk or 0, self.name) class Binder: history = True ## Instruction: Add overridden behaviour to testapp. ## Code After: from django.db import models from binder.models import BinderModel from binder.exceptions import BinderValidationError # From the api docs: an animal with a name. We don't use the # CaseInsensitiveCharField because it's so much simpler to use # memory-backed sqlite than Postgres in the tests. Eventually we # might switch and require Postgres for tests, if we need many # Postgres-specific things. class Animal(BinderModel): name = models.TextField(max_length=64) zoo = models.ForeignKey('Zoo', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) caretaker = models.ForeignKey('Caretaker', on_delete=models.CASCADE, related_name='animals', blank=True, null=True) deleted = models.BooleanField(default=False) # Softdelete def __str__(self): return 'animal %d: %s' % (self.pk or 0, self.name) def _binder_unset_relation_caretaker(self): raise BinderValidationError({'animal': {self.pk: {'caretaker': [{ 'code': 'cant_unset', 'message': 'You can\'t unset zoo.', }]}}}) class Binder: history = True
// ... existing code ... from django.db import models from binder.models import BinderModel from binder.exceptions import BinderValidationError # From the api docs: an animal with a name. We don't use the // ... modified code ... return 'animal %d: %s' % (self.pk or 0, self.name) def _binder_unset_relation_caretaker(self): raise BinderValidationError({'animal': {self.pk: {'caretaker': [{ 'code': 'cant_unset', 'message': 'You can\'t unset zoo.', }]}}}) class Binder: history = True // ... rest of the code ...
356257d3a0db07548c2efe0694c2fb210900b38a
keystoneclient/exceptions.py
keystoneclient/exceptions.py
#flake8: noqa from keystoneclient.apiclient.exceptions import *
#flake8: noqa from keystoneclient.apiclient.exceptions import * class CertificateConfigError(Exception): """Error reading the certificate""" def __init__(self, output): self.output = output msg = ("Unable to load certificate. " "Ensure your system is configured properly.") super(CertificateConfigError, self).__init__(msg)
Migrate the keystone.common.cms to keystoneclient
Migrate the keystone.common.cms to keystoneclient - Add checking the openssl return code 2, related to following review https://review.openstack.org/#/c/22716/ - Add support set subprocess to the cms, when we already know which subprocess to use. Closes-Bug: #1142574 Change-Id: I3f86e6ca8bb7738f57051ce7f0f5662b20e7a22b
Python
apache-2.0
citrix-openstack-build/keystoneauth,jamielennox/keystoneauth,sileht/keystoneauth
#flake8: noqa from keystoneclient.apiclient.exceptions import * + + class CertificateConfigError(Exception): + """Error reading the certificate""" + def __init__(self, output): + self.output = output + msg = ("Unable to load certificate. " + "Ensure your system is configured properly.") + super(CertificateConfigError, self).__init__(msg) +
Migrate the keystone.common.cms to keystoneclient
## Code Before: #flake8: noqa from keystoneclient.apiclient.exceptions import * ## Instruction: Migrate the keystone.common.cms to keystoneclient ## Code After: #flake8: noqa from keystoneclient.apiclient.exceptions import * class CertificateConfigError(Exception): """Error reading the certificate""" def __init__(self, output): self.output = output msg = ("Unable to load certificate. " "Ensure your system is configured properly.") super(CertificateConfigError, self).__init__(msg)
// ... existing code ... #flake8: noqa from keystoneclient.apiclient.exceptions import * class CertificateConfigError(Exception): """Error reading the certificate""" def __init__(self, output): self.output = output msg = ("Unable to load certificate. " "Ensure your system is configured properly.") super(CertificateConfigError, self).__init__(msg) // ... rest of the code ...
e6f85eb50ea1de37ba0f2c4ad75997a9da3879a0
changes/api/jobphase_index.py
changes/api/jobphase_index.py
from __future__ import absolute_import from flask import Response from sqlalchemy.orm import joinedload, subqueryload_all from changes.api.base import APIView from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer from changes.models import Job, JobPhase, JobStep class JobPhaseIndexAPIView(APIView): def get(self, job_id): job = Job.query.options( subqueryload_all(Job.phases), joinedload(Job.project), joinedload(Job.author), ).get(job_id) if job is None: return Response(status=404) phase_list = list(JobPhase.query.options( subqueryload_all(JobPhase.steps, JobStep.node), ).filter( JobPhase.job_id == job.id, )) return self.respond(self.serialize(phase_list, { JobPhase: JobPhaseWithStepsSerializer(), })) def get_stream_channels(self, job_id): return [ 'jobs:{0}'.format(job_id), 'testgroups:{0}:*'.format(job_id), 'logsources:{0}:*'.format(job_id), ]
from __future__ import absolute_import from flask import Response from sqlalchemy.orm import joinedload, subqueryload_all from changes.api.base import APIView from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer from changes.models import Job, JobPhase, JobStep class JobPhaseIndexAPIView(APIView): def get(self, job_id): job = Job.query.options( subqueryload_all(Job.phases), joinedload(Job.project), joinedload(Job.author), ).get(job_id) if job is None: return Response(status=404) phase_list = list(JobPhase.query.options( subqueryload_all(JobPhase.steps, JobStep.node), ).filter( JobPhase.job_id == job.id, ).order_by(JobPhase.date_started.asc(), JobPhase.date_created.asc())) return self.respond(self.serialize(phase_list, { JobPhase: JobPhaseWithStepsSerializer(), })) def get_stream_channels(self, job_id): return [ 'jobs:{0}'.format(job_id), 'testgroups:{0}:*'.format(job_id), 'logsources:{0}:*'.format(job_id), ]
Order JobPhase by date started, date created
Order JobPhase by date started, date created
Python
apache-2.0
bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes
from __future__ import absolute_import from flask import Response from sqlalchemy.orm import joinedload, subqueryload_all from changes.api.base import APIView from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer from changes.models import Job, JobPhase, JobStep class JobPhaseIndexAPIView(APIView): def get(self, job_id): job = Job.query.options( subqueryload_all(Job.phases), joinedload(Job.project), joinedload(Job.author), ).get(job_id) if job is None: return Response(status=404) phase_list = list(JobPhase.query.options( subqueryload_all(JobPhase.steps, JobStep.node), ).filter( JobPhase.job_id == job.id, - )) + ).order_by(JobPhase.date_started.asc(), JobPhase.date_created.asc())) return self.respond(self.serialize(phase_list, { JobPhase: JobPhaseWithStepsSerializer(), })) def get_stream_channels(self, job_id): return [ 'jobs:{0}'.format(job_id), 'testgroups:{0}:*'.format(job_id), 'logsources:{0}:*'.format(job_id), ]
Order JobPhase by date started, date created
## Code Before: from __future__ import absolute_import from flask import Response from sqlalchemy.orm import joinedload, subqueryload_all from changes.api.base import APIView from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer from changes.models import Job, JobPhase, JobStep class JobPhaseIndexAPIView(APIView): def get(self, job_id): job = Job.query.options( subqueryload_all(Job.phases), joinedload(Job.project), joinedload(Job.author), ).get(job_id) if job is None: return Response(status=404) phase_list = list(JobPhase.query.options( subqueryload_all(JobPhase.steps, JobStep.node), ).filter( JobPhase.job_id == job.id, )) return self.respond(self.serialize(phase_list, { JobPhase: JobPhaseWithStepsSerializer(), })) def get_stream_channels(self, job_id): return [ 'jobs:{0}'.format(job_id), 'testgroups:{0}:*'.format(job_id), 'logsources:{0}:*'.format(job_id), ] ## Instruction: Order JobPhase by date started, date created ## Code After: from __future__ import absolute_import from flask import Response from sqlalchemy.orm import joinedload, subqueryload_all from changes.api.base import APIView from changes.api.serializer.models.jobphase import JobPhaseWithStepsSerializer from changes.models import Job, JobPhase, JobStep class JobPhaseIndexAPIView(APIView): def get(self, job_id): job = Job.query.options( subqueryload_all(Job.phases), joinedload(Job.project), joinedload(Job.author), ).get(job_id) if job is None: return Response(status=404) phase_list = list(JobPhase.query.options( subqueryload_all(JobPhase.steps, JobStep.node), ).filter( JobPhase.job_id == job.id, ).order_by(JobPhase.date_started.asc(), JobPhase.date_created.asc())) return self.respond(self.serialize(phase_list, { JobPhase: JobPhaseWithStepsSerializer(), })) def get_stream_channels(self, job_id): return [ 'jobs:{0}'.format(job_id), 'testgroups:{0}:*'.format(job_id), 'logsources:{0}:*'.format(job_id), ]
... ).filter( JobPhase.job_id == job.id, ).order_by(JobPhase.date_started.asc(), JobPhase.date_created.asc())) return self.respond(self.serialize(phase_list, { ...
390fc84183c0f680c5fb1a980ee3c1227b187611
HowLong/HowLong.py
HowLong/HowLong.py
import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): print("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 print(red(str(timedelta(milliseconds=elapsed_time)))) print("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong()
from __future__ import print_function import sys import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END def log(*args): print(*args, file=sys.stderr) sys.stderr.flush() class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): log("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 log(red(str(timedelta(milliseconds=elapsed_time)))) log("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong()
Print debug info to stderr
MINOR: Print debug info to stderr
Python
apache-2.0
mattjegan/HowLong
- + from __future__ import print_function + import sys import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END + + + def log(*args): + print(*args, file=sys.stderr) + sys.stderr.flush() class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): - print("Running", self.readable_command) + log("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 - print(red(str(timedelta(milliseconds=elapsed_time)))) + log(red(str(timedelta(milliseconds=elapsed_time)))) - print("Finished", self.readable_command) + log("Finished", self.readable_command) + def howlong(): HowLong().run() + if __name__ == "__main__": howlong()
Print debug info to stderr
## Code Before: import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): print("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 print(red(str(timedelta(milliseconds=elapsed_time)))) print("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong() ## Instruction: Print debug info to stderr ## Code After: from __future__ import print_function import sys import argparse from datetime import timedelta from subprocess import Popen from time import time, sleep def red(text): RED = '\033[91m' END = '\033[0m' return RED + text + END def log(*args): print(*args, file=sys.stderr) sys.stderr.flush() class HowLong(object): def __init__(self): parser = argparse.ArgumentParser(description='Time a process') parser.add_argument('-i', type=float, nargs='?', metavar='interval', help='the timer interval, defaults to 1 second') parser.add_argument('command', metavar='C', type=str, nargs='+', help='a valid command') self.parsed_args = parser.parse_args() self.timer_interval = self.parsed_args.i if self.parsed_args.i else 1 self.readable_command = " ".join(self.parsed_args.command) def run(self): log("Running", self.readable_command) process = Popen(self.parsed_args.command) start_time = time() while process.poll() is None: sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 log(red(str(timedelta(milliseconds=elapsed_time)))) log("Finished", self.readable_command) def howlong(): HowLong().run() if __name__ == "__main__": howlong()
# ... existing code ... from __future__ import print_function import sys import argparse from datetime import timedelta # ... modified code ... END = '\033[0m' return RED + text + END def log(*args): print(*args, file=sys.stderr) sys.stderr.flush() ... def run(self): log("Running", self.readable_command) process = Popen(self.parsed_args.command) ... sleep(self.timer_interval) elapsed_time = (time() - start_time) * 1000 log(red(str(timedelta(milliseconds=elapsed_time)))) log("Finished", self.readable_command) def howlong(): ... HowLong().run() if __name__ == "__main__": howlong() # ... rest of the code ...
378f3bf0bb2e05260b7cbeeb4a4637d7d3a7ca7c
workflows/consumers.py
workflows/consumers.py
from urllib.parse import parse_qs from channels import Group from channels.sessions import channel_session @channel_session def ws_add(message): message.reply_channel.send({"accept": True}) qs = parse_qs(message['query_string']) workflow_pk = qs['workflow_pk'][0] message.channel_session['workflow_pk'] = workflow_pk Group("workflow-{}".format(workflow_pk)).add(message.reply_channel) @channel_session def ws_disconnect(message): workflow_pk = message.channel_session['workflow_pk'] Group("workflow-{}".format(workflow_pk)).discard(message.reply_channel)
from urllib.parse import parse_qs from channels import Group from channels.sessions import channel_session @channel_session def ws_add(message): message.reply_channel.send({"accept": True}) qs = parse_qs(message['query_string']) workflow_pk = qs[b'workflow_pk'][0].decode('utf-8') message.channel_session['workflow_pk'] = workflow_pk Group("workflow-{}".format(workflow_pk)).add(message.reply_channel) @channel_session def ws_disconnect(message): workflow_pk = message.channel_session['workflow_pk'] Group("workflow-{}".format(workflow_pk)).discard(message.reply_channel)
Fix query string problem of comparing byte strings and unicode strings in py3
Fix query string problem of comparing byte strings and unicode strings in py3
Python
mit
xflows/clowdflows-backend,xflows/clowdflows-backend,xflows/clowdflows-backend,xflows/clowdflows-backend
from urllib.parse import parse_qs from channels import Group from channels.sessions import channel_session @channel_session def ws_add(message): message.reply_channel.send({"accept": True}) qs = parse_qs(message['query_string']) - workflow_pk = qs['workflow_pk'][0] + workflow_pk = qs[b'workflow_pk'][0].decode('utf-8') message.channel_session['workflow_pk'] = workflow_pk Group("workflow-{}".format(workflow_pk)).add(message.reply_channel) @channel_session def ws_disconnect(message): workflow_pk = message.channel_session['workflow_pk'] Group("workflow-{}".format(workflow_pk)).discard(message.reply_channel)
Fix query string problem of comparing byte strings and unicode strings in py3
## Code Before: from urllib.parse import parse_qs from channels import Group from channels.sessions import channel_session @channel_session def ws_add(message): message.reply_channel.send({"accept": True}) qs = parse_qs(message['query_string']) workflow_pk = qs['workflow_pk'][0] message.channel_session['workflow_pk'] = workflow_pk Group("workflow-{}".format(workflow_pk)).add(message.reply_channel) @channel_session def ws_disconnect(message): workflow_pk = message.channel_session['workflow_pk'] Group("workflow-{}".format(workflow_pk)).discard(message.reply_channel) ## Instruction: Fix query string problem of comparing byte strings and unicode strings in py3 ## Code After: from urllib.parse import parse_qs from channels import Group from channels.sessions import channel_session @channel_session def ws_add(message): message.reply_channel.send({"accept": True}) qs = parse_qs(message['query_string']) workflow_pk = qs[b'workflow_pk'][0].decode('utf-8') message.channel_session['workflow_pk'] = workflow_pk Group("workflow-{}".format(workflow_pk)).add(message.reply_channel) @channel_session def ws_disconnect(message): workflow_pk = message.channel_session['workflow_pk'] Group("workflow-{}".format(workflow_pk)).discard(message.reply_channel)
# ... existing code ... message.reply_channel.send({"accept": True}) qs = parse_qs(message['query_string']) workflow_pk = qs[b'workflow_pk'][0].decode('utf-8') message.channel_session['workflow_pk'] = workflow_pk Group("workflow-{}".format(workflow_pk)).add(message.reply_channel) # ... rest of the code ...
74eb842870424a22334fee35881f1b6c877da8e6
scot/backend_mne.py
scot/backend_mne.py
"""Use mne-python routines as backend.""" from __future__ import absolute_import import scipy as sp from . import datatools from . import backend from . import backend_builtin as builtin def generate(): from mne.preprocessing.infomax_ import infomax def wrapper_infomax(data, random_state=None): """Call Infomax for ICA calculation.""" u = infomax(datatools.cat_trials(data).T, extended=True, random_state=random_state).T m = sp.linalg.pinv(u) return m, u def wrapper_csp(x, cl, reducedim): """Call MNE CSP algorithm.""" from mne.decoding import CSP csp = CSP(n_components=reducedim, cov_est="epoch") csp.fit(x, cl) c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :] y = datatools.dot_special(c.T, x) return c, d, y backend = builtin.generate() backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp}) return backend backend.register('mne', generate)
"""Use mne-python routines as backend.""" from __future__ import absolute_import import scipy as sp from . import datatools from . import backend from . import backend_builtin as builtin def generate(): from mne.preprocessing.infomax_ import infomax def wrapper_infomax(data, random_state=None): """Call Infomax for ICA calculation.""" u = infomax(datatools.cat_trials(data).T, extended=True, random_state=random_state).T m = sp.linalg.pinv(u) return m, u def wrapper_csp(x, cl, reducedim): """Call MNE CSP algorithm.""" from mne.decoding import CSP csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf") csp.fit(x, cl) c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :] y = datatools.dot_special(c.T, x) return c, d, y backend = builtin.generate() backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp}) return backend backend.register('mne', generate)
Use regularized covariance in CSP by default
Use regularized covariance in CSP by default
Python
mit
scot-dev/scot,cbrnr/scot,mbillingr/SCoT,cbrnr/scot,scot-dev/scot,cle1109/scot,cle1109/scot,mbillingr/SCoT
"""Use mne-python routines as backend.""" from __future__ import absolute_import import scipy as sp from . import datatools from . import backend from . import backend_builtin as builtin def generate(): from mne.preprocessing.infomax_ import infomax def wrapper_infomax(data, random_state=None): """Call Infomax for ICA calculation.""" u = infomax(datatools.cat_trials(data).T, extended=True, random_state=random_state).T m = sp.linalg.pinv(u) return m, u def wrapper_csp(x, cl, reducedim): """Call MNE CSP algorithm.""" from mne.decoding import CSP - csp = CSP(n_components=reducedim, cov_est="epoch") + csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf") csp.fit(x, cl) c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :] y = datatools.dot_special(c.T, x) return c, d, y backend = builtin.generate() backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp}) return backend backend.register('mne', generate)
Use regularized covariance in CSP by default
## Code Before: """Use mne-python routines as backend.""" from __future__ import absolute_import import scipy as sp from . import datatools from . import backend from . import backend_builtin as builtin def generate(): from mne.preprocessing.infomax_ import infomax def wrapper_infomax(data, random_state=None): """Call Infomax for ICA calculation.""" u = infomax(datatools.cat_trials(data).T, extended=True, random_state=random_state).T m = sp.linalg.pinv(u) return m, u def wrapper_csp(x, cl, reducedim): """Call MNE CSP algorithm.""" from mne.decoding import CSP csp = CSP(n_components=reducedim, cov_est="epoch") csp.fit(x, cl) c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :] y = datatools.dot_special(c.T, x) return c, d, y backend = builtin.generate() backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp}) return backend backend.register('mne', generate) ## Instruction: Use regularized covariance in CSP by default ## Code After: """Use mne-python routines as backend.""" from __future__ import absolute_import import scipy as sp from . import datatools from . import backend from . import backend_builtin as builtin def generate(): from mne.preprocessing.infomax_ import infomax def wrapper_infomax(data, random_state=None): """Call Infomax for ICA calculation.""" u = infomax(datatools.cat_trials(data).T, extended=True, random_state=random_state).T m = sp.linalg.pinv(u) return m, u def wrapper_csp(x, cl, reducedim): """Call MNE CSP algorithm.""" from mne.decoding import CSP csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf") csp.fit(x, cl) c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :] y = datatools.dot_special(c.T, x) return c, d, y backend = builtin.generate() backend.update({'ica': wrapper_infomax, 'csp': wrapper_csp}) return backend backend.register('mne', generate)
// ... existing code ... """Call MNE CSP algorithm.""" from mne.decoding import CSP csp = CSP(n_components=reducedim, cov_est="epoch", reg="ledoit_wolf") csp.fit(x, cl) c, d = csp.filters_.T[:, :reducedim], csp.patterns_[:reducedim, :] // ... rest of the code ...
2421212be1072db1428e7c832c0818a3928c1153
tests/test_collection_crs.py
tests/test_collection_crs.py
import os import re import fiona import fiona.crs from .conftest import WGS84PATTERN def test_collection_crs_wkt(path_coutwildrnp_shp): with fiona.open(path_coutwildrnp_shp) as src: assert re.match(WGS84PATTERN, src.crs_wkt) def test_collection_no_crs_wkt(tmpdir, path_coutwildrnp_shp): """crs members of a dataset with no crs can be accessed safely.""" filename = str(tmpdir.join("test.shp")) with fiona.open(path_coutwildrnp_shp) as src: profile = src.meta del profile['crs'] del profile['crs_wkt'] with fiona.open(filename, 'w', **profile) as dst: assert dst.crs_wkt == "" assert dst.crs == {}
import os import re import fiona import fiona.crs from .conftest import WGS84PATTERN def test_collection_crs_wkt(path_coutwildrnp_shp): with fiona.open(path_coutwildrnp_shp) as src: assert re.match(WGS84PATTERN, src.crs_wkt) def test_collection_no_crs_wkt(tmpdir, path_coutwildrnp_shp): """crs members of a dataset with no crs can be accessed safely.""" filename = str(tmpdir.join("test.shp")) with fiona.open(path_coutwildrnp_shp) as src: profile = src.meta del profile['crs'] del profile['crs_wkt'] with fiona.open(filename, 'w', **profile) as dst: assert dst.crs_wkt == "" assert dst.crs == {} def test_collection_create_crs_wkt(tmpdir): """A collection can be created using crs_wkt""" filename = str(tmpdir.join("test.shp")) wkt = 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]' with fiona.open(filename, 'w', schema={'geometry': 'Point', 'properties': {'foo': 'int'}}, crs_wkt=wkt, driver='GeoJSON') as dst: assert dst.crs_wkt == wkt with fiona.open(filename) as col: assert col.crs_wkt.startswith('GEOGCS["WGS 84')
Add test for collection creation with crs_wkt
Add test for collection creation with crs_wkt
Python
bsd-3-clause
Toblerity/Fiona,Toblerity/Fiona,rbuffat/Fiona,rbuffat/Fiona
import os import re import fiona import fiona.crs from .conftest import WGS84PATTERN + def test_collection_crs_wkt(path_coutwildrnp_shp): with fiona.open(path_coutwildrnp_shp) as src: assert re.match(WGS84PATTERN, src.crs_wkt) def test_collection_no_crs_wkt(tmpdir, path_coutwildrnp_shp): """crs members of a dataset with no crs can be accessed safely.""" filename = str(tmpdir.join("test.shp")) with fiona.open(path_coutwildrnp_shp) as src: profile = src.meta del profile['crs'] del profile['crs_wkt'] with fiona.open(filename, 'w', **profile) as dst: assert dst.crs_wkt == "" assert dst.crs == {} + + def test_collection_create_crs_wkt(tmpdir): + """A collection can be created using crs_wkt""" + filename = str(tmpdir.join("test.shp")) + wkt = 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]' + with fiona.open(filename, 'w', schema={'geometry': 'Point', 'properties': {'foo': 'int'}}, crs_wkt=wkt, driver='GeoJSON') as dst: + assert dst.crs_wkt == wkt + + with fiona.open(filename) as col: + assert col.crs_wkt.startswith('GEOGCS["WGS 84') +
Add test for collection creation with crs_wkt
## Code Before: import os import re import fiona import fiona.crs from .conftest import WGS84PATTERN def test_collection_crs_wkt(path_coutwildrnp_shp): with fiona.open(path_coutwildrnp_shp) as src: assert re.match(WGS84PATTERN, src.crs_wkt) def test_collection_no_crs_wkt(tmpdir, path_coutwildrnp_shp): """crs members of a dataset with no crs can be accessed safely.""" filename = str(tmpdir.join("test.shp")) with fiona.open(path_coutwildrnp_shp) as src: profile = src.meta del profile['crs'] del profile['crs_wkt'] with fiona.open(filename, 'w', **profile) as dst: assert dst.crs_wkt == "" assert dst.crs == {} ## Instruction: Add test for collection creation with crs_wkt ## Code After: import os import re import fiona import fiona.crs from .conftest import WGS84PATTERN def test_collection_crs_wkt(path_coutwildrnp_shp): with fiona.open(path_coutwildrnp_shp) as src: assert re.match(WGS84PATTERN, src.crs_wkt) def test_collection_no_crs_wkt(tmpdir, path_coutwildrnp_shp): """crs members of a dataset with no crs can be accessed safely.""" filename = str(tmpdir.join("test.shp")) with fiona.open(path_coutwildrnp_shp) as src: profile = src.meta del profile['crs'] del profile['crs_wkt'] with fiona.open(filename, 'w', **profile) as dst: assert dst.crs_wkt == "" assert dst.crs == {} def test_collection_create_crs_wkt(tmpdir): """A collection can be created using crs_wkt""" filename = str(tmpdir.join("test.shp")) wkt = 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]' with fiona.open(filename, 'w', schema={'geometry': 'Point', 'properties': {'foo': 'int'}}, crs_wkt=wkt, driver='GeoJSON') as dst: assert dst.crs_wkt == wkt with fiona.open(filename) as col: assert col.crs_wkt.startswith('GEOGCS["WGS 84')
... from .conftest import WGS84PATTERN def test_collection_crs_wkt(path_coutwildrnp_shp): ... assert dst.crs_wkt == "" assert dst.crs == {} def test_collection_create_crs_wkt(tmpdir): """A collection can be created using crs_wkt""" filename = str(tmpdir.join("test.shp")) wkt = 'GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_84",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295],AUTHORITY["EPSG","4326"]]' with fiona.open(filename, 'w', schema={'geometry': 'Point', 'properties': {'foo': 'int'}}, crs_wkt=wkt, driver='GeoJSON') as dst: assert dst.crs_wkt == wkt with fiona.open(filename) as col: assert col.crs_wkt.startswith('GEOGCS["WGS 84') ...
48f1d12f97be8a7bca60809967b88f77ba7d6393
setup.py
setup.py
from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="[email protected]", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="[email protected]", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
Use new Epsilon versioned feature.
Use new Epsilon versioned feature.
Python
mit
twisted/axiom,hawkowl/axiom
from distutils.core import setup + + import axiom distobj = setup( name="Axiom", - version="0.1", + version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="[email protected]", - url="http://divmod.org/trac/wiki/AxiomProject", + url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
Use new Epsilon versioned feature.
## Code Before: from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="[email protected]", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj) ## Instruction: Use new Epsilon versioned feature. ## Code After: from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="[email protected]", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
// ... existing code ... from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="[email protected]", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], // ... rest of the code ...
f2db056d4da23b96034f7c3ac5c4c12dd2853e91
luigi_slack/slack_api.py
luigi_slack/slack_api.py
import json from slackclient import SlackClient class SlackBotConf(object): def __init__(self): self.username = 'Luigi-slack Bot' class SlackAPI(object): def __init__(self, token, bot_conf=SlackBotConf()): self.client = SlackClient(token) self._all_channels = self._get_channels() self.bot = bot_conf def _get_channels(self): res = self.client.api_call('channels.list') _channels = json.loads(res.decode()) return _channels['channels'] def get_channels(self, reload_channels=False): if not self._all_channels or reload_channels: self._all_channels = self._get_channels() return self._all_channels def channel_name_to_id(self, names): name_to_id = [] for name in names: for channel in self._all_channels: if channel['name'] == name: name_to_id.append({'name': channel['name'], 'id': channel['id']}) return name_to_id def bulk_message(self, message, post_to=[]): channel_map = self.channel_name_to_id(post_to) for channel in channel_map: self.client.api_call('chat.postMessage', text=message, channel=channel['id'], username=self.bot.username) return True
import json from slackclient import SlackClient class SlackBotConf(object): def __init__(self): self.username = 'Luigi-slack Bot' class SlackAPI(object): def __init__(self, token, bot_conf=SlackBotConf()): self.client = SlackClient(token) self._all_channels = self._get_channels() self.bot = bot_conf def _get_channels(self): res = self.client.api_call('channels.list') _channels = json.loads(res.decode()) _parsed_channels = _channels.get('channels', None) if _parsed_channels is None: raise Exception("Could not get Slack channels. Are you sure your token is correct?") return _parsed_channels def get_channels(self, reload_channels=False): if not self._all_channels or reload_channels: self._all_channels = self._get_channels() return self._all_channels def channel_name_to_id(self, names): name_to_id = [] for name in names: for channel in self._all_channels: if channel['name'] == name: name_to_id.append({'name': channel['name'], 'id': channel['id']}) return name_to_id def bulk_message(self, message, post_to=[]): channel_map = self.channel_name_to_id(post_to) for channel in channel_map: self.client.api_call('chat.postMessage', text=message, channel=channel['id'], username=self.bot.username) return True
Validate token when fetching channels
Validate token when fetching channels
Python
mit
bonzanini/luigi-slack
import json from slackclient import SlackClient class SlackBotConf(object): def __init__(self): self.username = 'Luigi-slack Bot' class SlackAPI(object): def __init__(self, token, bot_conf=SlackBotConf()): self.client = SlackClient(token) self._all_channels = self._get_channels() self.bot = bot_conf def _get_channels(self): res = self.client.api_call('channels.list') _channels = json.loads(res.decode()) - return _channels['channels'] + _parsed_channels = _channels.get('channels', None) + if _parsed_channels is None: + raise Exception("Could not get Slack channels. Are you sure your token is correct?") + return _parsed_channels def get_channels(self, reload_channels=False): if not self._all_channels or reload_channels: self._all_channels = self._get_channels() return self._all_channels def channel_name_to_id(self, names): name_to_id = [] for name in names: for channel in self._all_channels: if channel['name'] == name: name_to_id.append({'name': channel['name'], 'id': channel['id']}) return name_to_id def bulk_message(self, message, post_to=[]): channel_map = self.channel_name_to_id(post_to) for channel in channel_map: self.client.api_call('chat.postMessage', text=message, channel=channel['id'], username=self.bot.username) return True
Validate token when fetching channels
## Code Before: import json from slackclient import SlackClient class SlackBotConf(object): def __init__(self): self.username = 'Luigi-slack Bot' class SlackAPI(object): def __init__(self, token, bot_conf=SlackBotConf()): self.client = SlackClient(token) self._all_channels = self._get_channels() self.bot = bot_conf def _get_channels(self): res = self.client.api_call('channels.list') _channels = json.loads(res.decode()) return _channels['channels'] def get_channels(self, reload_channels=False): if not self._all_channels or reload_channels: self._all_channels = self._get_channels() return self._all_channels def channel_name_to_id(self, names): name_to_id = [] for name in names: for channel in self._all_channels: if channel['name'] == name: name_to_id.append({'name': channel['name'], 'id': channel['id']}) return name_to_id def bulk_message(self, message, post_to=[]): channel_map = self.channel_name_to_id(post_to) for channel in channel_map: self.client.api_call('chat.postMessage', text=message, channel=channel['id'], username=self.bot.username) return True ## Instruction: Validate token when fetching channels ## Code After: import json from slackclient import SlackClient class SlackBotConf(object): def __init__(self): self.username = 'Luigi-slack Bot' class SlackAPI(object): def __init__(self, token, bot_conf=SlackBotConf()): self.client = SlackClient(token) self._all_channels = self._get_channels() self.bot = bot_conf def _get_channels(self): res = self.client.api_call('channels.list') _channels = json.loads(res.decode()) _parsed_channels = _channels.get('channels', None) if _parsed_channels is None: raise Exception("Could not get Slack channels. Are you sure your token is correct?") return _parsed_channels def get_channels(self, reload_channels=False): if not self._all_channels or reload_channels: self._all_channels = self._get_channels() return self._all_channels def channel_name_to_id(self, names): name_to_id = [] for name in names: for channel in self._all_channels: if channel['name'] == name: name_to_id.append({'name': channel['name'], 'id': channel['id']}) return name_to_id def bulk_message(self, message, post_to=[]): channel_map = self.channel_name_to_id(post_to) for channel in channel_map: self.client.api_call('chat.postMessage', text=message, channel=channel['id'], username=self.bot.username) return True
// ... existing code ... res = self.client.api_call('channels.list') _channels = json.loads(res.decode()) _parsed_channels = _channels.get('channels', None) if _parsed_channels is None: raise Exception("Could not get Slack channels. Are you sure your token is correct?") return _parsed_channels def get_channels(self, reload_channels=False): // ... rest of the code ...
47b3d205931d6ee7fa8062b3e2f01d1ea07df11a
pathvalidate/_error.py
pathvalidate/_error.py
from __future__ import absolute_import from __future__ import unicode_literals class NullNameError(ValueError): """ Raised when a name is empty. """ class InvalidCharError(ValueError): """ Raised when includes invalid character(s) within a string. """ class InvalidCharWindowsError(InvalidCharError): """ Raised when includes Windows specific invalid character(s) within a string. """ class InvalidLengthError(ValueError): """ Raised when a string too long/short. """ class ReservedNameError(ValueError): """ Raised when a string is matched a reserved name. """
from __future__ import absolute_import from __future__ import unicode_literals class InvalidNameError(ValueError): """ Base class of invalid name error. """ class NullNameError(InvalidNameError): """ Raised when a name is empty. """ class InvalidCharError(InvalidNameError): """ Raised when includes invalid character(s) within a string. """ class InvalidCharWindowsError(InvalidCharError): """ Raised when includes Windows specific invalid character(s) within a string. """ class InvalidLengthError(InvalidNameError): """ Raised when a string too long/short. """ class ReservedNameError(InvalidNameError): """ Raised when a string is matched a reserved name. """
Add base class of invalid name error
Add base class of invalid name error
Python
mit
thombashi/pathvalidate
from __future__ import absolute_import from __future__ import unicode_literals - class NullNameError(ValueError): + class InvalidNameError(ValueError): + """ + Base class of invalid name error. + """ + + + class NullNameError(InvalidNameError): """ Raised when a name is empty. """ - class InvalidCharError(ValueError): + class InvalidCharError(InvalidNameError): """ Raised when includes invalid character(s) within a string. """ class InvalidCharWindowsError(InvalidCharError): """ Raised when includes Windows specific invalid character(s) within a string. """ - class InvalidLengthError(ValueError): + class InvalidLengthError(InvalidNameError): """ Raised when a string too long/short. """ - class ReservedNameError(ValueError): + class ReservedNameError(InvalidNameError): """ Raised when a string is matched a reserved name. """
Add base class of invalid name error
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals class NullNameError(ValueError): """ Raised when a name is empty. """ class InvalidCharError(ValueError): """ Raised when includes invalid character(s) within a string. """ class InvalidCharWindowsError(InvalidCharError): """ Raised when includes Windows specific invalid character(s) within a string. """ class InvalidLengthError(ValueError): """ Raised when a string too long/short. """ class ReservedNameError(ValueError): """ Raised when a string is matched a reserved name. """ ## Instruction: Add base class of invalid name error ## Code After: from __future__ import absolute_import from __future__ import unicode_literals class InvalidNameError(ValueError): """ Base class of invalid name error. """ class NullNameError(InvalidNameError): """ Raised when a name is empty. """ class InvalidCharError(InvalidNameError): """ Raised when includes invalid character(s) within a string. """ class InvalidCharWindowsError(InvalidCharError): """ Raised when includes Windows specific invalid character(s) within a string. """ class InvalidLengthError(InvalidNameError): """ Raised when a string too long/short. """ class ReservedNameError(InvalidNameError): """ Raised when a string is matched a reserved name. """
... class InvalidNameError(ValueError): """ Base class of invalid name error. """ class NullNameError(InvalidNameError): """ Raised when a name is empty. ... class InvalidCharError(InvalidNameError): """ Raised when includes invalid character(s) within a string. ... class InvalidLengthError(InvalidNameError): """ Raised when a string too long/short. ... class ReservedNameError(InvalidNameError): """ Raised when a string is matched a reserved name. ...
1e150c4d5797f17ba8bea53d328cb613adc6bc0f
self_play.py
self_play.py
import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game.current_player, col_index) assert success self.render_board() print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner)) def calc_move(self, current_player): return random.randint(0, self.game.grid.width) def render_board(self): str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"] for row in reversed(self.game.grid): row_repr = [] for disc_value in row: if disc_value is DiscState.empty: row_repr.append("| |") elif disc_value is DiscState.red: row_repr.append("|O|") else: # disc_value is black row_repr.append("|X|") row_repr.append("\n") str_repr += row_repr print("".join(str_repr)) def disc_state_to_player_name(self, disc_state): if disc_state is DiscState.red: return "O" else: return "X"
import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game self.log = [] def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game.current_player, col_index) assert success self.log.append(col_index) self.render_board() print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner)) def calc_move(self, current_player): return random.randint(0, self.game.grid.width) def render_board(self): str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"] for row in reversed(self.game.grid): row_repr = [] for disc_value in row: if disc_value is DiscState.empty: row_repr.append("| |") elif disc_value is DiscState.red: row_repr.append("|O|") else: # disc_value is black row_repr.append("|X|") row_repr.append("\n") str_repr += row_repr print("".join(str_repr)) def disc_state_to_player_name(self, disc_state): if disc_state is DiscState.red: return "O" else: return "X"
Add log to self play
Add log to self play
Python
mit
misterwilliam/connect-four
import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game + self.log = [] def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game.current_player, col_index) assert success + self.log.append(col_index) self.render_board() print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner)) def calc_move(self, current_player): return random.randint(0, self.game.grid.width) def render_board(self): str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"] for row in reversed(self.game.grid): row_repr = [] for disc_value in row: if disc_value is DiscState.empty: row_repr.append("| |") elif disc_value is DiscState.red: row_repr.append("|O|") else: # disc_value is black row_repr.append("|X|") row_repr.append("\n") str_repr += row_repr print("".join(str_repr)) def disc_state_to_player_name(self, disc_state): if disc_state is DiscState.red: return "O" else: return "X"
Add log to self play
## Code Before: import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game.current_player, col_index) assert success self.render_board() print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner)) def calc_move(self, current_player): return random.randint(0, self.game.grid.width) def render_board(self): str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"] for row in reversed(self.game.grid): row_repr = [] for disc_value in row: if disc_value is DiscState.empty: row_repr.append("| |") elif disc_value is DiscState.red: row_repr.append("|O|") else: # disc_value is black row_repr.append("|X|") row_repr.append("\n") str_repr += row_repr print("".join(str_repr)) def disc_state_to_player_name(self, disc_state): if disc_state is DiscState.red: return "O" else: return "X" ## Instruction: Add log to self play ## Code After: import random from game import Game, DiscState class SelfPlay: def __init__(self, game): self.game = game self.log = [] def play(self): while self.game.winner is None: col_index = self.calc_move(self.game.current_player) if self.game.can_add_disc(col_index): success = self.game.try_turn(self.game.current_player, col_index) assert success self.log.append(col_index) self.render_board() print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner)) def calc_move(self, current_player): return random.randint(0, self.game.grid.width) def render_board(self): str_repr = [" %i " % col_index for col_index in range(self.game.grid.width)] + ["\n"] for row in reversed(self.game.grid): row_repr = [] for disc_value in row: if disc_value is DiscState.empty: row_repr.append("| |") elif disc_value is DiscState.red: row_repr.append("|O|") else: # disc_value is black row_repr.append("|X|") row_repr.append("\n") str_repr += row_repr print("".join(str_repr)) def disc_state_to_player_name(self, disc_state): if disc_state is DiscState.red: return "O" else: return "X"
... def __init__(self, game): self.game = game self.log = [] def play(self): ... success = self.game.try_turn(self.game.current_player, col_index) assert success self.log.append(col_index) self.render_board() print("Winner is: %s" % self.disc_state_to_player_name(self.game.winner)) ...
ceee44182b24ecdc0563a9e9a6841993d1978d0c
setup.py
setup.py
from distutils.core import setup setup( name='aJohnShots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA 1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
from distutils.core import setup setup( name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', long_description=open('README').read(), author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA-1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
Rename + add long_description + update keywords
Rename + add long_description + update keywords
Python
mit
funilrys/A-John-Shots
from distutils.core import setup setup( - name='aJohnShots', + name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', + long_description=open('README').read(), author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], - keywords=['Python', 'JSON', 'SHA 1', + keywords=['Python', 'JSON', 'SHA-1', - 'SHA-512', 'SHA-224', 'SHA-384', 'SHA'], + 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
Rename + add long_description + update keywords
## Code Before: from distutils.core import setup setup( name='aJohnShots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA 1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, ''' ## Instruction: Rename + add long_description + update keywords ## Code After: from distutils.core import setup setup( name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', long_description=open('README').read(), author='funilrys', author_email='[email protected]', license='GPL-3.0 https://opensource.org/licenses/GPL-3.0', url='https://github.com/funilrys/A-John-Shots', platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA-1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', 'Topic :: Software Development', 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)' ], ) ''' test_suite='testsuite', entry_points=""" [console_scripts] cmd = package:main """, '''
... setup( name='a_john_shots', version="1.0.0", description='Python module/library for saving Security Hash Algorithms into JSON format.', long_description=open('README').read(), author='funilrys', author_email='[email protected]', ... platforms=['any'], packages=['a_john_shots'], keywords=['Python', 'JSON', 'SHA-1', 'SHA-512', 'SHA-224', 'SHA-384', 'SHA', 'MD5'], classifiers=[ 'Environment :: Console', ...
11b0608f2cab4f9c804d5a2e67edfc4270448b71
ectoken.py
ectoken.py
from ctypes import CDLL, create_string_buffer, byref import pkg_resources bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so')) def ectoken_generate(key, string): if isinstance(string, unicode): string = string.encode('utf-8') string = 'ec_secure=%03d&%s' % (len(string) + 14, string) string_len = len(string) output = create_string_buffer(string_len) bf.bfencrypt(key, len(key), string, byref(output), string_len) return output.raw.encode('hex_codec')
from ctypes import CDLL, create_string_buffer, byref import pkg_resources bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so')) def ectoken_generate(key, string): if len(string) > 512: raise ValueError( '%r exceeds maximum length of 512 characters' % string) if isinstance(string, unicode): string = string.encode('utf-8') string = 'ec_secure=%03d&%s' % (len(string) + 14, string) string_len = len(string) output = create_string_buffer(string_len) bf.bfencrypt(key, len(key), string, byref(output), string_len) return output.raw.encode('hex_codec')
Add check for maximum length (taken from the original Edgecast ec_encrypt.c example)
Add check for maximum length (taken from the original Edgecast ec_encrypt.c example)
Python
bsd-3-clause
sebest/ectoken-py,sebest/ectoken-py
from ctypes import CDLL, create_string_buffer, byref import pkg_resources bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so')) def ectoken_generate(key, string): + if len(string) > 512: + raise ValueError( + '%r exceeds maximum length of 512 characters' % string) if isinstance(string, unicode): string = string.encode('utf-8') string = 'ec_secure=%03d&%s' % (len(string) + 14, string) string_len = len(string) output = create_string_buffer(string_len) bf.bfencrypt(key, len(key), string, byref(output), string_len) return output.raw.encode('hex_codec')
Add check for maximum length (taken from the original Edgecast ec_encrypt.c example)
## Code Before: from ctypes import CDLL, create_string_buffer, byref import pkg_resources bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so')) def ectoken_generate(key, string): if isinstance(string, unicode): string = string.encode('utf-8') string = 'ec_secure=%03d&%s' % (len(string) + 14, string) string_len = len(string) output = create_string_buffer(string_len) bf.bfencrypt(key, len(key), string, byref(output), string_len) return output.raw.encode('hex_codec') ## Instruction: Add check for maximum length (taken from the original Edgecast ec_encrypt.c example) ## Code After: from ctypes import CDLL, create_string_buffer, byref import pkg_resources bf = CDLL(pkg_resources.resource_filename(__name__, '_ecblowfish.so')) def ectoken_generate(key, string): if len(string) > 512: raise ValueError( '%r exceeds maximum length of 512 characters' % string) if isinstance(string, unicode): string = string.encode('utf-8') string = 'ec_secure=%03d&%s' % (len(string) + 14, string) string_len = len(string) output = create_string_buffer(string_len) bf.bfencrypt(key, len(key), string, byref(output), string_len) return output.raw.encode('hex_codec')
... def ectoken_generate(key, string): if len(string) > 512: raise ValueError( '%r exceeds maximum length of 512 characters' % string) if isinstance(string, unicode): string = string.encode('utf-8') ...
1adc660916eafe5937b96f1b5bc480185efc96ad
aospy_user/__init__.py
aospy_user/__init__.py
"""aospy_user: Library of user-defined aospy objects.""" from . import regions from . import units from . import calcs from . import variables from . import runs from . import models from . import projs from . import obj_from_name from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region, to_iterable)
"""aospy_user: Library of user-defined aospy objects.""" from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR, TIME_STR, TIME_STR_IDEALIZED) from . import regions from . import units from . import calcs from . import variables from . import runs from . import models from . import projs from . import obj_from_name from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region, to_iterable)
Use aospy coord label constants
Use aospy coord label constants
Python
apache-2.0
spencerahill/aospy-obj-lib
"""aospy_user: Library of user-defined aospy objects.""" + from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR, + TIME_STR, TIME_STR_IDEALIZED) + from . import regions from . import units from . import calcs from . import variables from . import runs from . import models from . import projs from . import obj_from_name from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region, to_iterable)
Use aospy coord label constants
## Code Before: """aospy_user: Library of user-defined aospy objects.""" from . import regions from . import units from . import calcs from . import variables from . import runs from . import models from . import projs from . import obj_from_name from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region, to_iterable) ## Instruction: Use aospy coord label constants ## Code After: """aospy_user: Library of user-defined aospy objects.""" from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR, TIME_STR, TIME_STR_IDEALIZED) from . import regions from . import units from . import calcs from . import variables from . import runs from . import models from . import projs from . import obj_from_name from .obj_from_name import (to_proj, to_model, to_run, to_var, to_region, to_iterable)
// ... existing code ... """aospy_user: Library of user-defined aospy objects.""" from aospy import (LAT_STR, LON_STR, PHALF_STR, PFULL_STR, PLEVEL_STR, TIME_STR, TIME_STR_IDEALIZED) from . import regions from . import units // ... rest of the code ...
1e9fb28b1263bb543191d3c44ba39d8311ad7cae
quantecon/__init__.py
quantecon/__init__.py
from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
Remove models/ subpackage from api due to migration to QuantEcon.applications
Remove models/ subpackage from api due to migration to QuantEcon.applications
Python
bsd-3-clause
QuantEcon/QuantEcon.py,oyamad/QuantEcon.py,QuantEcon/QuantEcon.py,oyamad/QuantEcon.py
- from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
Remove models/ subpackage from api due to migration to QuantEcon.applications
## Code Before: from . import models as models from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__ ## Instruction: Remove models/ subpackage from api due to migration to QuantEcon.applications ## Code After: from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV from .ecdf import ECDF from .estspec import smooth, periodogram, ar_periodogram from .graph_tools import DiGraph from .gridtools import cartesian, mlinspace from .kalman import Kalman from .lae import LAE from .arma import ARMA from .lqcontrol import LQ from .lqnash import nnash from .lss import LinearStateSpace from .matrix_eqn import solve_discrete_lyapunov, solve_discrete_riccati from .quadsums import var_quadratic_sum, m_quadratic_sum #->Propose Delete From Top Level from .markov import MarkovChain, random_markov_chain, random_stochastic_matrix, gth_solve, tauchen #Promote to keep current examples working from .markov import mc_compute_stationary, mc_sample_path #Imports that Should be Deprecated with markov package #<- from .rank_nullspace import rank_est, nullspace from .robustlq import RBLQ from . import quad as quad from .util import searchsorted #Add Version Attribute from .version import version as __version__
# ... existing code ... from .compute_fp import compute_fixed_point from .discrete_rv import DiscreteRV # ... rest of the code ...
b62c8c905cdd332a0073ce462be3e5c5b17b282d
api/webview/views.py
api/webview/views.py
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import DocumentSerializer class DocumentList(generics.ListCreateAPIView): """ List all documents in the SHARE API """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return all documents """ return Document.objects.all() class DocumentsFromSource(generics.ListCreateAPIView): """ List all documents from a particular source """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return queryset based on source """ return Document.objects.filter(source=self.kwargs['source']) @api_view(['GET']) @xframe_options_exempt def document_detail(request, source, docID): """ Retrieve one particular document. """ try: all_sources = Document.objects.filter(source=source) document = all_sources.get(docID=docID) except Document.DoesNotExist: return Response(status=404) serializer = DocumentSerializer(document) return Response(serializer.data)
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import DocumentSerializer class DocumentList(generics.ListAPIView): """ List all documents in the SHARE API """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return all documents """ return Document.objects.all() class DocumentsFromSource(generics.ListAPIView): """ List all documents from a particular source """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return queryset based on source """ return Document.objects.filter(source=self.kwargs['source']) @api_view(['GET']) @xframe_options_exempt def document_detail(request, source, docID): """ Retrieve one particular document. """ try: all_sources = Document.objects.filter(source=source) document = all_sources.get(docID=docID) except Document.DoesNotExist: return Response(status=404) serializer = DocumentSerializer(document) return Response(serializer.data)
Make the view List only remove Create
Make the view List only remove Create
Python
apache-2.0
erinspace/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,felliott/scrapi
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import DocumentSerializer - class DocumentList(generics.ListCreateAPIView): + class DocumentList(generics.ListAPIView): """ List all documents in the SHARE API """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return all documents """ return Document.objects.all() - class DocumentsFromSource(generics.ListCreateAPIView): + class DocumentsFromSource(generics.ListAPIView): """ List all documents from a particular source """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return queryset based on source """ return Document.objects.filter(source=self.kwargs['source']) @api_view(['GET']) @xframe_options_exempt def document_detail(request, source, docID): """ Retrieve one particular document. """ try: all_sources = Document.objects.filter(source=source) document = all_sources.get(docID=docID) except Document.DoesNotExist: return Response(status=404) serializer = DocumentSerializer(document) return Response(serializer.data)
Make the view List only remove Create
## Code Before: from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import DocumentSerializer class DocumentList(generics.ListCreateAPIView): """ List all documents in the SHARE API """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return all documents """ return Document.objects.all() class DocumentsFromSource(generics.ListCreateAPIView): """ List all documents from a particular source """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return queryset based on source """ return Document.objects.filter(source=self.kwargs['source']) @api_view(['GET']) @xframe_options_exempt def document_detail(request, source, docID): """ Retrieve one particular document. """ try: all_sources = Document.objects.filter(source=source) document = all_sources.get(docID=docID) except Document.DoesNotExist: return Response(status=404) serializer = DocumentSerializer(document) return Response(serializer.data) ## Instruction: Make the view List only remove Create ## Code After: from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import DocumentSerializer class DocumentList(generics.ListAPIView): """ List all documents in the SHARE API """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return all documents """ return Document.objects.all() class DocumentsFromSource(generics.ListAPIView): """ List all documents from a particular source """ serializer_class = DocumentSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(source=self.request.user) def get_queryset(self): """ Return queryset based on source """ return Document.objects.filter(source=self.kwargs['source']) @api_view(['GET']) @xframe_options_exempt def document_detail(request, source, docID): """ Retrieve one particular document. """ try: all_sources = Document.objects.filter(source=source) document = all_sources.get(docID=docID) except Document.DoesNotExist: return Response(status=404) serializer = DocumentSerializer(document) return Response(serializer.data)
... class DocumentList(generics.ListAPIView): """ List all documents in the SHARE API ... class DocumentsFromSource(generics.ListAPIView): """ List all documents from a particular source ...
7539a5445d24193395eed5dc658a4e69d8782736
buffpy/tests/test_profile.py
buffpy/tests/test_profile.py
from nose.tools import eq_ from mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') def test_profile_updates(): ''' Test updates relationship with a profile ''' mocked_api = MagicMock() with patch('buffpy.models.profile.Updates') as mocked_updates: profile = Profile(api=mocked_api, raw_response={'id': 1}) updates = profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
from unittest.mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { "name": "me", "service": "twiter", "id": 1 } def test_profile_schedules_getter(): """ Should retrieve profiles from buffer's API. """ mocked_api = MagicMock() mocked_api.get.return_value = "123" profile = Profile(mocked_api, mocked_response) assert profile.schedules == "123" mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1")) def test_profile_schedules_setter(): """ Should update profile's schedules. """ mocked_api = MagicMock() mocked_api.get.return_value = "123" profile = Profile(mocked_api, mocked_response) profile.schedules = { "times": ["mo"] } mocked_api.post.assert_called_once_with( url=PATHS["UPDATE_SCHEDULES"].format("1"), data="schedules[0][times][]=mo&") def test_profile_updates(): """ Should properly call buffer's updates. """ mocked_api = MagicMock() with patch("buffpy.models.profile.Updates") as mocked_updates: profile = Profile(api=mocked_api, raw_response={"id": 1}) assert profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
Migrate profile tests to pytest
Migrate profile tests to pytest
Python
mit
vtemian/buffpy
- from nose.tools import eq_ - from mock import MagicMock, patch + from unittest.mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS + mocked_response = { - 'name': 'me', + "name": "me", - 'service': 'twiter', + "service": "twiter", - 'id': 1 + "id": 1 } + def test_profile_schedules_getter(): + """ Should retrieve profiles from buffer's API. """ - ''' - Test schedules gettering from buffer api - ''' - mocked_api = MagicMock() + mocked_api = MagicMock() - mocked_api.get.return_value = '123' + mocked_api.get.return_value = "123" - profile = Profile(mocked_api, mocked_response) + profile = Profile(mocked_api, mocked_response) - eq_(profile.schedules, '123') + assert profile.schedules == "123" - mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) + mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1")) + def test_profile_schedules_setter(): + """ Should update profile's schedules. """ - ''' - Test schedules setter from buffer api - ''' - mocked_api = MagicMock() + mocked_api = MagicMock() - mocked_api.get.return_value = '123' + mocked_api.get.return_value = "123" - profile = Profile(mocked_api, mocked_response) + profile = Profile(mocked_api, mocked_response) - profile.schedules = { + profile.schedules = { - 'times': ['mo'] + "times": ["mo"] - } + } - mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, + mocked_api.post.assert_called_once_with( + url=PATHS["UPDATE_SCHEDULES"].format("1"), - data='schedules[0][times][]=mo&') + data="schedules[0][times][]=mo&") + def test_profile_updates(): + """ Should properly call buffer's updates. """ - ''' - Test updates relationship with a profile - ''' - mocked_api = MagicMock() + mocked_api = MagicMock() - with patch('buffpy.models.profile.Updates') as mocked_updates: + with patch("buffpy.models.profile.Updates") as mocked_updates: - profile = Profile(api=mocked_api, raw_response={'id': 1}) + profile = Profile(api=mocked_api, raw_response={"id": 1}) - updates = profile.updates + assert profile.updates - mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1) + mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
Migrate profile tests to pytest
## Code Before: from nose.tools import eq_ from mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') def test_profile_updates(): ''' Test updates relationship with a profile ''' mocked_api = MagicMock() with patch('buffpy.models.profile.Updates') as mocked_updates: profile = Profile(api=mocked_api, raw_response={'id': 1}) updates = profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1) ## Instruction: Migrate profile tests to pytest ## Code After: from unittest.mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { "name": "me", "service": "twiter", "id": 1 } def test_profile_schedules_getter(): """ Should retrieve profiles from buffer's API. """ mocked_api = MagicMock() mocked_api.get.return_value = "123" profile = Profile(mocked_api, mocked_response) assert profile.schedules == "123" mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1")) def test_profile_schedules_setter(): """ Should update profile's schedules. """ mocked_api = MagicMock() mocked_api.get.return_value = "123" profile = Profile(mocked_api, mocked_response) profile.schedules = { "times": ["mo"] } mocked_api.post.assert_called_once_with( url=PATHS["UPDATE_SCHEDULES"].format("1"), data="schedules[0][times][]=mo&") def test_profile_updates(): """ Should properly call buffer's updates. """ mocked_api = MagicMock() with patch("buffpy.models.profile.Updates") as mocked_updates: profile = Profile(api=mocked_api, raw_response={"id": 1}) assert profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
# ... existing code ... from unittest.mock import MagicMock, patch from buffpy.models.profile import Profile, PATHS mocked_response = { "name": "me", "service": "twiter", "id": 1 } def test_profile_schedules_getter(): """ Should retrieve profiles from buffer's API. """ mocked_api = MagicMock() mocked_api.get.return_value = "123" profile = Profile(mocked_api, mocked_response) assert profile.schedules == "123" mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1")) def test_profile_schedules_setter(): """ Should update profile's schedules. """ mocked_api = MagicMock() mocked_api.get.return_value = "123" profile = Profile(mocked_api, mocked_response) profile.schedules = { "times": ["mo"] } mocked_api.post.assert_called_once_with( url=PATHS["UPDATE_SCHEDULES"].format("1"), data="schedules[0][times][]=mo&") def test_profile_updates(): """ Should properly call buffer's updates. """ mocked_api = MagicMock() with patch("buffpy.models.profile.Updates") as mocked_updates: profile = Profile(api=mocked_api, raw_response={"id": 1}) assert profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1) # ... rest of the code ...