Datasets:

Modalities:
Text
Formats:
parquet
Languages:
code
ArXiv:
Tags:
code
Libraries:
Datasets
pandas
License:
commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
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
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
e905334869af72025592de586b81650cb3468b8a
sentry/queue/client.py
sentry/queue/client.py
from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
Declare queues when broker is instantiated
Declare queues when broker is instantiated
Python
bsd-3-clause
imankulov/sentry,BuildingLink/sentry,zenefits/sentry,korealerts1/sentry,kevinastone/sentry,fotinakis/sentry,fuziontech/sentry,ngonzalvez/sentry,mvaled/sentry,Kronuz/django-sentry,ngonzalvez/sentry,looker/sentry,felixbuenemann/sentry,ngonzalvez/sentry,nicholasserra/sentry,camilonova/sentry,jokey2k/sentry,llonchj/sentry,fuziontech/sentry,llonchj/sentry,NickPresta/sentry,boneyao/sentry,SilentCircle/sentry,Kryz/sentry,JamesMura/sentry,SilentCircle/sentry,wujuguang/sentry,JTCunning/sentry,rdio/sentry,1tush/sentry,alexm92/sentry,imankulov/sentry,wujuguang/sentry,jokey2k/sentry,jean/sentry,chayapan/django-sentry,looker/sentry,beeftornado/sentry,chayapan/django-sentry,gg7/sentry,chayapan/django-sentry,JamesMura/sentry,1tush/sentry,zenefits/sentry,ewdurbin/sentry,NickPresta/sentry,alex/sentry,camilonova/sentry,kevinastone/sentry,pauloschilling/sentry,boneyao/sentry,korealerts1/sentry,rdio/sentry,daevaorn/sentry,drcapulet/sentry,TedaLIEz/sentry,Kronuz/django-sentry,wong2/sentry,felixbuenemann/sentry,1tush/sentry,hongliang5623/sentry,looker/sentry,BayanGroup/sentry,BuildingLink/sentry,BuildingLink/sentry,BayanGroup/sentry,kevinlondon/sentry,daevaorn/sentry,looker/sentry,llonchj/sentry,gencer/sentry,fotinakis/sentry,BuildingLink/sentry,korealerts1/sentry,felixbuenemann/sentry,boneyao/sentry,alex/sentry,fuziontech/sentry,nicholasserra/sentry,beeftornado/sentry,SilentCircle/sentry,ifduyue/sentry,gencer/sentry,jean/sentry,pauloschilling/sentry,camilonova/sentry,wong2/sentry,mvaled/sentry,JamesMura/sentry,ewdurbin/sentry,JackDanger/sentry,beeftornado/sentry,BuildingLink/sentry,argonemyth/sentry,zenefits/sentry,alex/sentry,gg7/sentry,jean/sentry,vperron/sentry,NickPresta/sentry,mvaled/sentry,JackDanger/sentry,songyi199111/sentry,vperron/sentry,daevaorn/sentry,ifduyue/sentry,kevinlondon/sentry,BayanGroup/sentry,JackDanger/sentry,kevinastone/sentry,Natim/sentry,zenefits/sentry,pauloschilling/sentry,Natim/sentry,argonemyth/sentry,alexm92/sentry,Natim/sentry,Kronuz/django-sentry,gg7/sentry,hongliang5623/sentry,looker/sentry,daevaorn/sentry,TedaLIEz/sentry,alexm92/sentry,vperron/sentry,ifduyue/sentry,mvaled/sentry,jean/sentry,JamesMura/sentry,hongliang5623/sentry,songyi199111/sentry,argonemyth/sentry,JTCunning/sentry,gencer/sentry,nicholasserra/sentry,ifduyue/sentry,Kryz/sentry,Kryz/sentry,beni55/sentry,TedaLIEz/sentry,kevinlondon/sentry,NickPresta/sentry,mvaled/sentry,drcapulet/sentry,jean/sentry,gencer/sentry,songyi199111/sentry,beni55/sentry,beni55/sentry,SilentCircle/sentry,mvaled/sentry,mitsuhiko/sentry,ewdurbin/sentry,wujuguang/sentry,fotinakis/sentry,drcapulet/sentry,fotinakis/sentry,wong2/sentry,ifduyue/sentry,zenefits/sentry,JTCunning/sentry,rdio/sentry,imankulov/sentry,jokey2k/sentry,gencer/sentry,rdio/sentry,JamesMura/sentry,mitsuhiko/sentry
from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) + with producers[self.connection].acquire(block=False) as producer: + for queue in task_queues: + maybe_declare(queue, producer.channel) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: - for queue in task_queues: - maybe_declare(queue, producer.channel) producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
Declare queues when broker is instantiated
## Code Before: from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE) ## Instruction: Declare queues when broker is instantiated ## Code After: from kombu import BrokerConnection from kombu.common import maybe_declare from kombu.pools import producers from sentry.conf import settings from sentry.queue.queues import task_queues, task_exchange class Broker(object): def __init__(self, config): self.connection = BrokerConnection(**config) with producers[self.connection].acquire(block=False) as producer: for queue in task_queues: maybe_declare(queue, producer.channel) def delay(self, func, *args, **kwargs): payload = { "func": func, "args": args, "kwargs": kwargs, } with producers[self.connection].acquire(block=False) as producer: producer.publish(payload, exchange=task_exchange, serializer="pickle", compression="bzip2", queue='default', routing_key='default', ) broker = Broker(settings.QUEUE)
950ac9130bafe1fced578bf61d746b047830bfa0
automata/base/exceptions.py
automata/base/exceptions.py
"""Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton after validation.""" pass
"""Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton.""" pass
Remove "validation" from RejectionException docstring
Remove "validation" from RejectionException docstring
Python
mit
caleb531/automata
"""Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): - """The input was rejected by the automaton after validation.""" + """The input was rejected by the automaton.""" pass
Remove "validation" from RejectionException docstring
## Code Before: """Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton after validation.""" pass ## Instruction: Remove "validation" from RejectionException docstring ## Code After: """Exception classes shared by all automata.""" class AutomatonException(Exception): """The base class for all automaton-related errors.""" pass class InvalidStateError(AutomatonException): """A state is not a valid state for this automaton.""" pass class InvalidSymbolError(AutomatonException): """A symbol is not a valid symbol for this automaton.""" pass class MissingStateError(AutomatonException): """A state is missing from the automaton definition.""" pass class MissingSymbolError(AutomatonException): """A symbol is missing from the automaton definition.""" pass class InitialStateError(AutomatonException): """The initial state fails to meet some required condition.""" pass class FinalStateError(AutomatonException): """A final state fails to meet some required condition.""" pass class RejectionException(AutomatonException): """The input was rejected by the automaton.""" pass
c3f8860c717a139d396b0d902db989ab7b8369ba
stock_inventory_hierarchical/__openerp__.py
stock_inventory_hierarchical/__openerp__.py
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["inventory_form.png", "inventory_form_actions.png", "wizard.png"], 'license': 'AGPL-3', 'installable': True }
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
Fix image path in manifest
Fix image path in manifest
Python
agpl-3.0
kmee/stock-logistics-warehouse,factorlibre/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse,acsone/stock-logistics-warehouse,avoinsystems/stock-logistics-warehouse
{ "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], - "images": ["inventory_form.png", + "images": ["images/inventory_form.png", - "inventory_form_actions.png", + "images/inventory_form_actions.png", - "wizard.png"], + "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
Fix image path in manifest
## Code Before: { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["inventory_form.png", "inventory_form_actions.png", "wizard.png"], 'license': 'AGPL-3', 'installable': True } ## Instruction: Fix image path in manifest ## Code After: { "name": "Hierarchical Inventory adjustments", "summary": "Group several Inventory adjustments in a master inventory", "version": "8.0.2.0.0", "depends": ["stock"], "author": u"Numérigraphe,Odoo Community Association (OCA)", "category": "Warehouse Management", "data": ["views/stock_inventory_view.xml", "wizard/generate_inventory_view.xml"], "images": ["images/inventory_form.png", "images/inventory_form_actions.png", "images/wizard.png"], 'license': 'AGPL-3', 'installable': True }
70a642c0597fb2f929fc83d821c8b1f095ed1328
proxy/plugins/plugins.py
proxy/plugins/plugins.py
packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions packetFunctions[(self.pktType, self.pktSubtype)] = f class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions if (self.pktType, self.pktSubtype) not in packetFunctions: packetFunctions[(self.pktType, self.pktSubtype)] = [] packetFunctions[(self.pktType, self.pktSubtype)].append(f) class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
Allow mutiple hooks for packets
Allow mutiple hooks for packets
Python
agpl-3.0
alama/PSO2Proxy,alama/PSO2Proxy,flyergo/PSO2Proxy,alama/PSO2Proxy,cyberkitsune/PSO2Proxy,cyberkitsune/PSO2Proxy,flyergo/PSO2Proxy,cyberkitsune/PSO2Proxy
packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions + if (self.pktType, self.pktSubtype) not in packetFunctions: - packetFunctions[(self.pktType, self.pktSubtype)] = f + packetFunctions[(self.pktType, self.pktSubtype)] = [] + packetFunctions[(self.pktType, self.pktSubtype)].append(f) class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
Allow mutiple hooks for packets
## Code Before: packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions packetFunctions[(self.pktType, self.pktSubtype)] = f class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f ## Instruction: Allow mutiple hooks for packets ## Code After: packetFunctions = {} commands = {} onStart = [] onConnection = [] onConnectionLoss = [] class packetHook(object): def __init__(self, pktType, pktSubtype): self.pktType = pktType self.pktSubtype = pktSubtype def __call__(self, f): global packetFunctions if (self.pktType, self.pktSubtype) not in packetFunctions: packetFunctions[(self.pktType, self.pktSubtype)] = [] packetFunctions[(self.pktType, self.pktSubtype)].append(f) class commandHook(object): """docstring for commandHook""" def __init__(self, command): self.command = command def __call__(self, f): global commands commands[self.command] = f def onStartHook(f): global onStart onStart.append(f) return f def onConnectionHook(f): global onConnection onConnection.append(f) return f def onConnectionLossHook(f): global onConnectionLoss onConnectionLoss.append(f) return f
af91b7c2612fab598ba50c0c0256f7e552098d92
reportlab/docs/genAll.py
reportlab/docs/genAll.py
"""Runs the three manual-building scripts""" if __name__=='__main__': import os, sys d = os.path.dirname(sys.argv[0]) #need a quiet mode for the test suite if '-s' in sys.argv: # 'silent quiet = '-s' else: quiet = '' if not d: d = '.' if not os.path.isabs(d): d = os.path.normpath(os.path.join(os.getcwd(),d)) for p in ('reference/genreference.py', 'userguide/genuserguide.py', 'graphguide/gengraphguide.py', '../tools/docco/graphdocpy.py'): os.chdir(d) os.chdir(os.path.dirname(p)) os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet))
import os def _genAll(d=None,quiet=''): if not d: d = '.' if not os.path.isabs(d): d = os.path.normpath(os.path.join(os.getcwd(),d)) for p in ('reference/genreference.py', 'userguide/genuserguide.py', 'graphguide/gengraphguide.py', '../tools/docco/graphdocpy.py'): os.chdir(d) os.chdir(os.path.dirname(p)) os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet)) """Runs the manual-building scripts""" if __name__=='__main__': import sys #need a quiet mode for the test suite if '-s' in sys.argv: # 'silent quiet = '-s' else: quiet = '' _genAll(os.path.dirname(sys.argv[0]),quiet)
Allow for use in daily.py
Allow for use in daily.py
Python
bsd-3-clause
makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile
+ import os + def _genAll(d=None,quiet=''): + if not d: d = '.' + if not os.path.isabs(d): + d = os.path.normpath(os.path.join(os.getcwd(),d)) + for p in ('reference/genreference.py', + 'userguide/genuserguide.py', + 'graphguide/gengraphguide.py', + '../tools/docco/graphdocpy.py'): + os.chdir(d) + os.chdir(os.path.dirname(p)) + os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet)) + - """Runs the three manual-building scripts""" + """Runs the manual-building scripts""" if __name__=='__main__': - import os, sys - d = os.path.dirname(sys.argv[0]) + import sys + #need a quiet mode for the test suite + if '-s' in sys.argv: # 'silent + quiet = '-s' + else: + quiet = '' + _genAll(os.path.dirname(sys.argv[0]),quiet) - #need a quiet mode for the test suite - if '-s' in sys.argv: # 'silent - quiet = '-s' - else: - quiet = '' - - if not d: d = '.' - if not os.path.isabs(d): - d = os.path.normpath(os.path.join(os.getcwd(),d)) - for p in ('reference/genreference.py', - 'userguide/genuserguide.py', - 'graphguide/gengraphguide.py', - '../tools/docco/graphdocpy.py'): - os.chdir(d) - os.chdir(os.path.dirname(p)) - os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet)) -
Allow for use in daily.py
## Code Before: """Runs the three manual-building scripts""" if __name__=='__main__': import os, sys d = os.path.dirname(sys.argv[0]) #need a quiet mode for the test suite if '-s' in sys.argv: # 'silent quiet = '-s' else: quiet = '' if not d: d = '.' if not os.path.isabs(d): d = os.path.normpath(os.path.join(os.getcwd(),d)) for p in ('reference/genreference.py', 'userguide/genuserguide.py', 'graphguide/gengraphguide.py', '../tools/docco/graphdocpy.py'): os.chdir(d) os.chdir(os.path.dirname(p)) os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet)) ## Instruction: Allow for use in daily.py ## Code After: import os def _genAll(d=None,quiet=''): if not d: d = '.' if not os.path.isabs(d): d = os.path.normpath(os.path.join(os.getcwd(),d)) for p in ('reference/genreference.py', 'userguide/genuserguide.py', 'graphguide/gengraphguide.py', '../tools/docco/graphdocpy.py'): os.chdir(d) os.chdir(os.path.dirname(p)) os.system('%s %s %s' % (sys.executable,os.path.basename(p), quiet)) """Runs the manual-building scripts""" if __name__=='__main__': import sys #need a quiet mode for the test suite if '-s' in sys.argv: # 'silent quiet = '-s' else: quiet = '' _genAll(os.path.dirname(sys.argv[0]),quiet)
e34969db596ff3dfa4bf78efb3f3ccfe771d9ef9
setup.py
setup.py
try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django_exceptional_middleware' VERSION = '0.2' data_files = [ ( 'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ], ), ] setup( name=PACKAGE, version=VERSION, description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.", packages=[ 'exceptional_middleware' ], data_files=data_files, license='MIT', author='James Aylett', url = 'http://tartarus.org/james/computers/django/', )
try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django_exceptional_middleware' VERSION = '0.4' package_data = { 'exceptional_middleware': [ 'templates/http_responses/*.html' ], } setup( name=PACKAGE, version=VERSION, description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.", packages=[ 'exceptional_middleware' ], package_data=package_data, license='MIT', author='James Aylett', url = 'http://tartarus.org/james/computers/django/', )
Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
Python
mit
jaylett/django_exceptional_middleware
try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django_exceptional_middleware' - VERSION = '0.2' + VERSION = '0.4' + package_data = { + 'exceptional_middleware': [ 'templates/http_responses/*.html' ], + } - data_files = [ - ( - 'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ], - ), - ] setup( name=PACKAGE, version=VERSION, description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.", packages=[ 'exceptional_middleware' ], - data_files=data_files, + package_data=package_data, license='MIT', author='James Aylett', url = 'http://tartarus.org/james/computers/django/', )
Fix templates install. Bump to version 0.4 in the process (which is really my laziness).
## Code Before: try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django_exceptional_middleware' VERSION = '0.2' data_files = [ ( 'exceptional_middleware/templates/http_responses', [ 'exceptional_middleware/templates/http_responses/default.html' ], ), ] setup( name=PACKAGE, version=VERSION, description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.", packages=[ 'exceptional_middleware' ], data_files=data_files, license='MIT', author='James Aylett', url = 'http://tartarus.org/james/computers/django/', ) ## Instruction: Fix templates install. Bump to version 0.4 in the process (which is really my laziness). ## Code After: try: from setuptools.core import setup except ImportError: from distutils.core import setup PACKAGE = 'django_exceptional_middleware' VERSION = '0.4' package_data = { 'exceptional_middleware': [ 'templates/http_responses/*.html' ], } setup( name=PACKAGE, version=VERSION, description="Django middleware to allow generating arbitrary HTTP status codes via exceptions.", packages=[ 'exceptional_middleware' ], package_data=package_data, license='MIT', author='James Aylett', url = 'http://tartarus.org/james/computers/django/', )
c6265c2112ee9985af8b6b80fe0bee1811dc6abd
setup.py
setup.py
from distutils.core import setup setup( name='oceanoptics', version='0.2.6', author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter', author_email='mail@andreaspoehlmann.de', packages=['oceanoptics', 'oceanoptics.spectrometers'], description='A Python driver for Ocean Optics spectrometers.', long_description=open('README.md').read(), requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'], )
from distutils.core import setup setup( name='oceanoptics', version='0.2.7', author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams', author_email='mail@andreaspoehlmann.de', packages=['oceanoptics', 'oceanoptics.spectrometers'], description='A Python driver for Ocean Optics spectrometers.', long_description=open('README.md').read(), requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'], )
Add author and increase version number
Add author and increase version number
Python
mit
ap--/python-oceanoptics
from distutils.core import setup setup( name='oceanoptics', - version='0.2.6', + version='0.2.7', - author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter', + author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams', author_email='mail@andreaspoehlmann.de', packages=['oceanoptics', 'oceanoptics.spectrometers'], description='A Python driver for Ocean Optics spectrometers.', long_description=open('README.md').read(), requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'], )
Add author and increase version number
## Code Before: from distutils.core import setup setup( name='oceanoptics', version='0.2.6', author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter', author_email='mail@andreaspoehlmann.de', packages=['oceanoptics', 'oceanoptics.spectrometers'], description='A Python driver for Ocean Optics spectrometers.', long_description=open('README.md').read(), requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'], ) ## Instruction: Add author and increase version number ## Code After: from distutils.core import setup setup( name='oceanoptics', version='0.2.7', author='Andreas Poehlmann, Jose A. Jimenez-Berni, Ben Gamari, Simon Dickreuter, Ian Ross Williams', author_email='mail@andreaspoehlmann.de', packages=['oceanoptics', 'oceanoptics.spectrometers'], description='A Python driver for Ocean Optics spectrometers.', long_description=open('README.md').read(), requires=['python (>= 2.7)', 'pyusb (>= 1.0)', 'numpy'], )
5bb9b2c9d5df410c85f4736c17224aeb2f05dd33
s2v3.py
s2v3.py
from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing.
from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of +
Update print result to use "," instead of "+" for context text
Update print result to use "," instead of "+" for context text
Python
mit
alexmilesyounger/ds_basics
from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total - print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing. + print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of +
Update print result to use "," instead of "+" for context text
## Code Before: from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ' + str(calculate_sum(data_from_csv))) # ok we're using the right import, but having two imports is confusing. ## Instruction: Update print result to use "," instead of "+" for context text ## Code After: from s2v2 import * def calculate_sum(data_sample): total = 0 for row in data_sample[1:]: # slice to start at row two, but I think we should only skip row 1 if we're importing the full csv (data_from_csv), but if we use the data w/ the header (my_csv) we'll be skipping a row that we're not supposed to skip (the actual first row of non-header data). price = float(row[2]) total += price return total print('the sum total of prices for all ties in the dataset = ', calculate_sum(data_from_csv)) # ok we're using the right import, but having two imports is confusing. UPDDATE: No, I don't have to convert the calculate_sum result to a string to add text about it, I just need to use , instead of +
3ba5b6491bf61e2d2919f05bbf5cef088a754aeb
molecule/default/tests/test_installation.py
molecule/default/tests/test_installation.py
import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell == '/bin/false'
import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
Add nologin in expected user shell test
Add nologin in expected user shell test
Python
mit
infOpen/ansible-role-vsftpd
import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists - assert ftp_user.shell == '/bin/false' + assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
Add nologin in expected user shell test
## Code Before: import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell == '/bin/false' ## Instruction: Add nologin in expected user shell test ## Code After: import os import pytest from testinfra.utils.ansible_runner import AnsibleRunner testinfra_hosts = AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') @pytest.mark.parametrize('name', [ ('vsftpd'), ('db5.3-util'), ]) def test_installed_packages(host, name): """ Test if packages installed """ assert host.package(name).is_installed def test_service(host): """ Test service state """ service = host.service('vsftpd') assert service.is_enabled # if host.system_info.codename in ['jessie', 'xenial']: if host.file('/etc/init.d/vsftpd').exists: assert 'is running' in host.check_output('/etc/init.d/vsftpd status') else: assert service.is_running def test_process(host): """ Test process state """ assert len(host.process.filter(comm='vsftpd')) == 1 def test_socket(host): """ Test ports """ assert host.socket('tcp://127.0.0.1:21').is_listening def test_user(host): """ Test ftp user exists """ ftp_user = host.user('ftp') assert ftp_user.exists assert ftp_user.shell in ['/usr/sbin/nologin', '/bin/false']
b4c9b76d132668695b77d37d7db3071e629fcba7
makerscience_admin/models.py
makerscience_admin/models.py
from django.db import models from solo.models import SingletonModel class MakerScienceStaticContent (SingletonModel): about = models.TextField(null=True, blank=True) about_team = models.TextField(null=True, blank=True) about_contact = models.TextField(null=True, blank=True) about_faq = models.TextField(null=True, blank=True) about_cgu = models.TextField(null=True, blank=True) class PageViews(models.Model): client = models.CharField(max_length=255) resource_uri = models.CharField(max_length=255)
from django.db import models from django.db.models.signals import post_delete from solo.models import SingletonModel from accounts.models import ObjectProfileLink from makerscience_forum.models import MakerSciencePost class MakerScienceStaticContent (SingletonModel): about = models.TextField(null=True, blank=True) about_team = models.TextField(null=True, blank=True) about_contact = models.TextField(null=True, blank=True) about_faq = models.TextField(null=True, blank=True) about_cgu = models.TextField(null=True, blank=True) class PageViews(models.Model): client = models.CharField(max_length=255) resource_uri = models.CharField(max_length=255) def clear_makerscience(sender, instance, **kwargs): if sender == MakerSciencePost: ObjectProfileLink.objects.filter(content_type__model='post', object_id=instance.parent.id).delete() instance.parent.delete() post_delete.connect(clear_makerscience, sender=MakerSciencePost)
Allow to clear useless instances
Allow to clear useless instances
Python
agpl-3.0
atiberghien/makerscience-server,atiberghien/makerscience-server
from django.db import models + from django.db.models.signals import post_delete + from solo.models import SingletonModel + + from accounts.models import ObjectProfileLink + + from makerscience_forum.models import MakerSciencePost class MakerScienceStaticContent (SingletonModel): about = models.TextField(null=True, blank=True) about_team = models.TextField(null=True, blank=True) about_contact = models.TextField(null=True, blank=True) about_faq = models.TextField(null=True, blank=True) about_cgu = models.TextField(null=True, blank=True) class PageViews(models.Model): client = models.CharField(max_length=255) resource_uri = models.CharField(max_length=255) + + def clear_makerscience(sender, instance, **kwargs): + if sender == MakerSciencePost: + ObjectProfileLink.objects.filter(content_type__model='post', + object_id=instance.parent.id).delete() + instance.parent.delete() + + post_delete.connect(clear_makerscience, sender=MakerSciencePost) +
Allow to clear useless instances
## Code Before: from django.db import models from solo.models import SingletonModel class MakerScienceStaticContent (SingletonModel): about = models.TextField(null=True, blank=True) about_team = models.TextField(null=True, blank=True) about_contact = models.TextField(null=True, blank=True) about_faq = models.TextField(null=True, blank=True) about_cgu = models.TextField(null=True, blank=True) class PageViews(models.Model): client = models.CharField(max_length=255) resource_uri = models.CharField(max_length=255) ## Instruction: Allow to clear useless instances ## Code After: from django.db import models from django.db.models.signals import post_delete from solo.models import SingletonModel from accounts.models import ObjectProfileLink from makerscience_forum.models import MakerSciencePost class MakerScienceStaticContent (SingletonModel): about = models.TextField(null=True, blank=True) about_team = models.TextField(null=True, blank=True) about_contact = models.TextField(null=True, blank=True) about_faq = models.TextField(null=True, blank=True) about_cgu = models.TextField(null=True, blank=True) class PageViews(models.Model): client = models.CharField(max_length=255) resource_uri = models.CharField(max_length=255) def clear_makerscience(sender, instance, **kwargs): if sender == MakerSciencePost: ObjectProfileLink.objects.filter(content_type__model='post', object_id=instance.parent.id).delete() instance.parent.delete() post_delete.connect(clear_makerscience, sender=MakerSciencePost)
c713273fe145418113d750579f8b135dc513c3b8
config.py
config.py
import os if os.environ.get('DATABASE_URL') is None: SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' else: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
import os SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
Delete default case for SQLALCHEMY_DATABASE_URI
Delete default case for SQLALCHEMY_DATABASE_URI if user doesn't set it, he coud have some problems with SQLite
Python
mit
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
import os - if os.environ.get('DATABASE_URL') is None: - SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' - else: - SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] + SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] - SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
Delete default case for SQLALCHEMY_DATABASE_URI
## Code Before: import os if os.environ.get('DATABASE_URL') is None: SQLALCHEMY_DATABASE_URI = 'sqlite:///meetup.db' else: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning ## Instruction: Delete default case for SQLALCHEMY_DATABASE_URI ## Code After: import os SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] SQLALCHEMY_TRACK_MODIFICATIONS = False # supress deprecation warning
c61d5e84863dd67b5b76ec8031e624642f4c957c
main.py
main.py
from .ide.command import plugin_unloaded from .ide.error import * from .ide.rebuild import * from .ide.server import * from .ide.settings import plugin_loaded from .ide.text_command import * from .ide.type_hints import * from .ide.utility import *
from .ide.auto_complete import * from .ide.command import plugin_unloaded from .ide.error import * from .ide.rebuild import * from .ide.server import * from .ide.settings import plugin_loaded from .ide.text_command import * from .ide.type_hints import *
Fix issue with wrong import
Fix issue with wrong import
Python
mit
b123400/purescript-ide-sublime
+ from .ide.auto_complete import * from .ide.command import plugin_unloaded from .ide.error import * from .ide.rebuild import * from .ide.server import * from .ide.settings import plugin_loaded from .ide.text_command import * from .ide.type_hints import * - from .ide.utility import *
Fix issue with wrong import
## Code Before: from .ide.command import plugin_unloaded from .ide.error import * from .ide.rebuild import * from .ide.server import * from .ide.settings import plugin_loaded from .ide.text_command import * from .ide.type_hints import * from .ide.utility import * ## Instruction: Fix issue with wrong import ## Code After: from .ide.auto_complete import * from .ide.command import plugin_unloaded from .ide.error import * from .ide.rebuild import * from .ide.server import * from .ide.settings import plugin_loaded from .ide.text_command import * from .ide.type_hints import *
4e75e742475236cf7358b4481a29a54eb607dd4d
spacy/tests/regression/test_issue850.py
spacy/tests/regression/test_issue850.py
''' Test Matcher matches with '*' operator and Boolean flag ''' from __future__ import unicode_literals import pytest from ...matcher import Matcher from ...vocab import Vocab from ...attrs import LOWER from ...tokens import Doc @pytest.mark.xfail def test_issue850(): matcher = Matcher(Vocab()) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', IS_ANY_TOKEN: True}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank']) match = matcher(doc) assert len(match) == 1 start, end, label, ent_id = match assert start == 0 assert end == 4
''' Test Matcher matches with '*' operator and Boolean flag ''' from __future__ import unicode_literals from __future__ import print_function import pytest from ...matcher import Matcher from ...vocab import Vocab from ...attrs import LOWER from ...tokens import Doc def test_basic_case(): matcher = Matcher(Vocab( lex_attr_getters={LOWER: lambda string: string.lower()})) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', LOWER: 'and'}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) match = matcher(doc) assert len(match) == 1 ent_id, label, start, end = match[0] assert start == 0 assert end == 4 @pytest.mark.xfail def test_issue850(): '''The problem here is that the variable-length pattern matches the succeeding token. We then don't handle the ambiguity correctly.''' matcher = Matcher(Vocab( lex_attr_getters={LOWER: lambda string: string.lower()})) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', IS_ANY_TOKEN: True}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) match = matcher(doc) assert len(match) == 1 ent_id, label, start, end = match[0] assert start == 0 assert end == 4
Update regression test for variable-length pattern problem in the matcher.
Update regression test for variable-length pattern problem in the matcher.
Python
mit
aikramer2/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,aikramer2/spaCy,raphael0202/spaCy,explosion/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,explosion/spaCy,recognai/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,explosion/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy
''' Test Matcher matches with '*' operator and Boolean flag ''' from __future__ import unicode_literals + from __future__ import print_function import pytest from ...matcher import Matcher from ...vocab import Vocab from ...attrs import LOWER from ...tokens import Doc + def test_basic_case(): + matcher = Matcher(Vocab( + lex_attr_getters={LOWER: lambda string: string.lower()})) + IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) + matcher.add_pattern( + "FarAway", + [ + {LOWER: "bob"}, + {'OP': '*', LOWER: 'and'}, + {LOWER: 'frank'} + ]) + doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) + match = matcher(doc) + assert len(match) == 1 + ent_id, label, start, end = match[0] + assert start == 0 + assert end == 4 + @pytest.mark.xfail def test_issue850(): + '''The problem here is that the variable-length pattern matches the + succeeding token. We then don't handle the ambiguity correctly.''' - matcher = Matcher(Vocab()) + matcher = Matcher(Vocab( + lex_attr_getters={LOWER: lambda string: string.lower()})) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', IS_ANY_TOKEN: True}, {LOWER: 'frank'} ]) - doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank']) + doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) match = matcher(doc) assert len(match) == 1 - start, end, label, ent_id = match + ent_id, label, start, end = match[0] assert start == 0 assert end == 4
Update regression test for variable-length pattern problem in the matcher.
## Code Before: ''' Test Matcher matches with '*' operator and Boolean flag ''' from __future__ import unicode_literals import pytest from ...matcher import Matcher from ...vocab import Vocab from ...attrs import LOWER from ...tokens import Doc @pytest.mark.xfail def test_issue850(): matcher = Matcher(Vocab()) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', IS_ANY_TOKEN: True}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'cat', 'frank']) match = matcher(doc) assert len(match) == 1 start, end, label, ent_id = match assert start == 0 assert end == 4 ## Instruction: Update regression test for variable-length pattern problem in the matcher. ## Code After: ''' Test Matcher matches with '*' operator and Boolean flag ''' from __future__ import unicode_literals from __future__ import print_function import pytest from ...matcher import Matcher from ...vocab import Vocab from ...attrs import LOWER from ...tokens import Doc def test_basic_case(): matcher = Matcher(Vocab( lex_attr_getters={LOWER: lambda string: string.lower()})) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', LOWER: 'and'}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) match = matcher(doc) assert len(match) == 1 ent_id, label, start, end = match[0] assert start == 0 assert end == 4 @pytest.mark.xfail def test_issue850(): '''The problem here is that the variable-length pattern matches the succeeding token. We then don't handle the ambiguity correctly.''' matcher = Matcher(Vocab( lex_attr_getters={LOWER: lambda string: string.lower()})) IS_ANY_TOKEN = matcher.vocab.add_flag(lambda x: True) matcher.add_pattern( "FarAway", [ {LOWER: "bob"}, {'OP': '*', IS_ANY_TOKEN: True}, {LOWER: 'frank'} ]) doc = Doc(matcher.vocab, words=['bob', 'and', 'and', 'frank']) match = matcher(doc) assert len(match) == 1 ent_id, label, start, end = match[0] assert start == 0 assert end == 4
fa8783f3307582dafcf636f5c94a7e4cff05724b
bin/tree_print_fasta_names.py
bin/tree_print_fasta_names.py
import os import shutil import datetime import sys import argparse from ete3 import Tree import logging DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=read_newick(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
import os import shutil import datetime import sys from ete3 import Tree DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=Tree(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
Fix error in loading trees
Fix error in loading trees Former-commit-id: 6fda03a47c5fa2d65c143ebdd81e158ba5e1ccda
Python
mit
karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle,karel-brinda/prophyle
import os import shutil import datetime import sys - import argparse from ete3 import Tree - - import logging DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn - self.tree=read_newick(tree_newick_fn,format=format) + self.tree=Tree(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
Fix error in loading trees
## Code Before: import os import shutil import datetime import sys import argparse from ete3 import Tree import logging DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=read_newick(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root()) ## Instruction: Fix error in loading trees ## Code After: import os import shutil import datetime import sys from ete3 import Tree DEFAULT_FORMAT = 1 class TreeIndex: def __init__(self,tree_newick_fn,format=DEFAULT_FORMAT): self.tree_newick_fn=tree_newick_fn self.tree=Tree(tree_newick_fn,format=format) def process_node(self,node): if node.is_leaf(): if hasattr(node,"fastapath"): fastas_fn=node.fastapath.split("@") for fasta_fn in fastas_fn: print(fasta_fn) else: children=node.get_children() for child in children: self.process_node(child) if __name__ == "__main__": assert(len(sys.argv)==2) newick_fn=sys.argv[1] ti=TreeIndex( tree_newick_fn=newick_fn, ) ti.process_node(ti.tree.get_tree_root())
a20c6d072d70c535ed1f116fc04016c834ea9c14
doc/en/_getdoctarget.py
doc/en/_getdoctarget.py
import py def get_version_string(): fn = py.path.local(__file__).join("..", "..", "..", "_pytest", "__init__.py") for line in fn.readlines(): if "version" in line: return eval(line.split("=")[-1]) def get_minor_version_string(): return ".".join(get_version_string().split(".")[:2]) if __name__ == "__main__": print (get_minor_version_string())
import py def get_version_string(): fn = py.path.local(__file__).join("..", "..", "..", "_pytest", "__init__.py") for line in fn.readlines(): if "version" in line and not line.strip().startswith('#'): return eval(line.split("=")[-1]) def get_minor_version_string(): return ".".join(get_version_string().split(".")[:2]) if __name__ == "__main__": print (get_minor_version_string())
Fix getdoctarget to ignore comment lines
Fix getdoctarget to ignore comment lines
Python
mit
etataurov/pytest,gabrielcnr/pytest,mbirtwell/pytest,vodik/pytest,The-Compiler/pytest,omarkohl/pytest,Bjwebb/pytest,davidszotten/pytest,gabrielcnr/pytest,mdboom/pytest,ionelmc/pytest,malinoff/pytest,hpk42/pytest,tareqalayan/pytest,userzimmermann/pytest,rouge8/pytest,tgoodlet/pytest,abusalimov/pytest,bukzor/pytest,icemac/pytest,pfctdayelise/pytest,JonathonSonesen/pytest,ionelmc/pytest,alfredodeza/pytest,chiller/pytest,skylarjhdownes/pytest,RonnyPfannschmidt/pytest,Haibo-Wang-ORG/pytest,lukas-bednar/pytest,mhils/pytest,mhils/pytest,chiller/pytest,oleg-alexandrov/pytest,oleg-alexandrov/pytest,MengJueM/pytest,chillbear/pytest,rmfitzpatrick/pytest,tomviner/pytest,Bachmann1234/pytest,pytest-dev/pytest,doordash/pytest,eli-b/pytest,codewarrior0/pytest,flub/pytest,bukzor/pytest,ropez/pytest,Haibo-Wang-ORG/pytest,abusalimov/pytest,mdboom/pytest,MengJueM/pytest,icemac/pytest,The-Compiler/pytest,vmalloc/dessert,codewarrior0/pytest,jb098/pytest,chillbear/pytest,jb098/pytest,omarkohl/pytest,doordash/pytest,mbirtwell/pytest,nicoddemus/pytest,tomviner/pytest,nicoddemus/pytest,ropez/pytest,jaraco/pytest,rouge8/pytest,markshao/pytest,txomon/pytest,lukas-bednar/pytest,Bachmann1234/pytest,userzimmermann/pytest,MichaelAquilina/pytest,vodik/pytest,hpk42/pytest,ddboline/pytest,hackebrot/pytest,JonathonSonesen/pytest,Akasurde/pytest,Bjwebb/pytest
import py def get_version_string(): fn = py.path.local(__file__).join("..", "..", "..", "_pytest", "__init__.py") for line in fn.readlines(): - if "version" in line: + if "version" in line and not line.strip().startswith('#'): return eval(line.split("=")[-1]) def get_minor_version_string(): return ".".join(get_version_string().split(".")[:2]) if __name__ == "__main__": print (get_minor_version_string())
Fix getdoctarget to ignore comment lines
## Code Before: import py def get_version_string(): fn = py.path.local(__file__).join("..", "..", "..", "_pytest", "__init__.py") for line in fn.readlines(): if "version" in line: return eval(line.split("=")[-1]) def get_minor_version_string(): return ".".join(get_version_string().split(".")[:2]) if __name__ == "__main__": print (get_minor_version_string()) ## Instruction: Fix getdoctarget to ignore comment lines ## Code After: import py def get_version_string(): fn = py.path.local(__file__).join("..", "..", "..", "_pytest", "__init__.py") for line in fn.readlines(): if "version" in line and not line.strip().startswith('#'): return eval(line.split("=")[-1]) def get_minor_version_string(): return ".".join(get_version_string().split(".")[:2]) if __name__ == "__main__": print (get_minor_version_string())
efd6fad89131c4d3070c68013ace77f11647bd68
opal/core/search/__init__.py
opal/core/search/__init__.py
from opal.core.search import urls from opal.core import plugins from opal.core import celery # NOQA class SearchPlugin(plugins.OpalPlugin): """ The plugin entrypoint for OPAL's core search functionality """ urls = urls.urlpatterns javascripts = { 'opal.services': [ 'js/search/services/filter.js', 'js/search/services/filters_loader.js', 'js/search/services/filter_resource.js', "js/search/services/paginator.js", ], 'opal.controllers': [ 'js/search/controllers/search.js', 'js/search/controllers/extract.js', "js/search/controllers/save_filter.js", ] } plugins.register(SearchPlugin)
from opal.core import celery # NOQA from opal.core.search import plugin
Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
+ from opal.core import celery # NOQA - from opal.core.search import urls + from opal.core.search import plugin - from opal.core import plugins - - from opal.core import celery # NOQA - - - class SearchPlugin(plugins.OpalPlugin): - """ - The plugin entrypoint for OPAL's core search functionality - """ - urls = urls.urlpatterns - javascripts = { - 'opal.services': [ - 'js/search/services/filter.js', - 'js/search/services/filters_loader.js', - 'js/search/services/filter_resource.js', - "js/search/services/paginator.js", - ], - 'opal.controllers': [ - 'js/search/controllers/search.js', - 'js/search/controllers/extract.js', - "js/search/controllers/save_filter.js", - ] - } - - plugins.register(SearchPlugin) -
Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor
## Code Before: from opal.core.search import urls from opal.core import plugins from opal.core import celery # NOQA class SearchPlugin(plugins.OpalPlugin): """ The plugin entrypoint for OPAL's core search functionality """ urls = urls.urlpatterns javascripts = { 'opal.services': [ 'js/search/services/filter.js', 'js/search/services/filters_loader.js', 'js/search/services/filter_resource.js', "js/search/services/paginator.js", ], 'opal.controllers': [ 'js/search/controllers/search.js', 'js/search/controllers/extract.js', "js/search/controllers/save_filter.js", ] } plugins.register(SearchPlugin) ## Instruction: Move Opal.core.search plugin into a plugins.py ahead of full plugin 2.0 refactor ## Code After: from opal.core import celery # NOQA from opal.core.search import plugin
56a8b900570200e63ee460dd7e2962cba2450b16
preparation/tools/build_assets.py
preparation/tools/build_assets.py
from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert all not in args.resources or len(args.resources) == 1 for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert 'all' not in args.resources or len(args.resources) == 1 if 'all' in args.resources: args.resources = [name.replace('Resource', '') for name in names_registered()] for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
Fix bug with 'all' argument
Fix bug with 'all' argument
Python
mit
hatbot-team/hatbot_resources
from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) - assert all not in args.resources or len(args.resources) == 1 + assert 'all' not in args.resources or len(args.resources) == 1 + if 'all' in args.resources: + args.resources = [name.replace('Resource', '') for name in names_registered()] for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
Fix bug with 'all' argument
## Code Before: from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert all not in args.resources or len(args.resources) == 1 for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main() ## Instruction: Fix bug with 'all' argument ## Code After: from copy import copy import argparse from preparation.resources.Resource import names_registered, resource_by_name from hb_res.storage import get_storage, ExplanationStorage def generate_asset(resource, out_storage: ExplanationStorage): out_storage.clear() for explanation in resource: r = copy(explanation) for functor in resource.modifiers: if r is None: break r = functor(r) if r is not None: out_storage.add_entry(r) def rebuild_trunk(trunk: str): resource = resource_by_name(trunk + 'Resource')() with get_storage(trunk) as out_storage: print("Starting {} generation".format(trunk)) generate_asset(resource, out_storage) print("Finished {} generation".format(trunk)) def make_argparser(): parser = argparse.ArgumentParser(description='Rebuild some asset') names = [name.replace('Resource', '') for name in names_registered()] parser.add_argument('resources', metavar='RESOURCE', nargs='+', choices=names + ['all'], help='One of registered resources ({}) or just \'all\'.'.format(', '.join(names))) return parser def main(args=None): if not isinstance(args, argparse.Namespace): parser = make_argparser() args = parser.parse_args(args) assert 'all' not in args.resources or len(args.resources) == 1 if 'all' in args.resources: args.resources = [name.replace('Resource', '') for name in names_registered()] for name in args.resources: rebuild_trunk(name) if __name__ == '__main__': main()
6167215e4ed49e8a4300f327d5b4ed4540d1a420
numba/tests/npyufunc/test_parallel_env_variable.py
numba/tests/npyufunc/test_parallel_env_variable.py
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: try: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default. Should not fail even if # threads are launched because the value is the same. env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
Fix the parallel env variable test to reset the env correctly
Fix the parallel env variable test to reset the env correctly
Python
bsd-2-clause
seibert/numba,seibert/numba,stonebig/numba,cpcloud/numba,sklam/numba,gmarkall/numba,stuartarchibald/numba,numba/numba,stonebig/numba,seibert/numba,stuartarchibald/numba,sklam/numba,gmarkall/numba,sklam/numba,sklam/numba,stonebig/numba,IntelLabs/numba,IntelLabs/numba,stuartarchibald/numba,cpcloud/numba,numba/numba,stuartarchibald/numba,IntelLabs/numba,stuartarchibald/numba,cpcloud/numba,gmarkall/numba,numba/numba,seibert/numba,IntelLabs/numba,gmarkall/numba,numba/numba,numba/numba,sklam/numba,gmarkall/numba,stonebig/numba,cpcloud/numba,stonebig/numba,IntelLabs/numba,seibert/numba,cpcloud/numba
from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: - try: - self.assertEqual(threads, str(get_thread_count())) + self.assertEqual(threads, str(get_thread_count())) - self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) + self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) - finally: + finally: - # reset the env variable/set to default + # reset the env variable/set to default. Should not fail even if + # threads are launched because the value is the same. - env[key] = current + env[key] = current - config.reload_config() + config.reload_config() if __name__ == '__main__': unittest.main()
Fix the parallel env variable test to reset the env correctly
## Code Before: from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: try: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default env[key] = current config.reload_config() if __name__ == '__main__': unittest.main() ## Instruction: Fix the parallel env variable test to reset the env correctly ## Code After: from numba.np.ufunc.parallel import get_thread_count from os import environ as env from numba.core import config import unittest class TestParallelEnvVariable(unittest.TestCase): """ Tests environment variables related to the underlying "parallel" functions for npyufuncs. """ _numba_parallel_test_ = False def test_num_threads_variable(self): """ Tests the NUMBA_NUM_THREADS env variable behaves as expected. """ key = 'NUMBA_NUM_THREADS' current = str(getattr(env, key, config.NUMBA_DEFAULT_NUM_THREADS)) threads = "3154" env[key] = threads try: config.reload_config() except RuntimeError as e: # This test should fail if threads have already been launched self.assertIn("Cannot set NUMBA_NUM_THREADS", e.args[0]) else: self.assertEqual(threads, str(get_thread_count())) self.assertEqual(threads, str(config.NUMBA_NUM_THREADS)) finally: # reset the env variable/set to default. Should not fail even if # threads are launched because the value is the same. env[key] = current config.reload_config() if __name__ == '__main__': unittest.main()
504205d02ef2f5b66da225390fdb34b8b736ce57
ideascube/migrations/0009_add_a_system_user.py
ideascube/migrations/0009_add_a_system_user.py
from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.db import migrations def add_user(*args): User = get_user_model() User(serial='__system__', full_name='System', password='!!').save() class Migration(migrations.Migration): dependencies = [ ('ideascube', '0008_user_sdb_level'), ('search', '0001_initial'), ] operations = [ migrations.RunPython(add_user, None), ]
from __future__ import unicode_literals from django.db import migrations def add_user(apps, *args): User = apps.get_model('ideascube', 'User') User(serial='__system__', full_name='System', password='!!').save() class Migration(migrations.Migration): dependencies = [ ('ideascube', '0008_user_sdb_level'), ('search', '0001_initial'), ] operations = [ migrations.RunPython(add_user, None), ]
Load user from migration registry when creating system user
Load user from migration registry when creating system user Always load models from the registry in migration files. I hate the idea of touching a migration already released, but this one prevents us from adding new properties to User. If we load the User directly (not from registry) when creating the user model, we'll try to create a user with column that does not exist at the time of this migration.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
from __future__ import unicode_literals - from django.contrib.auth import get_user_model from django.db import migrations - def add_user(*args): + def add_user(apps, *args): - User = get_user_model() + User = apps.get_model('ideascube', 'User') User(serial='__system__', full_name='System', password='!!').save() class Migration(migrations.Migration): dependencies = [ ('ideascube', '0008_user_sdb_level'), ('search', '0001_initial'), ] operations = [ migrations.RunPython(add_user, None), ]
Load user from migration registry when creating system user
## Code Before: from __future__ import unicode_literals from django.contrib.auth import get_user_model from django.db import migrations def add_user(*args): User = get_user_model() User(serial='__system__', full_name='System', password='!!').save() class Migration(migrations.Migration): dependencies = [ ('ideascube', '0008_user_sdb_level'), ('search', '0001_initial'), ] operations = [ migrations.RunPython(add_user, None), ] ## Instruction: Load user from migration registry when creating system user ## Code After: from __future__ import unicode_literals from django.db import migrations def add_user(apps, *args): User = apps.get_model('ideascube', 'User') User(serial='__system__', full_name='System', password='!!').save() class Migration(migrations.Migration): dependencies = [ ('ideascube', '0008_user_sdb_level'), ('search', '0001_initial'), ] operations = [ migrations.RunPython(add_user, None), ]
d8d2e4b763fbd7cedc42046f6f45395bf15caa79
samples/plugins/scenario/scenario_plugin.py
samples/plugins/scenario/scenario_plugin.py
from rally.task.scenarios import base class ScenarioPlugin(base.Scenario): """Sample plugin which lists flavors.""" @base.atomic_action_timer("list_flavors") def _list_flavors(self): """Sample of usage clients - list flavors You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation. """ self.clients("nova").flavors.list() @base.atomic_action_timer("list_flavors_as_admin") def _list_flavors_as_admin(self): """The same with admin clients.""" self.admin_clients("nova").flavors.list() @base.scenario() def list_flavors(self): """List flavors.""" self._list_flavors() self._list_flavors_as_admin()
from rally.plugins.openstack import scenario from rally.task import atomic class ScenarioPlugin(scenario.OpenStackScenario): """Sample plugin which lists flavors.""" @atomic.action_timer("list_flavors") def _list_flavors(self): """Sample of usage clients - list flavors You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation. """ self.clients("nova").flavors.list() @atomic.action_timer("list_flavors_as_admin") def _list_flavors_as_admin(self): """The same with admin clients.""" self.admin_clients("nova").flavors.list() @scenario.configure() def list_flavors(self): """List flavors.""" self._list_flavors() self._list_flavors_as_admin()
Fix the scenario plugin sample
Fix the scenario plugin sample We forgot to fix scenario plugin sample when we were doing rally.task.scenario refactoring Change-Id: Iadbb960cf168bd3b9cd6c1881a5f7a8dffd7036f
Python
apache-2.0
group-policy/rally,eayunstack/rally,openstack/rally,amit0701/rally,paboldin/rally,eonpatapon/rally,cernops/rally,afaheem88/rally,yeming233/rally,vganapath/rally,gluke77/rally,aforalee/RRally,yeming233/rally,openstack/rally,gluke77/rally,gluke77/rally,eayunstack/rally,openstack/rally,aforalee/RRally,cernops/rally,group-policy/rally,openstack/rally,vganapath/rally,amit0701/rally,vganapath/rally,redhat-openstack/rally,eonpatapon/rally,amit0701/rally,gluke77/rally,paboldin/rally,redhat-openstack/rally,paboldin/rally,group-policy/rally,afaheem88/rally,eayunstack/rally,aplanas/rally,vganapath/rally,aplanas/rally
- from rally.task.scenarios import base + from rally.plugins.openstack import scenario + from rally.task import atomic - class ScenarioPlugin(base.Scenario): + class ScenarioPlugin(scenario.OpenStackScenario): """Sample plugin which lists flavors.""" - @base.atomic_action_timer("list_flavors") + @atomic.action_timer("list_flavors") def _list_flavors(self): """Sample of usage clients - list flavors You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation. """ self.clients("nova").flavors.list() - @base.atomic_action_timer("list_flavors_as_admin") + @atomic.action_timer("list_flavors_as_admin") def _list_flavors_as_admin(self): """The same with admin clients.""" self.admin_clients("nova").flavors.list() - @base.scenario() + @scenario.configure() def list_flavors(self): """List flavors.""" self._list_flavors() self._list_flavors_as_admin()
Fix the scenario plugin sample
## Code Before: from rally.task.scenarios import base class ScenarioPlugin(base.Scenario): """Sample plugin which lists flavors.""" @base.atomic_action_timer("list_flavors") def _list_flavors(self): """Sample of usage clients - list flavors You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation. """ self.clients("nova").flavors.list() @base.atomic_action_timer("list_flavors_as_admin") def _list_flavors_as_admin(self): """The same with admin clients.""" self.admin_clients("nova").flavors.list() @base.scenario() def list_flavors(self): """List flavors.""" self._list_flavors() self._list_flavors_as_admin() ## Instruction: Fix the scenario plugin sample ## Code After: from rally.plugins.openstack import scenario from rally.task import atomic class ScenarioPlugin(scenario.OpenStackScenario): """Sample plugin which lists flavors.""" @atomic.action_timer("list_flavors") def _list_flavors(self): """Sample of usage clients - list flavors You can use self.context, self.admin_clients and self.clients which are initialized on scenario instance creation. """ self.clients("nova").flavors.list() @atomic.action_timer("list_flavors_as_admin") def _list_flavors_as_admin(self): """The same with admin clients.""" self.admin_clients("nova").flavors.list() @scenario.configure() def list_flavors(self): """List flavors.""" self._list_flavors() self._list_flavors_as_admin()
68a621005c5a520b7a97c4cad462d43fb7f3aaed
paws/views.py
paws/views.py
from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): request = Request(event, context) resp = self.prepare(request) if resp: return resp kwargs = event.get('pathParameters') or {} func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): kwargs = event.get('pathParameters') or {} self.dispatch(request, **kwargs) def dispatch(self, request, **kwargs): func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
Break out dispatch, and drop prepare. Easier testing
Break out dispatch, and drop prepare. Easier testing
Python
bsd-3-clause
funkybob/paws
from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): - request = Request(event, context) - resp = self.prepare(request) - if resp: - return resp kwargs = event.get('pathParameters') or {} + self.dispatch(request, **kwargs) + + def dispatch(self, request, **kwargs): func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
Break out dispatch, and drop prepare. Easier testing
## Code Before: from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): request = Request(event, context) resp = self.prepare(request) if resp: return resp kwargs = event.get('pathParameters') or {} func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass ## Instruction: Break out dispatch, and drop prepare. Easier testing ## Code After: from .request import Request from .response import Response, response import logging log = logging.getLogger() class View: def __call__(self, event, context): kwargs = event.get('pathParameters') or {} self.dispatch(request, **kwargs) def dispatch(self, request, **kwargs): func = getattr(self, request.method.lower()) try: resp = func(request, **kwargs) except: import traceback log.error(self) log.error(traceback.format_exc()) return response(body='Internal server Error', status=500) if isinstance(resp, Response): resp = resp.render() return resp def prepare(self, request): pass
d4d448adff71b609d5efb269d1a9a2ea4aba3590
radio/templatetags/radio_js_config.py
radio/templatetags/radio_js_config.py
import random import json from django import template from django.conf import settings register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
import random import json from django import template from django.conf import settings from radio.models import SiteOption register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val for opt in SiteOption.objects.filter(javascript_visible=True): js_json[opt.name] = opt.value_boolean_or_string() js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
Allow SiteOption to load into the JS
Allow SiteOption to load into the JS
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
import random import json from django import template from django.conf import settings + + from radio.models import SiteOption register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val + for opt in SiteOption.objects.filter(javascript_visible=True): + js_json[opt.name] = opt.value_boolean_or_string() js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
Allow SiteOption to load into the JS
## Code Before: import random import json from django import template from django.conf import settings register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json) ## Instruction: Allow SiteOption to load into the JS ## Code After: import random import json from django import template from django.conf import settings from radio.models import SiteOption register = template.Library() # Build json value to pass as js config @register.simple_tag() def trunkplayer_js_config(user): js_settings = getattr(settings, 'JS_SETTINGS', None) js_json = {} if js_settings: for setting in js_settings: set_val = getattr(settings, setting, '') js_json[setting] = set_val for opt in SiteOption.objects.filter(javascript_visible=True): js_json[opt.name] = opt.value_boolean_or_string() js_json['user_is_staff'] = user.is_staff if user.is_authenticated(): js_json['user_is_authenticated'] = True else: js_json['user_is_authenticated'] = False js_json['radio_change_unit'] = user.has_perm('radio.change_unit') return json.dumps(js_json)
0a13a9a8a779102dbcb2beead7d8aa9143f4c79b
tests/pytests/unit/client/ssh/test_shell.py
tests/pytests/unit/client/ssh/test_shell.py
import os import subprocess import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" yield {"pub_key": str(pub_key), "priv_key": str(priv_key)} @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) class TestSSHShell: def test_ssh_shell_key_gen(self, keys): """ Test ssh key_gen """ shell.gen_key(keys["priv_key"]) for fp in keys.keys(): assert os.path.exists(keys[fp]) # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
import subprocess import types import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) def test_ssh_shell_key_gen(keys): """ Test ssh key_gen """ shell.gen_key(str(keys.priv_key)) assert keys.priv_key.exists() assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
Use commit suggestion to use types
Use commit suggestion to use types Co-authored-by: Pedro Algarvio <4410d99cefe57ec2c2cdbd3f1d5cf862bb4fb6f8@algarvio.me>
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
- import os import subprocess + import types import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" - yield {"pub_key": str(pub_key), "priv_key": str(priv_key)} + return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) - class TestSSHShell: - def test_ssh_shell_key_gen(self, keys): + def test_ssh_shell_key_gen(keys): - """ + """ - Test ssh key_gen + Test ssh key_gen - """ + """ - shell.gen_key(keys["priv_key"]) + shell.gen_key(str(keys.priv_key)) - for fp in keys.keys(): - assert os.path.exists(keys[fp]) + assert keys.priv_key.exists() + assert keys.pub_key.exists() + # verify there is not a passphrase set on key + ret = subprocess.check_output( + ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, + ) + assert ret.decode().startswith("ssh-rsa") - # verify there is not a passphrase set on key - ret = subprocess.check_output( - ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30, - ) - assert ret.decode().startswith("ssh-rsa") -
Use commit suggestion to use types
## Code Before: import os import subprocess import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" yield {"pub_key": str(pub_key), "priv_key": str(priv_key)} @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) class TestSSHShell: def test_ssh_shell_key_gen(self, keys): """ Test ssh key_gen """ shell.gen_key(keys["priv_key"]) for fp in keys.keys(): assert os.path.exists(keys[fp]) # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", keys["priv_key"], "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa") ## Instruction: Use commit suggestion to use types ## Code After: import subprocess import types import pytest import salt.client.ssh.shell as shell @pytest.fixture def keys(tmp_path): pub_key = tmp_path / "ssh" / "testkey.pub" priv_key = tmp_path / "ssh" / "testkey" return types.SimpleNamespace(pub_key=pub_key, priv_key=priv_key) @pytest.mark.skip_on_windows(reason="Windows does not support salt-ssh") @pytest.mark.skip_if_binaries_missing("ssh", "ssh-keygen", check_all=True) def test_ssh_shell_key_gen(keys): """ Test ssh key_gen """ shell.gen_key(str(keys.priv_key)) assert keys.priv_key.exists() assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, ) assert ret.decode().startswith("ssh-rsa")
09d780474d00f3a8f4c2295154d74dae2023c1d3
samples/storage_sample/storage/__init__.py
samples/storage_sample/storage/__init__.py
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
Drop the CLI from the sample storage client imports.
Drop the CLI from the sample storage client imports.
Python
apache-2.0
cherba/apitools,craigcitro/apitools,b-daniels/apitools,betamos/apitools,kevinli7/apitools,houglum/apitools,pcostell/apitools,thobrla/apitools,google/apitools
"""Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * - from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
Drop the CLI from the sample storage client imports.
## Code Before: """Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1 import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__) ## Instruction: Drop the CLI from the sample storage client imports. ## Code After: """Common imports for generated storage client library.""" # pylint:disable=wildcard-import import pkgutil from apitools.base.py import * from storage_v1_client import * from storage_v1_messages import * __path__ = pkgutil.extend_path(__path__, __name__)
08d838e87bd92dacbbbfe31b19c628b9d3b271a8
src/plone.example/plone/example/todo.py
src/plone.example/plone/example/todo.py
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
Set default values for fields
Set default values for fields
Python
bsd-2-clause
plone/plone.server,plone/plone.server
from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", + default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", + default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
Set default values for fields
## Code Before: from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass ## Instruction: Set default values for fields ## Code After: from plone.dexterity.interfaces import IDexterityContent from plone.dexterity.interfaces import IFormFieldProvider from plone.server.api.service import Service from plone.supermodel import model from zope import schema from zope.component import adapter from zope.dublincore.annotatableadapter import ZDCAnnotatableAdapter from zope.dublincore.interfaces import IWriteZopeDublinCore from zope.interface import provider class ITodo(model.Schema): title = schema.TextLine( title=u"Title", required=False, description=u"It's a title", default=u'' ) done = schema.Bool( title=u"Done", required=False, description=u"Has the task been completed?", default=False ) class View(Service): def __init__(self, context, request): self.context = context self.request = request async def __call__(self): return { 'context': str(self.context), 'portal_type': self.context.portal_type, } @provider(IFormFieldProvider) class IDublinCore(IWriteZopeDublinCore): """ We basically just want the IFormFieldProvider interface applied There's probably a zcml way of doing this. """ @adapter(IDexterityContent) class DublinCore(ZDCAnnotatableAdapter): pass
29a964a64230e26fca550e81a1ecba3dd782dfb1
python/vtd.py
python/vtd.py
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name)
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system if 'my_system' not in globals(): my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name) my_system.Refresh()
Refresh system instead of clobbering it
Refresh system instead of clobbering it Otherwise, if we set the Contexts, they'll be gone before we can request the NextActions!
Python
apache-2.0
chiphogg/vim-vtd
import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system + if 'my_system' not in globals(): - my_system = libvtd.trusted_system.TrustedSystem() + my_system = libvtd.trusted_system.TrustedSystem() - my_system.AddFile(file_name) + my_system.AddFile(file_name) + my_system.Refresh()
Refresh system instead of clobbering it
## Code Before: import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name) ## Instruction: Refresh system instead of clobbering it ## Code After: import libvtd.trusted_system def UpdateTrustedSystem(file_name): """Make sure the TrustedSystem object is up to date.""" global my_system if 'my_system' not in globals(): my_system = libvtd.trusted_system.TrustedSystem() my_system.AddFile(file_name) my_system.Refresh()
b532ffff18e95b6014921d88b6df075e8ac2c4ec
problib/example1/__init__.py
problib/example1/__init__.py
from sympy import symbols, cos, sin, latex from mathdeck import rand, answer metadata = { 'author': 'Bob Hope', 'institution': 'University of Missouri', 'subject': 'algebra', 'minor subject': 'polynomial equations', 'tags': ['simplify','roots','intervals'] } r = rand.Random() # choose three random integers between 0 and 10. root1 = r.randint(0,10) root2 = r.randint(0,10) root3 = r.randint(0,10) # # # specify our variables x = symbols('x') p = ((x-root1)*(x-root2)).expand(basic=True) template_variables = { 'p': latex(p), } a1 = answer.Answer() a1.value = cos(x)**2-sin(x)**2 a1.type = 'function' a1.variables = ['x'] a1.domain = 'R' a2 = answer.Answer() a2.value = 'x+1' a2.type = "function" a2.variables = ['x','y'] answers = { 'ans1': a1, 'ans2': a2 }
from sympy import symbols, cos, sin, latex from mathdeck import rand, answer metadata = { 'author': 'Bob Hope', 'institution': 'University of Missouri', 'subject': 'algebra', 'minor subject': 'polynomial equations', 'tags': ['simplify','roots','intervals'] } r = rand.Random() # choose three random integers between 0 and 10. root1 = r.randint(0,10) root2 = r.randint(0,10) root3 = r.randint(0,10) # # # specify our variables x = symbols('x') p = ((x-root1)*(x-root2)).expand(basic=True) func = cos(x)**2-sin(x)**2 a1 = answer.Answer( value=func, type='function', vars=['x']) a2 = answer.Answer(value='x+1',type='function',vars=['x']) answers = { 'ans1': a1, 'ans2': a2 } template_variables = { 'p': latex(p), }
Update mathdeck problib for new Answer refactoring
Update mathdeck problib for new Answer refactoring
Python
apache-2.0
patrickspencer/mathdeck,patrickspencer/mathdeck
from sympy import symbols, cos, sin, latex from mathdeck import rand, answer metadata = { 'author': 'Bob Hope', 'institution': 'University of Missouri', 'subject': 'algebra', 'minor subject': 'polynomial equations', 'tags': ['simplify','roots','intervals'] } r = rand.Random() # choose three random integers between 0 and 10. root1 = r.randint(0,10) root2 = r.randint(0,10) root3 = r.randint(0,10) # # # specify our variables x = symbols('x') p = ((x-root1)*(x-root2)).expand(basic=True) + func = cos(x)**2-sin(x)**2 - template_variables = { - 'p': latex(p), - } - a1 = answer.Answer() + a1 = answer.Answer( + value=func, + type='function', + vars=['x']) + a2 = answer.Answer(value='x+1',type='function',vars=['x']) - a1.value = cos(x)**2-sin(x)**2 - a1.type = 'function' - a1.variables = ['x'] - a1.domain = 'R' - - a2 = answer.Answer() - a2.value = 'x+1' - a2.type = "function" - a2.variables = ['x','y'] answers = { 'ans1': a1, 'ans2': a2 } + template_variables = { + 'p': latex(p), + } +
Update mathdeck problib for new Answer refactoring
## Code Before: from sympy import symbols, cos, sin, latex from mathdeck import rand, answer metadata = { 'author': 'Bob Hope', 'institution': 'University of Missouri', 'subject': 'algebra', 'minor subject': 'polynomial equations', 'tags': ['simplify','roots','intervals'] } r = rand.Random() # choose three random integers between 0 and 10. root1 = r.randint(0,10) root2 = r.randint(0,10) root3 = r.randint(0,10) # # # specify our variables x = symbols('x') p = ((x-root1)*(x-root2)).expand(basic=True) template_variables = { 'p': latex(p), } a1 = answer.Answer() a1.value = cos(x)**2-sin(x)**2 a1.type = 'function' a1.variables = ['x'] a1.domain = 'R' a2 = answer.Answer() a2.value = 'x+1' a2.type = "function" a2.variables = ['x','y'] answers = { 'ans1': a1, 'ans2': a2 } ## Instruction: Update mathdeck problib for new Answer refactoring ## Code After: from sympy import symbols, cos, sin, latex from mathdeck import rand, answer metadata = { 'author': 'Bob Hope', 'institution': 'University of Missouri', 'subject': 'algebra', 'minor subject': 'polynomial equations', 'tags': ['simplify','roots','intervals'] } r = rand.Random() # choose three random integers between 0 and 10. root1 = r.randint(0,10) root2 = r.randint(0,10) root3 = r.randint(0,10) # # # specify our variables x = symbols('x') p = ((x-root1)*(x-root2)).expand(basic=True) func = cos(x)**2-sin(x)**2 a1 = answer.Answer( value=func, type='function', vars=['x']) a2 = answer.Answer(value='x+1',type='function',vars=['x']) answers = { 'ans1': a1, 'ans2': a2 } template_variables = { 'p': latex(p), }
3a9568b4d4de969b1e2031e8d2d3cdd7bd56824f
zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py
zerver/migrations/0237_rename_zulip_realm_to_zulipinternal.py
from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return if not Realm.objects.filter(string_id="zulip").exists(): # If the user renamed the `zulip` system bot realm (or deleted # it), there's nothing for us to do. return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
Fix zulipinternal migration corner case.
migrations: Fix zulipinternal migration corner case. It's theoretically possible to have configured a Zulip server where the system bots live in the same realm as normal users (and may have in fact been the default in early Zulip releases? Unclear.). We should handle these without the migration intended to clean up naming for the system bot realm crashing. Fixes #13660.
Python
apache-2.0
brainwane/zulip,andersk/zulip,hackerkid/zulip,synicalsyntax/zulip,andersk/zulip,hackerkid/zulip,punchagan/zulip,shubhamdhama/zulip,showell/zulip,zulip/zulip,synicalsyntax/zulip,kou/zulip,rht/zulip,showell/zulip,brainwane/zulip,punchagan/zulip,shubhamdhama/zulip,hackerkid/zulip,andersk/zulip,kou/zulip,brainwane/zulip,brainwane/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,kou/zulip,punchagan/zulip,zulip/zulip,kou/zulip,showell/zulip,brainwane/zulip,eeshangarg/zulip,timabbott/zulip,eeshangarg/zulip,hackerkid/zulip,shubhamdhama/zulip,zulip/zulip,timabbott/zulip,brainwane/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,timabbott/zulip,rht/zulip,synicalsyntax/zulip,andersk/zulip,showell/zulip,shubhamdhama/zulip,rht/zulip,hackerkid/zulip,rht/zulip,hackerkid/zulip,eeshangarg/zulip,kou/zulip,synicalsyntax/zulip,brainwane/zulip,shubhamdhama/zulip,eeshangarg/zulip,andersk/zulip,rht/zulip,timabbott/zulip,punchagan/zulip,showell/zulip,eeshangarg/zulip,synicalsyntax/zulip,punchagan/zulip,timabbott/zulip,zulip/zulip,andersk/zulip,punchagan/zulip,zulip/zulip,hackerkid/zulip,timabbott/zulip,synicalsyntax/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,kou/zulip,punchagan/zulip,synicalsyntax/zulip,rht/zulip,kou/zulip,timabbott/zulip,shubhamdhama/zulip
from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): + return + if not Realm.objects.filter(string_id="zulip").exists(): + # If the user renamed the `zulip` system bot realm (or deleted + # it), there's nothing for us to do. return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
Fix zulipinternal migration corner case.
## Code Before: from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ] ## Instruction: Fix zulipinternal migration corner case. ## Code After: from django.conf import settings from django.db import migrations from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def rename_zulip_realm_to_zulipinternal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: if not settings.PRODUCTION: return Realm = apps.get_model('zerver', 'Realm') UserProfile = apps.get_model('zerver', 'UserProfile') if Realm.objects.count() == 0: # Database not yet populated, do nothing: return if Realm.objects.filter(string_id="zulipinternal").exists(): return if not Realm.objects.filter(string_id="zulip").exists(): # If the user renamed the `zulip` system bot realm (or deleted # it), there's nothing for us to do. return internal_realm = Realm.objects.get(string_id="zulip") # For safety, as a sanity check, verify that "internal_realm" is indeed the realm for system bots: welcome_bot = UserProfile.objects.get(email="welcome-bot@zulip.com") assert welcome_bot.realm.id == internal_realm.id internal_realm.string_id = "zulipinternal" internal_realm.name = "System use only" internal_realm.save() class Migration(migrations.Migration): dependencies = [ ('zerver', '0236_remove_illegal_characters_email_full'), ] operations = [ migrations.RunPython(rename_zulip_realm_to_zulipinternal) ]
97e3b202bbe6726a4056facb8b4690b0710029a9
handroll/tests/test_site.py
handroll/tests/test_site.py
import os import tempfile from handroll.site import Site from handroll.tests import TestCase class TestSite(TestCase): def test_finds_valid_site_root_from_templates(self): original = os.getcwd() valid_site = tempfile.mkdtemp() open(os.path.join(valid_site, 'template.html'), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_finds_valid_site_root_from_conf(self): original = os.getcwd() valid_site = tempfile.mkdtemp() open(os.path.join(valid_site, Site.CONFIG), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_site_has_absolute_path(self): original = os.getcwd() tempdir = tempfile.mkdtemp() site_path = os.path.join(tempdir, 'site') os.mkdir(site_path) os.chdir(tempdir) site = Site('site') self.assertEqual(site_path, site.path) os.chdir(original)
import os import tempfile from handroll.site import Site from handroll.tests import TestCase class TestSite(TestCase): def test_finds_valid_site_root_from_templates(self): original = os.getcwd() valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, 'template.html'), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_finds_valid_site_root_from_conf(self): original = os.getcwd() valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, Site.CONFIG), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_site_has_absolute_path(self): original = os.getcwd() tempdir = os.path.realpath(tempfile.mkdtemp()) site_path = os.path.join(tempdir, 'site') os.mkdir(site_path) os.chdir(tempdir) site = Site('site') self.assertEqual(site_path, site.path) os.chdir(original)
Use a real path when testing sites.
Use a real path when testing sites. Mac OS X returns link paths when calling `mkdtemp`. Calling realpath allows the site path comparison to be consistent across platforms.
Python
bsd-2-clause
handroll/handroll
import os import tempfile from handroll.site import Site from handroll.tests import TestCase class TestSite(TestCase): def test_finds_valid_site_root_from_templates(self): original = os.getcwd() - valid_site = tempfile.mkdtemp() + valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, 'template.html'), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_finds_valid_site_root_from_conf(self): original = os.getcwd() - valid_site = tempfile.mkdtemp() + valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, Site.CONFIG), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_site_has_absolute_path(self): original = os.getcwd() - tempdir = tempfile.mkdtemp() + tempdir = os.path.realpath(tempfile.mkdtemp()) site_path = os.path.join(tempdir, 'site') os.mkdir(site_path) os.chdir(tempdir) site = Site('site') self.assertEqual(site_path, site.path) os.chdir(original)
Use a real path when testing sites.
## Code Before: import os import tempfile from handroll.site import Site from handroll.tests import TestCase class TestSite(TestCase): def test_finds_valid_site_root_from_templates(self): original = os.getcwd() valid_site = tempfile.mkdtemp() open(os.path.join(valid_site, 'template.html'), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_finds_valid_site_root_from_conf(self): original = os.getcwd() valid_site = tempfile.mkdtemp() open(os.path.join(valid_site, Site.CONFIG), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_site_has_absolute_path(self): original = os.getcwd() tempdir = tempfile.mkdtemp() site_path = os.path.join(tempdir, 'site') os.mkdir(site_path) os.chdir(tempdir) site = Site('site') self.assertEqual(site_path, site.path) os.chdir(original) ## Instruction: Use a real path when testing sites. ## Code After: import os import tempfile from handroll.site import Site from handroll.tests import TestCase class TestSite(TestCase): def test_finds_valid_site_root_from_templates(self): original = os.getcwd() valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, 'template.html'), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_finds_valid_site_root_from_conf(self): original = os.getcwd() valid_site = os.path.realpath(tempfile.mkdtemp()) open(os.path.join(valid_site, Site.CONFIG), 'w').close() os.chdir(valid_site) site = Site() self.assertEqual(valid_site, site.path) os.chdir(original) def test_site_has_absolute_path(self): original = os.getcwd() tempdir = os.path.realpath(tempfile.mkdtemp()) site_path = os.path.join(tempdir, 'site') os.mkdir(site_path) os.chdir(tempdir) site = Site('site') self.assertEqual(site_path, site.path) os.chdir(original)
7e44a8bd38105144111624710819a1ee54891222
campos_checkin/__openerp__.py
campos_checkin/__openerp__.py
{ 'name': 'Campos Checkin', 'description': """ CampOS Check In functionality""", 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'Stein & Gabelgaard ApS', 'website': 'www.steingabelgaard.dk', 'depends': [ 'campos_jobber_final', 'campos_transportation', 'campos_crewnet', 'web_ir_actions_act_window_message', #'web_tree_dynamic_colored_field', ], 'data': [ 'wizards/campos_checkin_grp_wiz.xml', 'views/event_registration.xml', 'wizards/campos_checkin_wiz.xml', 'security/campos_checkin.xml', 'views/campos_event_participant.xml', 'views/campos_mat_report.xml', ], 'demo': [ ], }
{ 'name': 'Campos Checkin', 'description': """ CampOS Check In functionality""", 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'Stein & Gabelgaard ApS', 'website': 'www.steingabelgaard.dk', 'depends': [ 'campos_jobber_final', 'campos_transportation', 'campos_crewnet', 'web_ir_actions_act_window_message', #'web_tree_dynamic_colored_field', ], 'data': [ 'wizards/campos_checkin_wiz.xml', 'security/campos_checkin.xml', 'views/campos_event_participant.xml', 'views/campos_mat_report.xml', 'wizards/campos_checkin_grp_wiz.xml', 'views/event_registration.xml', ], 'demo': [ ], }
Fix order for menu ref
Fix order for menu ref
Python
agpl-3.0
sl2017/campos
{ 'name': 'Campos Checkin', 'description': """ CampOS Check In functionality""", 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'Stein & Gabelgaard ApS', 'website': 'www.steingabelgaard.dk', 'depends': [ 'campos_jobber_final', 'campos_transportation', 'campos_crewnet', 'web_ir_actions_act_window_message', #'web_tree_dynamic_colored_field', ], 'data': [ - 'wizards/campos_checkin_grp_wiz.xml', - 'views/event_registration.xml', 'wizards/campos_checkin_wiz.xml', 'security/campos_checkin.xml', 'views/campos_event_participant.xml', 'views/campos_mat_report.xml', + 'wizards/campos_checkin_grp_wiz.xml', + 'views/event_registration.xml', ], 'demo': [ ], }
Fix order for menu ref
## Code Before: { 'name': 'Campos Checkin', 'description': """ CampOS Check In functionality""", 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'Stein & Gabelgaard ApS', 'website': 'www.steingabelgaard.dk', 'depends': [ 'campos_jobber_final', 'campos_transportation', 'campos_crewnet', 'web_ir_actions_act_window_message', #'web_tree_dynamic_colored_field', ], 'data': [ 'wizards/campos_checkin_grp_wiz.xml', 'views/event_registration.xml', 'wizards/campos_checkin_wiz.xml', 'security/campos_checkin.xml', 'views/campos_event_participant.xml', 'views/campos_mat_report.xml', ], 'demo': [ ], } ## Instruction: Fix order for menu ref ## Code After: { 'name': 'Campos Checkin', 'description': """ CampOS Check In functionality""", 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'Stein & Gabelgaard ApS', 'website': 'www.steingabelgaard.dk', 'depends': [ 'campos_jobber_final', 'campos_transportation', 'campos_crewnet', 'web_ir_actions_act_window_message', #'web_tree_dynamic_colored_field', ], 'data': [ 'wizards/campos_checkin_wiz.xml', 'security/campos_checkin.xml', 'views/campos_event_participant.xml', 'views/campos_mat_report.xml', 'wizards/campos_checkin_grp_wiz.xml', 'views/event_registration.xml', ], 'demo': [ ], }
3cd99c23099a625da711e3ac458a46a7b364d83c
hystrix/pool.py
hystrix/pool.py
from __future__ import absolute_import from concurrent.futures import ThreadPoolExecutor import logging import six log = logging.getLogger(__name__) class PoolMetaclass(type): __instances__ = dict() __blacklist__ = ('Pool', 'PoolMetaclass') def __new__(cls, name, bases, attrs): if name in cls.__blacklist__: return super(PoolMetaclass, cls).__new__(cls, name, bases, attrs) pool_key = attrs.get('pool_key') or '{}Pool'.format(name) new_class = super(PoolMetaclass, cls).__new__(cls, pool_key, bases, attrs) setattr(new_class, 'pool_key', pool_key) if pool_key not in cls.__instances__: cls.__instances__[pool_key] = new_class return cls.__instances__[pool_key] class Pool(six.with_metaclass(PoolMetaclass, ThreadPoolExecutor)): pool_key = None def __init__(self, pool_key=None, max_workers=5): super(Pool, self).__init__(max_workers)
from __future__ import absolute_import from concurrent.futures import ProcessPoolExecutor import logging import six log = logging.getLogger(__name__) class PoolMetaclass(type): __instances__ = dict() __blacklist__ = ('Pool', 'PoolMetaclass') def __new__(cls, name, bases, attrs): if name in cls.__blacklist__: return super(PoolMetaclass, cls).__new__(cls, name, bases, attrs) pool_key = attrs.get('pool_key') or '{}Pool'.format(name) new_class = super(PoolMetaclass, cls).__new__(cls, pool_key, bases, attrs) setattr(new_class, 'pool_key', pool_key) if pool_key not in cls.__instances__: cls.__instances__[pool_key] = new_class return cls.__instances__[pool_key] class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)): pool_key = None def __init__(self, pool_key=None, max_workers=5): super(Pool, self).__init__(max_workers)
Change Pool to use ProcessPoolExecutor
Change Pool to use ProcessPoolExecutor
Python
apache-2.0
wiliamsouza/hystrix-py,wiliamsouza/hystrix-py
from __future__ import absolute_import - from concurrent.futures import ThreadPoolExecutor + from concurrent.futures import ProcessPoolExecutor import logging import six log = logging.getLogger(__name__) class PoolMetaclass(type): __instances__ = dict() __blacklist__ = ('Pool', 'PoolMetaclass') def __new__(cls, name, bases, attrs): if name in cls.__blacklist__: return super(PoolMetaclass, cls).__new__(cls, name, bases, attrs) pool_key = attrs.get('pool_key') or '{}Pool'.format(name) new_class = super(PoolMetaclass, cls).__new__(cls, pool_key, bases, attrs) setattr(new_class, 'pool_key', pool_key) if pool_key not in cls.__instances__: cls.__instances__[pool_key] = new_class return cls.__instances__[pool_key] - class Pool(six.with_metaclass(PoolMetaclass, ThreadPoolExecutor)): + class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)): pool_key = None def __init__(self, pool_key=None, max_workers=5): super(Pool, self).__init__(max_workers)
Change Pool to use ProcessPoolExecutor
## Code Before: from __future__ import absolute_import from concurrent.futures import ThreadPoolExecutor import logging import six log = logging.getLogger(__name__) class PoolMetaclass(type): __instances__ = dict() __blacklist__ = ('Pool', 'PoolMetaclass') def __new__(cls, name, bases, attrs): if name in cls.__blacklist__: return super(PoolMetaclass, cls).__new__(cls, name, bases, attrs) pool_key = attrs.get('pool_key') or '{}Pool'.format(name) new_class = super(PoolMetaclass, cls).__new__(cls, pool_key, bases, attrs) setattr(new_class, 'pool_key', pool_key) if pool_key not in cls.__instances__: cls.__instances__[pool_key] = new_class return cls.__instances__[pool_key] class Pool(six.with_metaclass(PoolMetaclass, ThreadPoolExecutor)): pool_key = None def __init__(self, pool_key=None, max_workers=5): super(Pool, self).__init__(max_workers) ## Instruction: Change Pool to use ProcessPoolExecutor ## Code After: from __future__ import absolute_import from concurrent.futures import ProcessPoolExecutor import logging import six log = logging.getLogger(__name__) class PoolMetaclass(type): __instances__ = dict() __blacklist__ = ('Pool', 'PoolMetaclass') def __new__(cls, name, bases, attrs): if name in cls.__blacklist__: return super(PoolMetaclass, cls).__new__(cls, name, bases, attrs) pool_key = attrs.get('pool_key') or '{}Pool'.format(name) new_class = super(PoolMetaclass, cls).__new__(cls, pool_key, bases, attrs) setattr(new_class, 'pool_key', pool_key) if pool_key not in cls.__instances__: cls.__instances__[pool_key] = new_class return cls.__instances__[pool_key] class Pool(six.with_metaclass(PoolMetaclass, ProcessPoolExecutor)): pool_key = None def __init__(self, pool_key=None, max_workers=5): super(Pool, self).__init__(max_workers)
c52edc120f38acb079fa364cdb684fc2052d4727
corehq/messaging/smsbackends/trumpia/urls.py
corehq/messaging/smsbackends/trumpia/urls.py
from django.conf.urls import url from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView urlpatterns = [ url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(), name=TrumpiaIncomingView.urlname), ]
from django.conf.urls import url from corehq.apps.hqwebapp.decorators import waf_allow from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView urlpatterns = [ url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()), name=TrumpiaIncomingView.urlname), ]
Annotate trumpia url to say it allows XML in the querystring
Annotate trumpia url to say it allows XML in the querystring
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from django.conf.urls import url + + from corehq.apps.hqwebapp.decorators import waf_allow from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView urlpatterns = [ - url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(), + url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()), name=TrumpiaIncomingView.urlname), ]
Annotate trumpia url to say it allows XML in the querystring
## Code Before: from django.conf.urls import url from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView urlpatterns = [ url(r'^sms/(?P<api_key>[\w-]+)/?$', TrumpiaIncomingView.as_view(), name=TrumpiaIncomingView.urlname), ] ## Instruction: Annotate trumpia url to say it allows XML in the querystring ## Code After: from django.conf.urls import url from corehq.apps.hqwebapp.decorators import waf_allow from corehq.messaging.smsbackends.trumpia.views import TrumpiaIncomingView urlpatterns = [ url(r'^sms/(?P<api_key>[\w-]+)/?$', waf_allow('XSS_QUERYSTRING')(TrumpiaIncomingView.as_view()), name=TrumpiaIncomingView.urlname), ]
d159f8201b9d9aeafd24f07a9e39855fc537182d
cocoscore/tools/data_tools.py
cocoscore/tools/data_tools.py
import pandas as pd def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True): """ Load a sentence data set as pandas DataFrame from a given path. :param data_frame_path: the path to load the pandas DataFrame from :param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ... :param class_labels: if True, the class label is assumed to be present as the last column :return: a pandas DataFrame loaded from the given path """ column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text'] if class_labels: column_names.append('class') data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False, names=column_names) if sort_reindex: data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort') data_df.reset_index(inplace=True, drop=True) assert data_df.isnull().sum().sum() == 0 return data_df
import pandas as pd def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False): """ Load a sentence data set as pandas DataFrame from a given path. :param data_frame_path: the path to load the pandas DataFrame from :param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ... :param class_labels: if True, the class label is assumed to be present as the second-to-last column :param match_distance: if True, the distance between the closest match is assumed to be present as the last column :return: a pandas DataFrame loaded from the given path """ column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text'] if class_labels: column_names.append('class') if match_distance: column_names.append('distance') data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False, names=column_names) if sort_reindex: data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort') data_df.reset_index(inplace=True, drop=True) assert data_df.isnull().sum().sum() == 0 return data_df
Add match_distance flag to load_data_frame()
Add match_distance flag to load_data_frame()
Python
mit
JungeAlexander/cocoscore
import pandas as pd - def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True): + def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False): """ Load a sentence data set as pandas DataFrame from a given path. :param data_frame_path: the path to load the pandas DataFrame from :param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ... - :param class_labels: if True, the class label is assumed to be present as the last column + :param class_labels: if True, the class label is assumed to be present as the second-to-last column + :param match_distance: if True, the distance between the closest match is assumed to be present as the last column :return: a pandas DataFrame loaded from the given path """ column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text'] if class_labels: column_names.append('class') + if match_distance: + column_names.append('distance') data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False, names=column_names) if sort_reindex: data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort') data_df.reset_index(inplace=True, drop=True) assert data_df.isnull().sum().sum() == 0 return data_df
Add match_distance flag to load_data_frame()
## Code Before: import pandas as pd def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True): """ Load a sentence data set as pandas DataFrame from a given path. :param data_frame_path: the path to load the pandas DataFrame from :param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ... :param class_labels: if True, the class label is assumed to be present as the last column :return: a pandas DataFrame loaded from the given path """ column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text'] if class_labels: column_names.append('class') data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False, names=column_names) if sort_reindex: data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort') data_df.reset_index(inplace=True, drop=True) assert data_df.isnull().sum().sum() == 0 return data_df ## Instruction: Add match_distance flag to load_data_frame() ## Code After: import pandas as pd def load_data_frame(data_frame_path, sort_reindex=False, class_labels=True, match_distance=False): """ Load a sentence data set as pandas DataFrame from a given path. :param data_frame_path: the path to load the pandas DataFrame from :param sort_reindex: if True, the returned data frame will be sorted by PMID and reindex by 0, 1, 2, ... :param class_labels: if True, the class label is assumed to be present as the second-to-last column :param match_distance: if True, the distance between the closest match is assumed to be present as the last column :return: a pandas DataFrame loaded from the given path """ column_names = ['pmid', 'paragraph', 'sentence', 'entity1', 'entity2', 'sentence_text'] if class_labels: column_names.append('class') if match_distance: column_names.append('distance') data_df = pd.read_csv(data_frame_path, sep='\t', header=None, index_col=False, names=column_names) if sort_reindex: data_df.sort_values('pmid', axis=0, inplace=True, kind='mergesort') data_df.reset_index(inplace=True, drop=True) assert data_df.isnull().sum().sum() == 0 return data_df
920e2fbb7e99c17dbe8d5b71e9c9b26a718ca444
ideascube/search/apps.py
ideascube/search/apps.py
from django.apps import AppConfig from django.db.models.signals import pre_migrate, post_migrate from .utils import create_index_table, reindex_content def create_index(sender, **kwargs): if isinstance(sender, SearchConfig): create_index_table(force=True) def reindex(sender, **kwargs): if isinstance(sender, SearchConfig): reindex_content(force=False) class SearchConfig(AppConfig): name = 'ideascube.search' verbose_name = 'Search' def ready(self): pre_migrate.connect(create_index, sender=self) post_migrate.connect(reindex, sender=self)
from django.apps import AppConfig from django.db.models.signals import pre_migrate, post_migrate from .utils import create_index_table, reindex_content def create_index(sender, **kwargs): if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): create_index_table(force=True) def reindex(sender, **kwargs): if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): reindex_content(force=False) class SearchConfig(AppConfig): name = 'ideascube.search' verbose_name = 'Search' def ready(self): pre_migrate.connect(create_index, sender=self) post_migrate.connect(reindex, sender=self)
Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
Make (pre|post)_migrate scripts for the index table only if working on 'transient'. Django run (pre|post)_migrate script once per database. As we have two databases, the create_index is launch twice with different kwargs['using'] ('default' and 'transient'). We should try to create the index table only when we are working on the transient database. Most of the time, this is not important and create a new index table twice is not important. However, if we run tests, the database are configured and migrate one after the other and the 'transient' database may be miss-configured at a time. By creating the table only at the right time, we ensure that everything is properly configured.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
from django.apps import AppConfig from django.db.models.signals import pre_migrate, post_migrate from .utils import create_index_table, reindex_content def create_index(sender, **kwargs): - if isinstance(sender, SearchConfig): + if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): create_index_table(force=True) def reindex(sender, **kwargs): - if isinstance(sender, SearchConfig): + if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): reindex_content(force=False) class SearchConfig(AppConfig): name = 'ideascube.search' verbose_name = 'Search' def ready(self): pre_migrate.connect(create_index, sender=self) post_migrate.connect(reindex, sender=self)
Make (pre|post)_migrate scripts for the index table only if working on 'transient'.
## Code Before: from django.apps import AppConfig from django.db.models.signals import pre_migrate, post_migrate from .utils import create_index_table, reindex_content def create_index(sender, **kwargs): if isinstance(sender, SearchConfig): create_index_table(force=True) def reindex(sender, **kwargs): if isinstance(sender, SearchConfig): reindex_content(force=False) class SearchConfig(AppConfig): name = 'ideascube.search' verbose_name = 'Search' def ready(self): pre_migrate.connect(create_index, sender=self) post_migrate.connect(reindex, sender=self) ## Instruction: Make (pre|post)_migrate scripts for the index table only if working on 'transient'. ## Code After: from django.apps import AppConfig from django.db.models.signals import pre_migrate, post_migrate from .utils import create_index_table, reindex_content def create_index(sender, **kwargs): if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): create_index_table(force=True) def reindex(sender, **kwargs): if (kwargs['using'] == 'transient' and isinstance(sender, SearchConfig)): reindex_content(force=False) class SearchConfig(AppConfig): name = 'ideascube.search' verbose_name = 'Search' def ready(self): pre_migrate.connect(create_index, sender=self) post_migrate.connect(reindex, sender=self)
360efe51bc45f189c235bed6b2b7bfdd4fd1bfbd
flask-restful/api.py
flask-restful/api.py
from flask import Flask, request from flask_restful import Resource, Api, reqparse from indra import reach from indra.statements import * import json app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('txt') parser.add_argument('json') class InputText(Resource): def post(self): args = parser.parse_args() txt = args['txt'] rp = reach.process_text(txt, offline=False) st = rp.statements json_statements = {} json_statements['statements'] = [] for s in st: s_json = s.to_json() json_statements['statements'].append(s_json) json_statements = json.dumps(json_statements) return json_statements, 201 api.add_resource(InputText, '/parse') class InputStmtJSON(Resource): def post(self): args = parser.parse_args() print(args) json_data = args['json'] json_dict = json.loads(json_data) st = [] for j in json_dict['statements']: s = Statement.from_json(j) print(s) st.append(s) return 201 api.add_resource(InputStmtJSON, '/load') if __name__ == '__main__': app.run(debug=True)
import json from bottle import route, run, request, post, default_app from indra import trips, reach, bel, biopax from indra.statements import * @route('/trips/process_text', method='POST') def trips_process_text(): body = json.load(request.body) text = body.get('text') tp = trips.process_text(text) if tp and tp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in tp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res @route('/reach/process_text', method='POST') def reach_process_text(): body = json.load(request.body) text = body.get('text') rp = reach.process_text(text) if rp and rp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in rp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res @route('/reach/process_pmc', method='POST') def reach_process_pmc(): body = json.load(request.body) pmcid = body.get('pmcid') rp = reach.process_pmc(pmcid) if rp and rp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in rp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res if __name__ == '__main__': app = default_app() run(app)
Reimplement using bottle and add 3 endpoints
Reimplement using bottle and add 3 endpoints
Python
bsd-2-clause
sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/indra
- from flask import Flask, request - from flask_restful import Resource, Api, reqparse - from indra import reach + import json + from bottle import route, run, request, post, default_app + from indra import trips, reach, bel, biopax from indra.statements import * - import json - app = Flask(__name__) - api = Api(app) - parser = reqparse.RequestParser() - parser.add_argument('txt') - parser.add_argument('json') - class InputText(Resource): - def post(self): - args = parser.parse_args() - txt = args['txt'] - rp = reach.process_text(txt, offline=False) - st = rp.statements - json_statements = {} - json_statements['statements'] = [] - for s in st: - s_json = s.to_json() - json_statements['statements'].append(s_json) - json_statements = json.dumps(json_statements) - return json_statements, 201 + @route('/trips/process_text', method='POST') + def trips_process_text(): + body = json.load(request.body) + text = body.get('text') + tp = trips.process_text(text) + if tp and tp.statements: + stmts = json.dumps([json.loads(st.to_json()) for st + in tp.statements]) + res = {'statements': stmts} + return res + else: + res = {'statements': []} + return res - api.add_resource(InputText, '/parse') + @route('/reach/process_text', method='POST') + def reach_process_text(): + body = json.load(request.body) + text = body.get('text') + rp = reach.process_text(text) + if rp and rp.statements: + stmts = json.dumps([json.loads(st.to_json()) for st + in rp.statements]) + res = {'statements': stmts} - class InputStmtJSON(Resource): - def post(self): - args = parser.parse_args() - print(args) - json_data = args['json'] - json_dict = json.loads(json_data) - st = [] - for j in json_dict['statements']: - s = Statement.from_json(j) - print(s) - st.append(s) - return 201 + return res + else: + res = {'statements': []} + return res - api.add_resource(InputStmtJSON, '/load') + + @route('/reach/process_pmc', method='POST') + def reach_process_pmc(): + body = json.load(request.body) + pmcid = body.get('pmcid') + rp = reach.process_pmc(pmcid) + if rp and rp.statements: + stmts = json.dumps([json.loads(st.to_json()) for st + in rp.statements]) + res = {'statements': stmts} + return res + else: + res = {'statements': []} + return res + if __name__ == '__main__': - app.run(debug=True) + app = default_app() + run(app)
Reimplement using bottle and add 3 endpoints
## Code Before: from flask import Flask, request from flask_restful import Resource, Api, reqparse from indra import reach from indra.statements import * import json app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('txt') parser.add_argument('json') class InputText(Resource): def post(self): args = parser.parse_args() txt = args['txt'] rp = reach.process_text(txt, offline=False) st = rp.statements json_statements = {} json_statements['statements'] = [] for s in st: s_json = s.to_json() json_statements['statements'].append(s_json) json_statements = json.dumps(json_statements) return json_statements, 201 api.add_resource(InputText, '/parse') class InputStmtJSON(Resource): def post(self): args = parser.parse_args() print(args) json_data = args['json'] json_dict = json.loads(json_data) st = [] for j in json_dict['statements']: s = Statement.from_json(j) print(s) st.append(s) return 201 api.add_resource(InputStmtJSON, '/load') if __name__ == '__main__': app.run(debug=True) ## Instruction: Reimplement using bottle and add 3 endpoints ## Code After: import json from bottle import route, run, request, post, default_app from indra import trips, reach, bel, biopax from indra.statements import * @route('/trips/process_text', method='POST') def trips_process_text(): body = json.load(request.body) text = body.get('text') tp = trips.process_text(text) if tp and tp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in tp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res @route('/reach/process_text', method='POST') def reach_process_text(): body = json.load(request.body) text = body.get('text') rp = reach.process_text(text) if rp and rp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in rp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res @route('/reach/process_pmc', method='POST') def reach_process_pmc(): body = json.load(request.body) pmcid = body.get('pmcid') rp = reach.process_pmc(pmcid) if rp and rp.statements: stmts = json.dumps([json.loads(st.to_json()) for st in rp.statements]) res = {'statements': stmts} return res else: res = {'statements': []} return res if __name__ == '__main__': app = default_app() run(app)
e78910c8b9ecf48f96a693dae3c15afa32a12da1
casexml/apps/phone/views.py
casexml/apps/phone/views.py
from django_digest.decorators import * from casexml.apps.phone import xml from casexml.apps.case.models import CommCareCase from casexml.apps.phone.restore import generate_restore_response from casexml.apps.phone.models import User from casexml.apps.case import const @httpdigest def restore(request): user = User.from_django_user(request.user) restore_id = request.GET.get('since') return generate_restore_response(user, restore_id) def xml_for_case(request, case_id, version="1.0"): """ Test view to get the xml for a particular case """ from django.http import HttpResponse case = CommCareCase.get(case_id) return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE], version), mimetype="text/xml")
from django.http import HttpResponse from django_digest.decorators import * from casexml.apps.phone import xml from casexml.apps.case.models import CommCareCase from casexml.apps.phone.restore import generate_restore_response from casexml.apps.phone.models import User from casexml.apps.case import const @httpdigest def restore(request): user = User.from_django_user(request.user) restore_id = request.GET.get('since') return generate_restore_response(user, restore_id) def xml_for_case(request, case_id, version="1.0"): """ Test view to get the xml for a particular case """ case = CommCareCase.get(case_id) return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE], version), mimetype="text/xml")
Revert "moving httpresponse to view"
Revert "moving httpresponse to view" This reverts commit a6f501bb9de6382e35372996851916adac067fa0.
Python
bsd-3-clause
SEL-Columbia/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq
+ from django.http import HttpResponse from django_digest.decorators import * from casexml.apps.phone import xml from casexml.apps.case.models import CommCareCase from casexml.apps.phone.restore import generate_restore_response from casexml.apps.phone.models import User from casexml.apps.case import const @httpdigest def restore(request): user = User.from_django_user(request.user) restore_id = request.GET.get('since') return generate_restore_response(user, restore_id) def xml_for_case(request, case_id, version="1.0"): """ Test view to get the xml for a particular case """ - from django.http import HttpResponse case = CommCareCase.get(case_id) return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE], version), mimetype="text/xml")
Revert "moving httpresponse to view"
## Code Before: from django_digest.decorators import * from casexml.apps.phone import xml from casexml.apps.case.models import CommCareCase from casexml.apps.phone.restore import generate_restore_response from casexml.apps.phone.models import User from casexml.apps.case import const @httpdigest def restore(request): user = User.from_django_user(request.user) restore_id = request.GET.get('since') return generate_restore_response(user, restore_id) def xml_for_case(request, case_id, version="1.0"): """ Test view to get the xml for a particular case """ from django.http import HttpResponse case = CommCareCase.get(case_id) return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE], version), mimetype="text/xml") ## Instruction: Revert "moving httpresponse to view" ## Code After: from django.http import HttpResponse from django_digest.decorators import * from casexml.apps.phone import xml from casexml.apps.case.models import CommCareCase from casexml.apps.phone.restore import generate_restore_response from casexml.apps.phone.models import User from casexml.apps.case import const @httpdigest def restore(request): user = User.from_django_user(request.user) restore_id = request.GET.get('since') return generate_restore_response(user, restore_id) def xml_for_case(request, case_id, version="1.0"): """ Test view to get the xml for a particular case """ case = CommCareCase.get(case_id) return HttpResponse(xml.get_case_xml(case, [const.CASE_ACTION_CREATE, const.CASE_ACTION_UPDATE], version), mimetype="text/xml")
63f6e4d50116d5ca2bfc82c1c608e08040055b5e
subdue/core/__init__.py
subdue/core/__init__.py
__all__ = [ 'color', 'BANNER', 'DEFAULT_DRIVER_CODE' 'die', 'verbose', 'use_colors', 'set_color_policy', ] import sys as _sys from . import color as _color BANNER = """\ _ _ ___ _ _| |__ __| |_ _ ___ / __| | | | '_ \ / _` | | | |/ _ \\ \__ \ |_| | |_) | (_| | |_| | __/ |___/\__,_|_.__/ \__,_|\__,_|\___| """ DEFAULT_DRIVER_CODE = """\ #!/usr/bin/env python from subdue.sub import main main() """ verbose = False def set_color_policy(policy): _color.color_policy = policy def die(msg): _sys.stderr.write(msg) _sys.stderr.write("\n") _sys.stderr.flush() _sys.exit(1)
__all__ = [ 'BANNER', 'DEFAULT_DRIVER_CODE' 'die', 'verbose', 'set_color_policy', ] import sys as _sys from . import color as _color BANNER = """\ _ _ ___ _ _| |__ __| |_ _ ___ / __| | | | '_ \ / _` | | | |/ _ \\ \__ \ |_| | |_) | (_| | |_| | __/ |___/\__,_|_.__/ \__,_|\__,_|\___| """ DEFAULT_DRIVER_CODE = """\ #!/usr/bin/env python from subdue.sub import main main() """ verbose = False def set_color_policy(policy): _color.color_policy = policy def die(msg): _sys.stderr.write(msg) _sys.stderr.write("\n") _sys.stderr.flush() _sys.exit(1)
Remove old exports from subdue.core
Remove old exports from subdue.core
Python
mit
jdevera/subdue
__all__ = [ - 'color', 'BANNER', 'DEFAULT_DRIVER_CODE' 'die', 'verbose', - 'use_colors', 'set_color_policy', ] import sys as _sys from . import color as _color BANNER = """\ _ _ ___ _ _| |__ __| |_ _ ___ / __| | | | '_ \ / _` | | | |/ _ \\ \__ \ |_| | |_) | (_| | |_| | __/ |___/\__,_|_.__/ \__,_|\__,_|\___| """ DEFAULT_DRIVER_CODE = """\ #!/usr/bin/env python from subdue.sub import main main() """ verbose = False def set_color_policy(policy): _color.color_policy = policy def die(msg): _sys.stderr.write(msg) _sys.stderr.write("\n") _sys.stderr.flush() _sys.exit(1)
Remove old exports from subdue.core
## Code Before: __all__ = [ 'color', 'BANNER', 'DEFAULT_DRIVER_CODE' 'die', 'verbose', 'use_colors', 'set_color_policy', ] import sys as _sys from . import color as _color BANNER = """\ _ _ ___ _ _| |__ __| |_ _ ___ / __| | | | '_ \ / _` | | | |/ _ \\ \__ \ |_| | |_) | (_| | |_| | __/ |___/\__,_|_.__/ \__,_|\__,_|\___| """ DEFAULT_DRIVER_CODE = """\ #!/usr/bin/env python from subdue.sub import main main() """ verbose = False def set_color_policy(policy): _color.color_policy = policy def die(msg): _sys.stderr.write(msg) _sys.stderr.write("\n") _sys.stderr.flush() _sys.exit(1) ## Instruction: Remove old exports from subdue.core ## Code After: __all__ = [ 'BANNER', 'DEFAULT_DRIVER_CODE' 'die', 'verbose', 'set_color_policy', ] import sys as _sys from . import color as _color BANNER = """\ _ _ ___ _ _| |__ __| |_ _ ___ / __| | | | '_ \ / _` | | | |/ _ \\ \__ \ |_| | |_) | (_| | |_| | __/ |___/\__,_|_.__/ \__,_|\__,_|\___| """ DEFAULT_DRIVER_CODE = """\ #!/usr/bin/env python from subdue.sub import main main() """ verbose = False def set_color_policy(policy): _color.color_policy = policy def die(msg): _sys.stderr.write(msg) _sys.stderr.write("\n") _sys.stderr.flush() _sys.exit(1)

EditPackFT

EditPackFT is a dataset built for training LLMs on the task of instructional code editing. The mail columns are:

  1. old_contents the code before the edit
  2. instruction the instruction to transform the before code into the after code
  3. new_contents the code after the edit
  4. content a pre-formatted training window that can be used to train an LLM with prompts in the format of: <before><instruction><after>

This dataset has been filtered from CommitPackFT. For more detail, see our paper, and our GitHub repository.

Citation

If you use our work, please cite our paper as such:

@inproceedings{cassano2023edit,
      title={{Can It Edit? Evaluating the Ability of Large Language Models to Follow Code Editing Instructions}}, 
      author={Federico Cassano and Luisa Li and Akul Sethi and Noah Shinn and Abby Brennan-Jones and Anton Lozhkov and Carolyn Jane Anderson and Arjun Guha},
      booktitle={The First International Workshop on Large Language Model for Code},
      year={2024},
      url={https://arxiv.org/abs/2312.12450}
}
Downloads last month
146
Edit dataset card

Models trained or fine-tuned on nuprl/EditPackFT

Collection including nuprl/EditPackFT