commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
a2d3c2e0391d2deeb1d6729567c2d8812ad7e7df
exam/asserts.py
exam/asserts.py
irrelevant = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', irrelevant) self.expected_after = kwargs.pop('after', irrelevant) def __enter__(self): self.before = self.__apply() if not self.expected_before is irrelevant: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is irrelevant: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
IRRELEVANT = object() class ChangeWatcher(object): def __init__(self, thing, *args, **kwargs): self.thing = thing self.args = args self.kwargs = kwargs self.expected_before = kwargs.pop('before', IRRELEVANT) self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after') assert self.before != self.after, self.__equality_failure_message def __apply(self): return self.thing(*self.args, **self.kwargs) @property def __equality_failure_message(self): return 'Expected before %s != %s after' % (self.before, self.after) def __precondition_failure_msg_for(self, condition): return '%s value did not change (%s)' % ( condition, getattr(self, condition) ) class AssertsMixin(object): assertChanges = ChangeWatcher
Make the irrelevant object a constant
Make the irrelevant object a constant
Python
mit
Fluxx/exam,gterzian/exam,Fluxx/exam,gterzian/exam
--- +++ @@ -1,4 +1,4 @@ -irrelevant = object() +IRRELEVANT = object() class ChangeWatcher(object): @@ -7,20 +7,20 @@ self.thing = thing self.args = args self.kwargs = kwargs - self.expected_before = kwargs.pop('before', irrelevant) - self.expected_after = kwargs.pop('after', irrelevant) + self.expected_before = kwargs.pop('before', IRRELEVANT) + self.expected_after = kwargs.pop('after', IRRELEVANT) def __enter__(self): self.before = self.__apply() - if not self.expected_before is irrelevant: + if not self.expected_before is IRRELEVANT: check = self.before == self.expected_before assert check, self.__precondition_failure_msg_for('before') def __exit__(self, type, value, traceback): self.after = self.__apply() - if not self.expected_after is irrelevant: + if not self.expected_after is IRRELEVANT: check = self.after == self.expected_after assert check, self.__precondition_failure_msg_for('after')
ba13537cf18b8bced21544866fcdcc887e1d290d
latex/exc.py
latex/exc.py
import os from .errors import parse_log class LatexError(Exception): pass class LatexBuildError(LatexError): """LaTeX call exception.""" def __init__(self, logfn=None): if os.path.exists(logfn): self.log = open(logfn).read() else: self.log = None def __str__(self): return str(self.log) def get_errors(self, *args, **kwargs): """Parse the log for errors. Any arguments are passed on to :func:`.parse_log`. :return: The return of :func:`.parse_log`, applied to the log associated with this build error. """ return parse_log(self.log)
import os from .errors import parse_log class LatexError(Exception): pass class LatexBuildError(LatexError): """LaTeX call exception.""" def __init__(self, logfn=None): if os.path.exists(logfn): # the binary log is probably latin1 or utf8? # utf8 throws errors occasionally, so we try with latin1 # and ignore invalid chars binlog = open(logfn, 'rb').read() self.log = binlog.decode('latin1', 'ignore') else: self.log = None def __str__(self): return str(self.log) def get_errors(self, *args, **kwargs): """Parse the log for errors. Any arguments are passed on to :func:`.parse_log`. :return: The return of :func:`.parse_log`, applied to the log associated with this build error. """ return parse_log(self.log)
Fix latexs output encoding to latin1.
Fix latexs output encoding to latin1.
Python
bsd-3-clause
mbr/latex
--- +++ @@ -12,7 +12,11 @@ def __init__(self, logfn=None): if os.path.exists(logfn): - self.log = open(logfn).read() + # the binary log is probably latin1 or utf8? + # utf8 throws errors occasionally, so we try with latin1 + # and ignore invalid chars + binlog = open(logfn, 'rb').read() + self.log = binlog.decode('latin1', 'ignore') else: self.log = None
1cdb773f0d20dcdb1a66a4a6a52eff35398b1296
getBlocks.py
getBlocks.py
#!/usr/bin/python import subprocess import argparse def readArguments(): parser = argparse.ArgumentParser() parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred") args = parser.parse_args() return args def checkFile(file): ''' Check if file exist in HDFS ''' command = "hdfs fsck -stat " + file subprocess.check_call(command) def getBlocks(file): ''' Get list of blocks ''' command = "hdfs fsck " + file + " -files -blocks -locations" run_command(command) def run_command(cmd): print cmd def main(): args = readArguments() checkFile(args.file) if __name__ == "__main__": main()
#!/usr/bin/python import subprocess import shlex import argparse def readArguments(): parser = argparse.ArgumentParser() parser.add_argument('-f','--file', action="store", dest="file", required=True, help="File to shred") args = parser.parse_args() return args def checkFile(file): ''' Check if file exist in HDFS ''' command = "hdfs fsck -stat " + file cmd = shlex.split(command) print cmd subprocess.check_call(cmd) def getBlocks(file): ''' Get list of blocks ''' command = "hdfs fsck " + file + " -files -blocks -locations" run_command(command) def run_command(cmd): print cmd def main(): args = readArguments() checkFile(args.file) if __name__ == "__main__": main()
Use shlex to split command line
Use shlex to split command line
Python
apache-2.0
monolive/hdfs-shred
--- +++ @@ -1,6 +1,7 @@ #!/usr/bin/python import subprocess +import shlex import argparse def readArguments(): @@ -14,8 +15,9 @@ Check if file exist in HDFS ''' command = "hdfs fsck -stat " + file - subprocess.check_call(command) - + cmd = shlex.split(command) + print cmd + subprocess.check_call(cmd) def getBlocks(file): '''
fc1cb951991cc9b4b0cdb9d533127d26eb21ea57
rave/__main__.py
rave/__main__.py
import argparse import sys from os import path def parse_arguments(): parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave') parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)') parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)') parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging.') parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.') arguments = parser.parse_args() return arguments def main(): args = parse_arguments() if args.debug: from . import log log.Logger.LEVEL |= log.DEBUG from . import bootstrap bootstrap.bootstrap_engine(args.bootstrapper) if args.game: game = bootstrap.bootstrap_game(args.game_bootstrapper, args.game) bootstrap.shutdown_game(game) bootstrap.shutdown() main()
import argparse import sys from os import path def parse_arguments(): parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave') parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)') parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)') parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.') arguments = parser.parse_args() return arguments def main(): args = parse_arguments() from . import bootstrap bootstrap.bootstrap_engine(args.bootstrapper) if args.game: game = bootstrap.bootstrap_game(args.game_bootstrapper, args.game) bootstrap.shutdown_game(game) bootstrap.shutdown() main()
Remove -d command line argument in favour of __debug__.
rave: Remove -d command line argument in favour of __debug__.
Python
bsd-2-clause
rave-engine/rave
--- +++ @@ -7,7 +7,6 @@ parser = argparse.ArgumentParser(description='A modular and extensible visual novel engine.', prog='rave') parser.add_argument('-b', '--bootstrapper', help='Select bootstrapper to bootstrap the engine with. (default: autoselect)') parser.add_argument('-B', '--game-bootstrapper', metavar='BOOTSTRAPPER', help='Select bootstrapper to bootstrap the game with. (default: autoselect)') - parser.add_argument('-d', '--debug', action='store_true', help='Enable debug logging.') parser.add_argument('game', metavar='GAME', nargs='?', help='The game to run. Format dependent on used bootstrapper.') arguments = parser.parse_args() @@ -15,10 +14,6 @@ def main(): args = parse_arguments() - - if args.debug: - from . import log - log.Logger.LEVEL |= log.DEBUG from . import bootstrap bootstrap.bootstrap_engine(args.bootstrapper)
cb2db952d3a6c651dac5a285e8b0dc01a5e12a4b
rules/arm-toolchain.py
rules/arm-toolchain.py
import xyz class ArmToolchain(xyz.BuildProtocol): group_only = True pkg_name = 'arm-toolchain' supported_targets = ['arm-none-eabi'] deps = [('gcc', {'target': 'arm-none-eabi'}), ('binutils', {'target': 'arm-none-eabi'})] rules = ArmToolchain()
import xyz class ArmToolchain(xyz.BuildProtocol): group_only = True pkg_name = 'arm-toolchain' supported_targets = ['arm-none-eabi'] deps = [('gcc', {'target': 'arm-none-eabi'}), ('binutils', {'target': 'arm-none-eabi'}), ('gdb', {'target': 'arm-none-eabi'}) ] rules = ArmToolchain()
Add gdb to the toolchain
Add gdb to the toolchain
Python
mit
BreakawayConsulting/xyz
--- +++ @@ -5,6 +5,8 @@ pkg_name = 'arm-toolchain' supported_targets = ['arm-none-eabi'] deps = [('gcc', {'target': 'arm-none-eabi'}), - ('binutils', {'target': 'arm-none-eabi'})] + ('binutils', {'target': 'arm-none-eabi'}), + ('gdb', {'target': 'arm-none-eabi'}) + ] rules = ArmToolchain()
545171378864d4d80aeef52bd036ed99f18aadfc
tests/testdata/amazon.py
tests/testdata/amazon.py
AWS_SECRET_ACCESS_KEY = 'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8'
AWS_SECRET_ACCESS_KEY = r'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8'
Fix deprecation warnings due to invalid escape sequences.
Fix deprecation warnings due to invalid escape sequences.
Python
mit
landscapeio/dodgy
--- +++ @@ -1,2 +1,2 @@ -AWS_SECRET_ACCESS_KEY = 'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8' +AWS_SECRET_ACCESS_KEY = r'A8+6AN5TSUZ3vysJg68Rt\A9E7duMlfKODwb3ZD8'
da3599ac6ed29e750d28834a8c0c0f39e9b57702
src/acquisition/covid_hosp/state_daily/network.py
src/acquisition/covid_hosp/state_daily/network.py
# first party from delphi.epidata.acquisition.covid_hosp.common.network import Network as BaseNetwork class Network(BaseNetwork): DATASET_ID = '823dd0e-c8c4-4206-953e-c6d2f451d6ed' def fetch_metadata(*args, **kwags): """Download and return metadata. See `fetch_metadata_for_dataset`. """ return Network.fetch_metadata_for_dataset( *args, **kwags, dataset_id=Network.DATASET_ID)
# first party from delphi.epidata.acquisition.covid_hosp.common.network import Network as BaseNetwork class Network(BaseNetwork): DATASET_ID = '7823dd0e-c8c4-4206-953e-c6d2f451d6ed' def fetch_metadata(*args, **kwags): """Download and return metadata. See `fetch_metadata_for_dataset`. """ return Network.fetch_metadata_for_dataset( *args, **kwags, dataset_id=Network.DATASET_ID)
Update state daily dataset ID
Update state daily dataset ID
Python
mit
cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata,cmu-delphi/delphi-epidata
--- +++ @@ -4,7 +4,7 @@ class Network(BaseNetwork): - DATASET_ID = '823dd0e-c8c4-4206-953e-c6d2f451d6ed' + DATASET_ID = '7823dd0e-c8c4-4206-953e-c6d2f451d6ed' def fetch_metadata(*args, **kwags): """Download and return metadata.
29cc59bc478c4c6bc936141d19a3386468ff8f07
tests/test_general_attributes.py
tests/test_general_attributes.py
# -*- coding: utf-8 -*- from jawa.attribute import get_attribute_classes def test_mandatory_attributes(): for parser_class in get_attribute_classes().values(): assert hasattr(parser_class, 'ADDED_IN'), ( 'Attribute parser missing mandatory ADDED_IN property' ) assert hasattr(parser_class, 'MINIMUM_CLASS_VERSION'), ( 'Attribute parser missing mandatory MINIMUM_CLASS_VERSION ' 'property' )
# -*- coding: utf-8 -*- from jawa.attribute import get_attribute_classes def test_mandatory_attributes(): required_properities = ['ADDED_IN', 'MINIMUM_CLASS_VERSION'] for name, class_ in get_attribute_classes().items(): for p in required_properities: assert hasattr(class_, p), ( '{name} parser missing mandatory {p} property'.format( name=name, p=p ) ) def test_attribute_naming(): for name, class_ in get_attribute_classes().items(): if hasattr(class_, 'ATTRIBUTE_NAME'): continue assert class_.__name__.endswith('Attribute'), ( '{name} parser does not follow naming convention and does' ' not explicity set it.'.format(name=name) )
Add a simple test for Attribuet class naming conventions.
Add a simple test for Attribuet class naming conventions.
Python
mit
TkTech/Jawa,TkTech/Jawa
--- +++ @@ -3,11 +3,23 @@ def test_mandatory_attributes(): - for parser_class in get_attribute_classes().values(): - assert hasattr(parser_class, 'ADDED_IN'), ( - 'Attribute parser missing mandatory ADDED_IN property' + required_properities = ['ADDED_IN', 'MINIMUM_CLASS_VERSION'] + for name, class_ in get_attribute_classes().items(): + for p in required_properities: + assert hasattr(class_, p), ( + '{name} parser missing mandatory {p} property'.format( + name=name, + p=p + ) + ) + + +def test_attribute_naming(): + for name, class_ in get_attribute_classes().items(): + if hasattr(class_, 'ATTRIBUTE_NAME'): + continue + + assert class_.__name__.endswith('Attribute'), ( + '{name} parser does not follow naming convention and does' + ' not explicity set it.'.format(name=name) ) - assert hasattr(parser_class, 'MINIMUM_CLASS_VERSION'), ( - 'Attribute parser missing mandatory MINIMUM_CLASS_VERSION ' - 'property' - )
3be25f88352ff20a3239b0647f437c45f4903008
robotpy_ext/control/button_debouncer.py
robotpy_ext/control/button_debouncer.py
import wpilib class ButtonDebouncer: '''Useful utility class for debouncing buttons''' def __init__(self, joystick, buttonnum, period=0.5): ''' :param joystick: Joystick object :type joystick: :class:`wpilib.Joystick` :param buttonnum: Number of button to retrieve :type buttonnum: int :param period: Period of time (in seconds) to wait before allowing new button presses. Defaults to 0.5 seconds. :type period: float ''' self.joystick = joystick self.buttonnum = buttonnum self.latest = 0 self.debounce_period = float(period) self.timer = wpilib.Timer def set_debounce_period(self, period): '''Set number of seconds to wait before returning True for the button again''' self.debounce_period = float(period) def get(self): '''Returns the value of the joystick button. If the button is held down, then True will only be returned once every ``debounce_period`` seconds''' now = self.timer.getFPGATimestamp() if self.joystick.getRawButton(self.buttonnum): if (now-self.latest) > self.debounce_period: self.latest = now return True return False
import wpilib class ButtonDebouncer: '''Useful utility class for debouncing buttons''' def __init__(self, joystick, buttonnum, period=0.5): ''' :param joystick: Joystick object :type joystick: :class:`wpilib.Joystick` :param buttonnum: Number of button to retrieve :type buttonnum: int :param period: Period of time (in seconds) to wait before allowing new button presses. Defaults to 0.5 seconds. :type period: float ''' self.joystick = joystick self.buttonnum = buttonnum self.latest = 0 self.debounce_period = float(period) self.timer = wpilib.Timer def set_debounce_period(self, period): '''Set number of seconds to wait before returning True for the button again''' self.debounce_period = float(period) def get(self): '''Returns the value of the joystick button. If the button is held down, then True will only be returned once every ``debounce_period`` seconds''' now = self.timer.getFPGATimestamp() if self.joystick.getRawButton(self.buttonnum): if (now-self.latest) > self.debounce_period: self.latest = now return True return False __bool__ = get
Add __bool__ redirect to buttondebounce
Add __bool__ redirect to buttondebounce
Python
bsd-3-clause
robotpy/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities
--- +++ @@ -34,3 +34,5 @@ self.latest = now return True return False + + __bool__ = get
d8dd87f6f5bd1bdead9f2b77ec9271035d05a378
snappybouncer/admin.py
snappybouncer/admin.py
from django.contrib import admin from snappybouncer.models import Conversation, UserAccount, Ticket admin.site.register(Conversation) admin.site.register(UserAccount) admin.site.register(Ticket)
from django.contrib import admin from snappybouncer.models import Conversation, UserAccount, Ticket from control.actions import export_select_fields_csv_action class TicketAdmin(admin.ModelAdmin): actions = [export_select_fields_csv_action( "Export selected objects as CSV file", fields = [ ("id", "unique_id"), ("support_nonce", "support_nonce"), ("message", "Message"), ("response", "Response"), ("created_at", "Created At"), ("updated_at", "Updated At"), ], header=True )] admin.site.register(Conversation) admin.site.register(UserAccount) admin.site.register(Ticket, TicketAdmin)
Add download to snappy bouncer
Add download to snappy bouncer
Python
bsd-3-clause
praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control
--- +++ @@ -1,6 +1,21 @@ from django.contrib import admin from snappybouncer.models import Conversation, UserAccount, Ticket +from control.actions import export_select_fields_csv_action + +class TicketAdmin(admin.ModelAdmin): + actions = [export_select_fields_csv_action( + "Export selected objects as CSV file", + fields = [ + ("id", "unique_id"), + ("support_nonce", "support_nonce"), + ("message", "Message"), + ("response", "Response"), + ("created_at", "Created At"), + ("updated_at", "Updated At"), + ], + header=True + )] admin.site.register(Conversation) admin.site.register(UserAccount) -admin.site.register(Ticket) +admin.site.register(Ticket, TicketAdmin)
c9284e4d36026b837f1a43a58100b434e7a57337
pygotham/admin/schedule.py
pygotham/admin/schedule.py
"""Admin for schedule-related models.""" from pygotham.admin.utils import model_view from pygotham.schedule import models # This line is really long because pep257 needs it to be on one line. __all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView') CATEGORY = 'Schedule' DayModelView = model_view( models.Day, 'Days', CATEGORY, column_default_sort='date', column_list=('date', 'event'), form_columns=('event', 'date'), ) RoomModelView = model_view( models.Room, 'Rooms', CATEGORY, column_default_sort='order', form_columns=('name', 'order'), ) SlotModelView = model_view( models.Slot, 'Slots', CATEGORY, column_default_sort='start', column_list=('day', 'rooms', 'kind', 'start', 'end'), form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'), ) PresentationModelView = model_view( models.Presentation, 'Presentations', CATEGORY, )
"""Admin for schedule-related models.""" from pygotham.admin.utils import model_view from pygotham.schedule import models # This line is really long because pep257 needs it to be on one line. __all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView') CATEGORY = 'Schedule' DayModelView = model_view( models.Day, 'Days', CATEGORY, column_default_sort='date', column_list=('date', 'event'), form_columns=('event', 'date'), ) RoomModelView = model_view( models.Room, 'Rooms', CATEGORY, column_default_sort='order', form_columns=('name', 'order'), ) SlotModelView = model_view( models.Slot, 'Slots', CATEGORY, column_default_sort='start', column_filters=('day',), column_list=( 'day', 'rooms', 'kind', 'start', 'end', 'presentation', 'content_override', ), form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'), ) PresentationModelView = model_view( models.Presentation, 'Presentations', CATEGORY, )
Use version of slots admin already in production
Use version of slots admin already in production While building the schedule for the conference, the admin view for `schedule.models.Slot` was changed in production* to figure out what implementation made the most sense. This formalizes it as the preferred version. Closes #111 *Don't do this at home.
Python
bsd-3-clause
djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,pathunstrom/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,pathunstrom/pygotham,djds23/pygotham-1
--- +++ @@ -33,7 +33,11 @@ 'Slots', CATEGORY, column_default_sort='start', - column_list=('day', 'rooms', 'kind', 'start', 'end'), + column_filters=('day',), + column_list=( + 'day', 'rooms', 'kind', 'start', 'end', 'presentation', + 'content_override', + ), form_columns=('day', 'rooms', 'kind', 'start', 'end', 'content_override'), )
c84f14d33f9095f2d9d8919a9b6ba11e17acd4ca
txspinneret/test/util.py
txspinneret/test/util.py
from twisted.web import http from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
from twisted.web import http from twisted.web.http_headers import Headers from twisted.web.test.requesthelper import DummyRequest class InMemoryRequest(DummyRequest): """ In-memory `IRequest`. """ def __init__(self, *a, **kw): DummyRequest.__init__(self, *a, **kw) # This was only added to `DummyRequest` in Twisted 14.0.0, so we'll do # this so our tests pass on older versions of Twisted. self.requestHeaders = Headers() def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
Make `InMemoryRequest` work on Twisted<14.0.0
Make `InMemoryRequest` work on Twisted<14.0.0
Python
mit
jonathanj/txspinneret,mithrandi/txspinneret
--- +++ @@ -1,4 +1,5 @@ from twisted.web import http +from twisted.web.http_headers import Headers from twisted.web.test.requesthelper import DummyRequest @@ -7,6 +8,13 @@ """ In-memory `IRequest`. """ + def __init__(self, *a, **kw): + DummyRequest.__init__(self, *a, **kw) + # This was only added to `DummyRequest` in Twisted 14.0.0, so we'll do + # this so our tests pass on older versions of Twisted. + self.requestHeaders = Headers() + + def redirect(self, url): self.setResponseCode(http.FOUND) self.setHeader(b'location', url)
be670eb5830a873d21e4e8587600a75018f01939
collection_pipelines/__init__.py
collection_pipelines/__init__.py
from collection_pipelines.http import http from collection_pipelines.json import * class cat(CollectionPipelineProcessor): def __init__(self, fname): self.fname = fname self.source(self.make_generator) def make_generator(self): with open(self.fname, 'r') as f: for line in f: self.receiver.send(line.rstrip('\n')) self.receiver.close() class filter(CollectionPipelineProcessor): def __init__(self, text): self.text = text def process(self, item): if item != self.text: self.receiver.send(item) class out(CollectionPipelineProcessor): def process(self, item): print(item) def source(self, start_source): start_source() class count(CollectionPipelineProcessor): def __init__(self): self.val = 0 def process(self, item): self.val += 1 def on_done(self): self.receiver.send(self.val) class unique(CollectionPipelineProcessor): seen = [] def process(self, item): if item not in self.seen: self.receiver.send(item) self.seen.append(item)
from collection_pipelines.http import http from collection_pipelines.json import * class cat(CollectionPipelineProcessor): def __init__(self, fname): self.fname = fname self.source(self.make_generator) def make_generator(self): with open(self.fname, 'r') as f: for line in f: self.receiver.send(line.rstrip('\n')) self.receiver.close() class filter(CollectionPipelineProcessor): def __init__(self, text): self.text = text def process(self, item): if item != self.text: self.receiver.send(item) class out(CollectionPipelineOutput): def process(self, item): print(item) class count(CollectionPipelineProcessor): def __init__(self): self.val = 0 def process(self, item): self.val += 1 def on_done(self): self.receiver.send(self.val) class unique(CollectionPipelineProcessor): seen = [] def process(self, item): if item not in self.seen: self.receiver.send(item) self.seen.append(item)
Update out() processor to extend CollectionPipelineOutput class
Update out() processor to extend CollectionPipelineOutput class
Python
mit
povilasb/pycollection-pipelines
--- +++ @@ -23,12 +23,9 @@ self.receiver.send(item) -class out(CollectionPipelineProcessor): +class out(CollectionPipelineOutput): def process(self, item): print(item) - - def source(self, start_source): - start_source() class count(CollectionPipelineProcessor):
915370a5950bcaee4b7037196ef02621e518dcd9
rcamp/lib/views.py
rcamp/lib/views.py
from django.shortcuts import render_to_response from django.shortcuts import render from django.template import RequestContext from django.shortcuts import redirect def handler404(request): return render(request, '404.html', {}, status=404) def handler500(request): return render(request, '500.html', {}, status=500) def index_view(request): if request.user.is_authenticated(): return redirect('projects:project-list') return render(request, 'index.html', {})
from django.shortcuts import render_to_response from django.shortcuts import render from django.template import RequestContext from django.shortcuts import redirect def handler404(request, exception=None): return render(request, '404.html', {}, status=404) def handler500(request): return render(request, '500.html', {}, status=500) def index_view(request): if request.user.is_authenticated(): return redirect('projects:project-list') return render(request, 'index.html', {})
Fix 404 handler not handling exception argument
Fix 404 handler not handling exception argument
Python
mit
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
--- +++ @@ -4,7 +4,7 @@ from django.shortcuts import redirect -def handler404(request): +def handler404(request, exception=None): return render(request, '404.html', {}, status=404)
d07722c8e7cc2efa0551830ca424d2db2bf734f3
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app
from flask import Flask from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES from helpers.text import slugify from config import config bootstrap = Bootstrap() db = SQLAlchemy() login_manager = LoginManager() login_manager.login_view = 'auth.login' ads = UploadSet('ads', IMAGES) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) app.jinja_env.globals.update(slugify=slugify) bootstrap.init_app(app) db.init_app(app) login_manager.init_app(app) configure_uploads(app, ads) from .aflafrettir import aflafrettir as afla_blueprint from .auth import auth as auth_blueprint from .admin import admin as admin_blueprint app.register_blueprint(afla_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(admin_blueprint, url_prefix='/admin') return app
Add slugify to the jinja2's globals scope
Add slugify to the jinja2's globals scope
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
--- +++ @@ -3,6 +3,8 @@ from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.uploads import UploadSet, configure_uploads, IMAGES + +from helpers.text import slugify from config import config @@ -15,6 +17,7 @@ def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) + app.jinja_env.globals.update(slugify=slugify) bootstrap.init_app(app) db.init_app(app)
6067e96b0c5462f9d3e9391cc3193a28ba7ad808
DebianChangesBot/mailparsers/security_announce.py
DebianChangesBot/mailparsers/security_announce.py
from DebianChangesBot import MailParser class SecurityAnnounce(MailParser): def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': return False fmt = SecurityAnnounceFormatter() data = { 'dsa_number' : None, 'package' : None, 'problem' : None, 'year' : None, 'url' : None, } m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) else: return False m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: data['year'] = m.group(1) else: return False data['url'] = "http://www.debian.org/security/%s/dsa-%s" % (data['year'], re.sub(r'-\d+$', '', data['dsa_number'])) data = self._tidy_data(data) for k, v in data.iteritems(): data[k] = str(v.decode('ascii')) return colourise(_("[red][Security][reset] ([yellow]DSA-%(dsa_number)s[reset]) - New [green]%(package)s[reset] packages fix %(problem)s. %(url)s") % data)
from DebianChangesBot import MailParser class SecurityAnnounce(MailParser): def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': return None fmt = SecurityAnnounceFormatter() m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: fmt.year = m.group(1) return fmt
Make formatter example more realistic
Make formatter example more realistic Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@chris-lamb.co.uk>
Python
agpl-3.0
lamby/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot,sebastinas/debian-devel-changes-bot,lamby/debian-devel-changes-bot,xtaran/debian-devel-changes-bot
--- +++ @@ -5,34 +5,18 @@ def parse(self, msg): if self._get_header(msg, 'List-Id') != '<debian-security-announce.lists.debian.org>': - return False + return None fmt = SecurityAnnounceFormatter() - - data = { - 'dsa_number' : None, - 'package' : None, - 'problem' : None, - 'year' : None, - 'url' : None, - } m = re.match(r'^\[SECURITY\] \[DSA ([-\d]+)\] New (.*?) packages fix (.*)$', self._get_header(msg, 'Subject')) if m: fmt.dsa_number = m.group(1) fmt.package = m.group(2) fmt.problem = m.group(3) - else: - return False m = re.match(r'.*(20\d\d)', self._get_header(msg, 'Date')) if m: - data['year'] = m.group(1) - else: - return False + fmt.year = m.group(1) - data['url'] = "http://www.debian.org/security/%s/dsa-%s" % (data['year'], re.sub(r'-\d+$', '', data['dsa_number'])) - data = self._tidy_data(data) - - for k, v in data.iteritems(): data[k] = str(v.decode('ascii')) - return colourise(_("[red][Security][reset] ([yellow]DSA-%(dsa_number)s[reset]) - New [green]%(package)s[reset] packages fix %(problem)s. %(url)s") % data) + return fmt
2c1d40030f19356bdac6117d1df6dc35a475e480
vcr_unittest/testcase.py
vcr_unittest/testcase.py
from __future__ import absolute_import, unicode_literals import inspect import logging import os import unittest import vcr logger = logging.getLogger(__name__) class VCRTestCase(unittest.TestCase): vcr_enabled = True def setUp(self): super(VCRTestCase, self).setUp() if self.vcr_enabled: myvcr = vcr.VCR(**self._get_vcr_kwargs()) name = self._get_cassette_name() cm = myvcr.use_cassette(name) self.cassette = cm.__enter__() self.addCleanup(cm.__exit__, None, None, None) def _get_vcr_kwargs(self): return dict( cassette_library_dir=self._get_cassette_library_dir(), ) def _get_cassette_library_dir(self): testdir = os.path.dirname(inspect.getfile(self.__class__)) return os.path.join(testdir, 'cassettes') def _get_cassette_name(self): return '{0}.{1}'.format(self.__class__.__name__, self._testMethodName)
from __future__ import absolute_import, unicode_literals import inspect import logging import os import unittest import vcr logger = logging.getLogger(__name__) class VCRTestCase(unittest.TestCase): vcr_enabled = True def setUp(self): super(VCRTestCase, self).setUp() if self.vcr_enabled: myvcr = vcr.VCR(**self._get_vcr_kwargs()) name = self._get_cassette_name() cm = myvcr.use_cassette(name) self.cassette = cm.__enter__() self.addCleanup(cm.__exit__, None, None, None) def _get_vcr_kwargs(self): return dict( cassette_library_dir=self._get_cassette_library_dir(), ) def _get_cassette_library_dir(self): testdir = os.path.dirname(inspect.getfile(self.__class__)) return os.path.join(testdir, 'cassettes') def _get_cassette_name(self): return '{0}.{1}.yaml'.format(self.__class__.__name__, self._testMethodName)
Add .yaml extension on default cassette name.
Add .yaml extension on default cassette name.
Python
mit
agriffis/vcrpy-unittest
--- +++ @@ -32,5 +32,5 @@ return os.path.join(testdir, 'cassettes') def _get_cassette_name(self): - return '{0}.{1}'.format(self.__class__.__name__, - self._testMethodName) + return '{0}.{1}.yaml'.format(self.__class__.__name__, + self._testMethodName)
8e7c64e0e9868b9bbc3156c70f6c368cad427f1f
egoio/__init__.py
egoio/__init__.py
import numpy from psycopg2.extensions import register_adapter, AsIs def adapt_numpy_int64(numpy_int64): """ Adapting numpy.int64 type to SQL-conform int type using psycopg extension, see [1]_ for more info. References ---------- .. [1] http://initd.org/psycopg/docs/advanced.html#adapting-new-python-types-to-sql-syntax """ return AsIs(numpy_int64) register_adapter(numpy.int64, adapt_numpy_int64)
Add register_adapter to have type adaptions
Add register_adapter to have type adaptions
Python
agpl-3.0
openego/ego.io,openego/ego.io
--- +++ @@ -0,0 +1,15 @@ +import numpy +from psycopg2.extensions import register_adapter, AsIs + + +def adapt_numpy_int64(numpy_int64): + """ Adapting numpy.int64 type to SQL-conform int type using psycopg extension, see [1]_ for more info. + + References + ---------- + .. [1] http://initd.org/psycopg/docs/advanced.html#adapting-new-python-types-to-sql-syntax + """ + return AsIs(numpy_int64) + + +register_adapter(numpy.int64, adapt_numpy_int64)
939d76ec219b3bff45dceaef59aee08a82a76f87
virtool/labels/models.py
virtool/labels/models.py
from sqlalchemy import Column, String, Sequence, Integer from virtool.postgres import Base class Label(Base): __tablename__ = 'labels' id = Column(Integer, Sequence('labels_id_seq'), primary_key=True) name = Column(String, unique=True) color = Column(String(length=7)) description = Column(String) def __repr__(self): return "<Label(id= '%s', name='%s', color='%s', description='%s')>" % ( self.id, self.name, self.color, self.description)
from sqlalchemy import Column, String, Sequence, Integer from virtool.postgres import Base class Label(Base): __tablename__ = 'labels' id = Column(Integer, primary_key=True) name = Column(String, unique=True) color = Column(String(length=7)) description = Column(String) def __repr__(self): return "<Label(id= '%s', name='%s', color='%s', description='%s')>" % ( self.id, self.name, self.color, self.description)
Simplify label model serial ID
Simplify label model serial ID
Python
mit
virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool
--- +++ @@ -6,7 +6,7 @@ class Label(Base): __tablename__ = 'labels' - id = Column(Integer, Sequence('labels_id_seq'), primary_key=True) + id = Column(Integer, primary_key=True) name = Column(String, unique=True) color = Column(String(length=7)) description = Column(String)
e67849ca91d5d7405cd2c666516b92d2db513963
runners/trytls/__init__.py
runners/trytls/__init__.py
from .testenv import testenv __version__ = "0.1.1" __all__ = ["testenv"]
from .testenv import testenv __version__ = "0.2.0" __all__ = ["testenv"]
Update init to latest version number
Update init to latest version number
Python
mit
ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls,ouspg/trytls
--- +++ @@ -1,5 +1,5 @@ from .testenv import testenv -__version__ = "0.1.1" +__version__ = "0.2.0" __all__ = ["testenv"]
ed33050bf503a1f8c9a009411f2cbbd4e2f78e4a
datastore/services/__init__.py
datastore/services/__init__.py
"""Portal Service Layer The service layer provides an API on top of Django models to build useful outputs for consumers such as views. This layer helps keep views thin, encourages reusability across views, simplifies testing, and eases separation of concerns for models. Have a look at this example on SO for a high-level example: http://stackoverflow.com/questions/12578908/separation-of-business-logic-and-data-access-in-django/12579490#12579490 I usually implement a service layer in between views and models. This acts like your project's API and gives you a good helicopter view of what is going on. I inherited this practice from a colleague of mine that uses this layering technique a lot with Java projects (JSF), e.g: models.py class Book: author = models.ForeignKey(User) title = models.CharField(max_length=125) class Meta: app_label = "library" services.py from library.models import Book def get_books(limit=None, **filters): simple service function for retrieving books can be widely extended if limit: return Book.objects.filter(**filters)[:limit] return Book.objects.filter(**filters) views.py from library.services import get_books class BookListView(ListView): simple view, e.g. implement a _build and _apply filters function queryset = get_books() """ from overview import overview from meterruns_export import meterruns_export
"""Portal Service Layer The service layer provides an API on top of Django models to build useful outputs for consumers such as views. This layer helps keep views thin, encourages reusability across views, simplifies testing, and eases separation of concerns for models. Have a look at this example on SO for a high-level example: http://stackoverflow.com/questions/12578908/separation-of-business-logic-and-data-access-in-django/12579490#12579490 I usually implement a service layer in between views and models. This acts like your project's API and gives you a good helicopter view of what is going on. I inherited this practice from a colleague of mine that uses this layering technique a lot with Java projects (JSF), e.g: models.py class Book: author = models.ForeignKey(User) title = models.CharField(max_length=125) class Meta: app_label = "library" services.py from library.models import Book def get_books(limit=None, **filters): simple service function for retrieving books can be widely extended if limit: return Book.objects.filter(**filters)[:limit] return Book.objects.filter(**filters) views.py from library.services import get_books class BookListView(ListView): simple view, e.g. implement a _build and _apply filters function queryset = get_books() """ from .overview import overview from .meterruns_export import meterruns_export
Fix imports to work with Python3
Fix imports to work with Python3
Python
mit
impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore,impactlab/oeem-energy-datastore
--- +++ @@ -36,5 +36,5 @@ """ -from overview import overview -from meterruns_export import meterruns_export +from .overview import overview +from .meterruns_export import meterruns_export
d5b744d358e2e2bd3e6f85e0fbae487e2ee64c64
bot/logger/logger.py
bot/logger/logger.py
import time from bot.action.util.textformat import FormattedText from bot.logger.message_sender import MessageSender LOG_ENTRY_FORMAT = "{time} [{tag}] {text}" class Logger: def __init__(self, sender: MessageSender): self.sender = sender def log(self, tag, text): text = self._get_text_to_send(tag, text) self.sender.send(text) def _get_text_to_send(self, tag, text): raise NotImplementedError() class PlainTextLogger(Logger): def _get_text_to_send(self, tag: str, text: str): return LOG_ENTRY_FORMAT.format(time=time.strftime("%X"), tag=tag, text=text) class FormattedTextLogger(Logger): def _get_text_to_send(self, tag: FormattedText, text: FormattedText): return FormattedText().normal(LOG_ENTRY_FORMAT).start_format()\ .normal(time=time.strftime("%X")).concat(tag=tag).concat(text=text).end_format()
import time from bot.action.util.textformat import FormattedText from bot.logger.message_sender import MessageSender LOG_ENTRY_FORMAT = "{time} [{tag}] {text}" TEXT_SEPARATOR = " | " class Logger: def __init__(self, sender: MessageSender): self.sender = sender def log(self, tag, *texts): text = self._get_text_to_send(tag, *texts) self.sender.send(text) def _get_text_to_send(self, tag, *texts): raise NotImplementedError() class PlainTextLogger(Logger): def _get_text_to_send(self, tag: str, *texts: str): text = TEXT_SEPARATOR.join(texts) return LOG_ENTRY_FORMAT.format(time=time.strftime("%X"), tag=tag, text=text) class FormattedTextLogger(Logger): def _get_text_to_send(self, tag: FormattedText, *texts: FormattedText): text = FormattedText().normal(TEXT_SEPARATOR).join(texts) return FormattedText().normal(LOG_ENTRY_FORMAT).start_format()\ .normal(time=time.strftime("%X")).concat(tag=tag).concat(text=text).end_format()
Improve Logger to support variable text params
Improve Logger to support variable text params
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
--- +++ @@ -5,26 +5,29 @@ LOG_ENTRY_FORMAT = "{time} [{tag}] {text}" +TEXT_SEPARATOR = " | " class Logger: def __init__(self, sender: MessageSender): self.sender = sender - def log(self, tag, text): - text = self._get_text_to_send(tag, text) + def log(self, tag, *texts): + text = self._get_text_to_send(tag, *texts) self.sender.send(text) - def _get_text_to_send(self, tag, text): + def _get_text_to_send(self, tag, *texts): raise NotImplementedError() class PlainTextLogger(Logger): - def _get_text_to_send(self, tag: str, text: str): + def _get_text_to_send(self, tag: str, *texts: str): + text = TEXT_SEPARATOR.join(texts) return LOG_ENTRY_FORMAT.format(time=time.strftime("%X"), tag=tag, text=text) class FormattedTextLogger(Logger): - def _get_text_to_send(self, tag: FormattedText, text: FormattedText): + def _get_text_to_send(self, tag: FormattedText, *texts: FormattedText): + text = FormattedText().normal(TEXT_SEPARATOR).join(texts) return FormattedText().normal(LOG_ENTRY_FORMAT).start_format()\ .normal(time=time.strftime("%X")).concat(tag=tag).concat(text=text).end_format()
90a3b5c66a050f22df56e39dc6fb4f32490df4cb
st2reactor/st2reactor/container/base.py
st2reactor/st2reactor/container/base.py
from datetime import timedelta import eventlet import logging import sys from threading import Thread import time # Constants SUCCESS_EXIT_CODE = 0 eventlet.monkey_patch( os=True, select=True, socket=True, thread=False if '--use-debugger' in sys.argv else True, time=True ) LOG = logging.getLogger('st2reactor.sensor.container') class SensorContainer(object): __pool = None __sensors = None __threads = {} def __init__(self, thread_pool_size=100, sensor_instances=[]): self.__pool = eventlet.GreenPool(thread_pool_size) self.__sensors = sensor_instances def _run_sensor(self, sensor): """ XXX: sensor.init() needs to be called here. """ sensor.start() def _sensor_cleanup(self, sensor): sensor.stop() def shutdown(): LOG.info('Container shutting down. Invoking cleanup on sensors.') for sensor, gt in self.__threads.iteritems(): gt.kill() self._sensor_cleanup(sensor) LOG.info('All sensors are shut down.') def run(self): for sensor in self.__sensors: LOG.info('Running sensor %s' % sensor.__class__.__name__) gt = self.__pool.spawn(self._run_sensor, sensor) self.__threads[sensor] = gt self.__pool.waitall() def main(self): self.run() LOG.info('Container has no active sensors running.') return SUCCESS_EXIT_CODE
from datetime import timedelta import eventlet import sys from threading import Thread import time from st2common import log as logging # Constants SUCCESS_EXIT_CODE = 0 eventlet.monkey_patch( os=True, select=True, socket=True, thread=False if '--use-debugger' in sys.argv else True, time=True ) LOG = logging.getLogger('st2reactor.sensor.container') class SensorContainer(object): __pool = None __sensors = None __threads = {} def __init__(self, thread_pool_size=100, sensor_instances=[]): self.__pool = eventlet.GreenPool(thread_pool_size) self.__sensors = sensor_instances def _run_sensor(self, sensor): """ XXX: sensor.init() needs to be called here. """ sensor.start() def _sensor_cleanup(self, sensor): sensor.stop() def shutdown(): LOG.info('Container shutting down. Invoking cleanup on sensors.') for sensor, gt in self.__threads.iteritems(): gt.kill() self._sensor_cleanup(sensor) LOG.info('All sensors are shut down.') def run(self): for sensor in self.__sensors: LOG.info('Running sensor %s' % sensor.__class__.__name__) gt = self.__pool.spawn(self._run_sensor, sensor) self.__threads[sensor] = gt self.__pool.waitall() def main(self): self.run() LOG.info('Container has no active sensors running.') return SUCCESS_EXIT_CODE
Use st2common log and not logging
Fix: Use st2common log and not logging
Python
apache-2.0
StackStorm/st2,Plexxi/st2,grengojbo/st2,Itxaka/st2,nzlosh/st2,armab/st2,grengojbo/st2,dennybaa/st2,alfasin/st2,emedvedev/st2,peak6/st2,tonybaloney/st2,jtopjian/st2,lakshmi-kannan/st2,tonybaloney/st2,nzlosh/st2,StackStorm/st2,Itxaka/st2,pixelrebel/st2,pixelrebel/st2,Itxaka/st2,Plexxi/st2,punalpatel/st2,alfasin/st2,tonybaloney/st2,pixelrebel/st2,emedvedev/st2,punalpatel/st2,pinterb/st2,armab/st2,StackStorm/st2,emedvedev/st2,Plexxi/st2,alfasin/st2,StackStorm/st2,peak6/st2,nzlosh/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,jtopjian/st2,Plexxi/st2,pinterb/st2,peak6/st2,grengojbo/st2,jtopjian/st2,punalpatel/st2,dennybaa/st2,pinterb/st2,nzlosh/st2,dennybaa/st2,armab/st2
--- +++ @@ -1,9 +1,10 @@ from datetime import timedelta import eventlet -import logging import sys from threading import Thread import time + +from st2common import log as logging # Constants SUCCESS_EXIT_CODE = 0
aca834449910cd358ea59a73984f895cbfc67030
examples/index.py
examples/index.py
import random import tables print 'tables.__version__', tables.__version__ nrows=10000-1 class Distance(tables.IsDescription): frame = tables.Int32Col(pos=0) distance = tables.Float64Col(pos=1) h5file = tables.openFile('index.h5', mode='w') table = h5file.createTable(h5file.root, 'distance_table', Distance, 'distance table', expectedrows=nrows) r = table.row for i in range(nrows): #r['frame'] = nrows-i r['frame'] = random.randint(0, nrows) r['distance'] = float(i**2) r.append() table.flush() table.cols.frame.createIndex(optlevel=9, testmode=True, verbose=True) #table.cols.frame.optimizeIndex(level=5, verbose=1) results = [r.nrow for r in table.where('frame < 2')] print "frame<2 -->", table.readCoordinates(results) #print "frame<2 -->", table.getWhereList('frame < 2') results = [r.nrow for r in table.where('(1 < frame) & (frame <= 5)')] print "rows-->", results print "1<frame<=5 -->", table.readCoordinates(results) #print "1<frame<=5 -->", table.getWhereList('(1 < frame) & (frame <= 5)') h5file.close()
import random import tables print 'tables.__version__', tables.__version__ nrows=10000-1 class Distance(tables.IsDescription): frame = tables.Int32Col(pos=0) distance = tables.Float64Col(pos=1) h5file = tables.openFile('index.h5', mode='w') table = h5file.createTable(h5file.root, 'distance_table', Distance, 'distance table', expectedrows=nrows) r = table.row for i in range(nrows): #r['frame'] = nrows-i r['frame'] = random.randint(0, nrows) r['distance'] = float(i**2) r.append() table.flush() table.cols.frame.createIndex(optlevel=9, _testmode=True, _verbose=True) #table.cols.frame.optimizeIndex(level=5, verbose=1) results = [r.nrow for r in table.where('frame < 2')] print "frame<2 -->", table.readCoordinates(results) #print "frame<2 -->", table.getWhereList('frame < 2') results = [r.nrow for r in table.where('(1 < frame) & (frame <= 5)')] print "rows-->", results print "1<frame<=5 -->", table.readCoordinates(results) #print "1<frame<=5 -->", table.getWhereList('(1 < frame) & (frame <= 5)') h5file.close()
Fix keyword names in example code
Fix keyword names in example code
Python
bsd-3-clause
PyTables/PyTables,jennolsen84/PyTables,jack-pappas/PyTables,FrancescAlted/PyTables,dotsdl/PyTables,tp199911/PyTables,jennolsen84/PyTables,joonro/PyTables,joonro/PyTables,rabernat/PyTables,dotsdl/PyTables,rabernat/PyTables,cpcloud/PyTables,mohamed-ali/PyTables,avalentino/PyTables,jennolsen84/PyTables,tp199911/PyTables,jack-pappas/PyTables,cpcloud/PyTables,tp199911/PyTables,avalentino/PyTables,FrancescAlted/PyTables,gdementen/PyTables,jack-pappas/PyTables,tp199911/PyTables,rabernat/PyTables,mohamed-ali/PyTables,PyTables/PyTables,jennolsen84/PyTables,gdementen/PyTables,mohamed-ali/PyTables,andreabedini/PyTables,rdhyee/PyTables,dotsdl/PyTables,gdementen/PyTables,rabernat/PyTables,rdhyee/PyTables,joonro/PyTables,andreabedini/PyTables,FrancescAlted/PyTables,andreabedini/PyTables,cpcloud/PyTables,jack-pappas/PyTables,mohamed-ali/PyTables,jack-pappas/PyTables,andreabedini/PyTables,PyTables/PyTables,rdhyee/PyTables,dotsdl/PyTables,gdementen/PyTables,cpcloud/PyTables,joonro/PyTables,rdhyee/PyTables,avalentino/PyTables
--- +++ @@ -19,7 +19,7 @@ r.append() table.flush() -table.cols.frame.createIndex(optlevel=9, testmode=True, verbose=True) +table.cols.frame.createIndex(optlevel=9, _testmode=True, _verbose=True) #table.cols.frame.optimizeIndex(level=5, verbose=1) results = [r.nrow for r in table.where('frame < 2')]
02076f919e56503c76a41e78feed8a6720c65c19
robot/robot/src/autonomous/timed_shoot.py
robot/robot/src/autonomous/timed_shoot.py
try: import wpilib except ImportError: from pyfrc import wpilib from common.autonomous_helper import StatefulAutonomous, timed_state class TimedShootAutonomous(StatefulAutonomous): ''' Tunable autonomous mode that does dumb time-based shooting decisions. Works consistently. ''' DEFAULT = False MODE_NAME = "Timed shoot" def __init__(self, components): super().__init__(components) self.register_sd_var('drive_speed', 0.5) def on_disable(self): '''This function is called when autonomous mode is disabled''' pass def update(self, tm): # always keep the arm down self.intake.armDown() if tm > 0.3: self.catapult.pulldown() super().update(tm) @timed_state(duration=1.2, next_state='drive', first=True) def drive_wait(self, tm, state_tm): pass @timed_state(duration=1.4, next_state='launch') def drive(self, tm, state_tm): self.drive.move(0, self.drive_speed, 0) @timed_state(duration=1.0) def launch(self, tm): self.catapult.launchNoSensor()
try: import wpilib except ImportError: from pyfrc import wpilib from common.autonomous_helper import StatefulAutonomous, timed_state class TimedShootAutonomous(StatefulAutonomous): ''' Tunable autonomous mode that does dumb time-based shooting decisions. Works consistently. ''' DEFAULT = False MODE_NAME = "Timed shoot" def __init__(self, components): super().__init__(components) self.register_sd_var('drive_speed', 0.5) def on_disable(self): '''This function is called when autonomous mode is disabled''' pass def update(self, tm): # always keep the arm down self.intake.armDown() if tm > 0.3: self.catapult.pulldown() super().update(tm) @timed_state(duration=1.2, next_state='drive', first=True) def drive_wait(self, tm, state_tm): '''Wait some period before we start driving''' pass @timed_state(duration=1.4, next_state='launch') def drive(self, tm, state_tm): '''Start the launch sequence! Drive slowly forward for N seconds''' self.drive.move(0, self.drive_speed, 0) @timed_state(duration=1.0) def launch(self, tm): '''Finally, fire and keep firing for 1 seconds''' self.catapult.launchNoSensor()
Add comments for timed shoot
Add comments for timed shoot
Python
bsd-3-clause
frc1418/2014
--- +++ @@ -34,14 +34,17 @@ @timed_state(duration=1.2, next_state='drive', first=True) def drive_wait(self, tm, state_tm): + '''Wait some period before we start driving''' pass @timed_state(duration=1.4, next_state='launch') def drive(self, tm, state_tm): + '''Start the launch sequence! Drive slowly forward for N seconds''' self.drive.move(0, self.drive_speed, 0) @timed_state(duration=1.0) def launch(self, tm): + '''Finally, fire and keep firing for 1 seconds''' self.catapult.launchNoSensor()
dddfbf8970f22d44eac7805c3e325fd1684673d7
word-count/word_count.py
word-count/word_count.py
def word_count(s): words = strip_punc(s.lower()).split() return {word: words.count(word) for word in set(words)} def strip_punc(s): return "".join(ch if ch.isalnum() else " " for ch in s)
def word_count(s): words = strip_punc(s).lower().split() return {word: words.count(word) for word in set(words)} def strip_punc(s): return "".join(ch if ch.isalnum() else " " for ch in s)
Move .lower() method call for readability
Move .lower() method call for readability
Python
agpl-3.0
CubicComet/exercism-python-solutions
--- +++ @@ -1,5 +1,5 @@ def word_count(s): - words = strip_punc(s.lower()).split() + words = strip_punc(s).lower().split() return {word: words.count(word) for word in set(words)}
4f34ec163d00e16df7150d58274a4a0135c90b04
bugimporters/main.py
bugimporters/main.py
#!/usr/bin/env python import argparse import sys def main(raw_arguments): parser = argparse.ArgumentParser(description='Simple oh-bugimporters crawl program') parser.add_argument('-i', action="store", dest="input") parser.add_argument('-o', action="store", dest="output") args = parser.parse_args(raw_arguments) print args if __name__ == '__main__': main(sys.argv[1:])
#!/usr/bin/env python import argparse import sys import json import mock import bugimporters.trac def dict2obj(d): class Trivial(object): def get_base_url(self): return self.base_url ret = Trivial() for thing in d: setattr(ret, thing, d[thing]) ret.old_trac = False # FIXME, hack ret.max_connections = 5 # FIXME, hack ret.as_appears_in_distribution = ''# FIXME, hack return ret class FakeReactorManager(object): def __init__(self): self.running_deferreds = 0 # FIXME: Hack def maybe_quit(self, *args, **kwargs): ## FIXME: Hack return def main(raw_arguments): parser = argparse.ArgumentParser(description='Simple oh-bugimporters crawl program') parser.add_argument('-i', action="store", dest="input") parser.add_argument('-o', action="store", dest="output") args = parser.parse_args(raw_arguments) json_data = json.load(open(args.input)) objs = [] for d in json_data: objs.append(dict2obj(d)) for obj in objs: bug_data = [] def generate_bug_transit(bug_data=bug_data): def bug_transit(bug): bug_data.append(bug) return {'get_fresh_urls': lambda *args: {}, 'update': bug_transit, 'delete_by_url': lambda *args: {}} bug_importer = bugimporters.trac.SynchronousTracBugImporter( obj, FakeReactorManager(), data_transits={'bug': generate_bug_transit(), 'trac': { 'get_bug_times': lambda url: (None, None), 'get_timeline_url': mock.Mock(), 'update_timeline': mock.Mock() }}) class StupidQuery(object): @staticmethod def get_query_url(): return 'http://twistedmatrix.com/trac/query?format=csv&col=id&col=summary&col=status&col=owner&col=type&col=priority&col=milestone&id=5228&order=priority' # FIXME: Hack @staticmethod def save(*args, **kwargs): pass # FIXME: Hack queries = [StupidQuery] bug_importer.process_queries(queries) print "YAHOO", bug_data if __name__ == '__main__': main(sys.argv[1:])
Add enough hackish machinery for the CLI downloader to download one bug
Add enough hackish machinery for the CLI downloader to download one bug
Python
agpl-3.0
openhatch/oh-bugimporters,openhatch/oh-bugimporters,openhatch/oh-bugimporters
--- +++ @@ -1,15 +1,67 @@ #!/usr/bin/env python import argparse import sys +import json +import mock +import bugimporters.trac + +def dict2obj(d): + class Trivial(object): + def get_base_url(self): + return self.base_url + ret = Trivial() + for thing in d: + setattr(ret, thing, d[thing]) + ret.old_trac = False # FIXME, hack + ret.max_connections = 5 # FIXME, hack + ret.as_appears_in_distribution = ''# FIXME, hack + return ret + +class FakeReactorManager(object): + def __init__(self): + self.running_deferreds = 0 # FIXME: Hack + def maybe_quit(self, *args, **kwargs): ## FIXME: Hack + return def main(raw_arguments): parser = argparse.ArgumentParser(description='Simple oh-bugimporters crawl program') parser.add_argument('-i', action="store", dest="input") parser.add_argument('-o', action="store", dest="output") + args = parser.parse_args(raw_arguments) - args = parser.parse_args(raw_arguments) - print args + json_data = json.load(open(args.input)) + objs = [] + for d in json_data: + objs.append(dict2obj(d)) + + for obj in objs: + bug_data = [] + def generate_bug_transit(bug_data=bug_data): + def bug_transit(bug): + bug_data.append(bug) + return {'get_fresh_urls': lambda *args: {}, + 'update': bug_transit, + 'delete_by_url': lambda *args: {}} + + bug_importer = bugimporters.trac.SynchronousTracBugImporter( + obj, FakeReactorManager(), + data_transits={'bug': generate_bug_transit(), + 'trac': { + 'get_bug_times': lambda url: (None, None), + 'get_timeline_url': mock.Mock(), + 'update_timeline': mock.Mock() + }}) + class StupidQuery(object): + @staticmethod + def get_query_url(): + return 'http://twistedmatrix.com/trac/query?format=csv&col=id&col=summary&col=status&col=owner&col=type&col=priority&col=milestone&id=5228&order=priority' # FIXME: Hack + @staticmethod + def save(*args, **kwargs): + pass # FIXME: Hack + queries = [StupidQuery] + bug_importer.process_queries(queries) + print "YAHOO", bug_data if __name__ == '__main__': main(sys.argv[1:])
5ea8993f76477c3cb6f35c26b38d82eda8a9478f
tests_django/integration_tests/test_output_adapter_integration.py
tests_django/integration_tests/test_output_adapter_integration.py
from django.test import TestCase from chatterbot.ext.django_chatterbot.models import Statement class OutputIntegrationTestCase(TestCase): """ Tests to make sure that output adapters function correctly when using Django. """ def test_output_adapter(self): from chatterbot.output import OutputAdapter adapter = OutputAdapter() statement = Statement(text='_') result = adapter.process_response(statement, confidence=1) self.assertEqual(result.text, '_')
from django.test import TestCase from chatterbot.ext.django_chatterbot.models import Statement class OutputIntegrationTestCase(TestCase): """ Tests to make sure that output adapters function correctly when using Django. """ def test_output_adapter(self): from chatterbot.output import OutputAdapter adapter = OutputAdapter() statement = Statement(text='_') result = adapter.process_response(statement) self.assertEqual(result.text, '_')
Remove confidence parameter in django test case
Remove confidence parameter in django test case
Python
bsd-3-clause
vkosuri/ChatterBot,Reinaesaya/OUIRL-ChatBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,davizucon/ChatterBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot
--- +++ @@ -14,6 +14,6 @@ adapter = OutputAdapter() statement = Statement(text='_') - result = adapter.process_response(statement, confidence=1) + result = adapter.process_response(statement) self.assertEqual(result.text, '_')
19c2f919c6deb11331e927ad3f794424905fc4f3
self-post-stream/stream.py
self-post-stream/stream.py
import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
import praw import argparse parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) args = parser.parse_args() args.limit = 1000 if args.limit > 1000 else args.limit r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self] for post in posts: print("Title:", post.title) print("Score: {} | Comments: {}".format(post.score, post.num_comments)) print() print(post.selftext.replace('**', '').replace('*', '')) print() print("Link:", post.permalink) print('=' * 30)
Add value check for -limit
Add value check for -limit
Python
mit
kshvmdn/reddit-bots
--- +++ @@ -4,7 +4,9 @@ parser = argparse.ArgumentParser(description='Stream self posts from any subreddit.') parser.add_argument('-sub', required=False, default='all', help='Subreddit name (default=\'all\')') parser.add_argument('-limit', required=False, default=100, help='Post limit (default=100, max=1000)', type=int) + args = parser.parse_args() +args.limit = 1000 if args.limit > 1000 else args.limit r = praw.Reddit(user_agent='stream only self posts from a sub by /u/km97') posts = [post for post in r.get_subreddit(args.sub).get_hot(limit=args.limit) if post.is_self]
a643cb510429d9fcf4de43e64b04480419c5500b
mscgen/setup.py
mscgen/setup.py
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the mscgen Sphinx extension. Allow mscgen-formatted Message Sequence Chart graphs to be included in Sphinx-generated documents inline. ''' requires = ['Sphinx>=0.6'] setup( name='mscgen', version='0.3', url='http://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/mscgen', license='BSD', author='Leandro Lucarella', author_email='llucax@gmail.com', description='Sphinx extension mscgen', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the mscgen Sphinx extension. Allow mscgen-formatted Message Sequence Chart graphs to be included in Sphinx-generated documents inline. ''' requires = ['Sphinx>=0.6'] setup( name='sphinxcontrib-mscgen', version='0.3', url='http://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/mscgen', license='BSD', author='Leandro Lucarella', author_email='llucax@gmail.com', description='Sphinx extension mscgen', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
Change package name to sphinxcontrib-mscgen
mscgen: Change package name to sphinxcontrib-mscgen
Python
bsd-2-clause
sphinx-contrib/spelling,sphinx-contrib/spelling
--- +++ @@ -12,7 +12,7 @@ requires = ['Sphinx>=0.6'] setup( - name='mscgen', + name='sphinxcontrib-mscgen', version='0.3', url='http://bitbucket.org/birkenfeld/sphinx-contrib', download_url='http://pypi.python.org/pypi/mscgen',
cbfbc7482a19b5d7ddcdb3980bfdf5d1d8487141
Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py
Google_Code_Jam/2010_Africa/Qualification_Round/B/reverse_words.py
#!/usr/bin/python -tt """Solves problem B from Google Code Jam Qualification Round Africa 2010 (https://code.google.com/codejam/contest/351101/dashboard#s=p1) "Reverse Words" """ import sys def main(): """Reads problem data from stdin and prints answers to stdout. Args: None Returns: Nothing """ lines = sys.stdin.read().splitlines() num_test_cases = int(lines[0]) test_cases = lines[1:] assert len(test_cases) == num_test_cases i = 1 for test_case in test_cases: words = test_case.split() words.reverse() print 'Case #%d:' % (i,), ' '.join(words) i += 1 if __name__ == '__main__': main()
#!/usr/bin/python -tt """Solves problem B from Google Code Jam Qualification Round Africa 2010 (https://code.google.com/codejam/contest/351101/dashboard#s=p1) "Reverse Words" """ import sys def main(): """Reads problem data from stdin and prints answers to stdout. Args: None Returns: Nothing Raises: AssertionError: on invalid input (claimed number of test cases does not match actual number) """ lines = sys.stdin.read().splitlines() num_test_cases = int(lines[0]) test_cases = lines[1:] assert len(test_cases) == num_test_cases i = 1 for test_case in test_cases: words = test_case.split() words.reverse() print 'Case #%d:' % (i,), ' '.join(words) i += 1 if __name__ == '__main__': main()
Add description of assertions raised
Add description of assertions raised
Python
cc0-1.0
mschruf/python
--- +++ @@ -15,6 +15,10 @@ Returns: Nothing + + Raises: + AssertionError: on invalid input (claimed number of test cases + does not match actual number) """ lines = sys.stdin.read().splitlines()
504f46a7dd56d78538547bb74515dd55ac1668fb
myhdl/_delay.py
myhdl/_delay.py
# This file is part of the myhdl library, a Python package for using # Python as a Hardware Description Language. # # Copyright (C) 2003-2008 Jan Decaluwe # # The myhdl library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of the # License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ Module that provides the delay class.""" _errmsg = "arg of delay constructor should be a natural integeer" class delay(object): """ Class to model delay in yield statements. """ def __init__(self, val): """ Return a delay instance. Required parameters: val -- a natural integer representing the desired delay """ if not isinstance(val, int) or val < 0: raise TypeError(_errmsg) self._time = val
# This file is part of the myhdl library, a Python package for using # Python as a Hardware Description Language. # # Copyright (C) 2003-2008 Jan Decaluwe # # The myhdl library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of the # License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ Module that provides the delay class.""" _errmsg = "arg of delay constructor should be a natural integer" class delay(object): """ Class to model delay in yield statements. """ def __init__(self, val): """ Return a delay instance. Required parameters: val -- a natural integer representing the desired delay """ if not isinstance(val, int) or val < 0: raise TypeError(_errmsg) self._time = val
Fix a typo in an error message
Fix a typo in an error message integeer -> integer
Python
lgpl-2.1
myhdl/myhdl,myhdl/myhdl,josyb/myhdl,myhdl/myhdl,josyb/myhdl,josyb/myhdl
--- +++ @@ -18,7 +18,7 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """ Module that provides the delay class.""" -_errmsg = "arg of delay constructor should be a natural integeer" +_errmsg = "arg of delay constructor should be a natural integer" class delay(object):
407f3dfc9f2d87942908c23e6c4db938ac4d94dc
run_migrations.py
run_migrations.py
""" Run all migrations """ import imp import os import sys import pymongo from os.path import join import logging logging.basicConfig(level=logging.DEBUG) ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) def load_config(env): config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config') fp = None try: sys.path.append(config_path) fp, pathname, description = imp.find_module( "backdrop/write/config/%s" % env) return imp.load_module(env, fp, pathname, description) finally: sys.path.pop() if fp: fp.close() def get_database(config): client = pymongo.MongoClient(config.MONGO_HOST, config.MONGO_PORT) return client[config.DATABASE_NAME] def get_migrations(): migrations_path = join(ROOT_PATH, 'migrations') for migration_file in os.listdir(migrations_path): if migration_file.endswith('.py'): migration_path = join(migrations_path, migration_file) yield imp.load_source('migration', migration_path) if __name__ == '__main__': config = load_config(os.getenv('GOVUK_ENV', 'development')) database = get_database(config) for migration in get_migrations(): migration.up(database)
""" Run all migrations """ import imp import os import sys import pymongo from os.path import join import logging logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) def load_config(env): config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config') fp = None try: sys.path.append(config_path) fp, pathname, description = imp.find_module( "backdrop/write/config/%s" % env) return imp.load_module(env, fp, pathname, description) finally: sys.path.pop() if fp: fp.close() def get_database(config): client = pymongo.MongoClient(config.MONGO_HOST, config.MONGO_PORT) return client[config.DATABASE_NAME] def get_migrations(): migrations_path = join(ROOT_PATH, 'migrations') for migration_file in os.listdir(migrations_path): if migration_file.endswith('.py'): migration_path = join(migrations_path, migration_file) yield imp.load_source('migration', migration_path) if __name__ == '__main__': config = load_config(os.getenv('GOVUK_ENV', 'development')) database = get_database(config) for migration in get_migrations(): log.info("Running migration %s" % migration) migration.up(database)
Make migration logging more verbose
Make migration logging more verbose
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
--- +++ @@ -9,6 +9,7 @@ import logging logging.basicConfig(level=logging.DEBUG) +log = logging.getLogger(__name__) ROOT_PATH = os.path.abspath(os.path.dirname(__file__)) @@ -48,4 +49,5 @@ database = get_database(config) for migration in get_migrations(): + log.info("Running migration %s" % migration) migration.up(database)
4b0b85a54208625c7a2753d8ba9b96818f1411d0
denorm/__init__.py
denorm/__init__.py
from denorm.fields import denormalized from denorm.dependencies import depend_on_related,depend_on_q
from denorm.fields import denormalized from denorm.dependencies import depend_on_related, depend_on_q __all__ = ["denormalized", "depend_on_related", "depend_on_q"]
Use __all__ to make it not overwrite .models randomly.
Use __all__ to make it not overwrite .models randomly.
Python
bsd-3-clause
heinrich5991/django-denorm,miracle2k/django-denorm,Chive/django-denorm,anentropic/django-denorm,simas/django-denorm,catalanojuan/django-denorm,victorvde/django-denorm,initcrash/django-denorm,PetrDlouhy/django-denorm,gerdemb/django-denorm,kennknowles/django-denorm,Eksmo/django-denorm,alex-mcleod/django-denorm,mjtamlyn/django-denorm,Kronuz/django-denorm,lechup/django-denorm,idahogray/django-denorm,larsbijl/django-denorm,incuna/django-denorm
--- +++ @@ -1,3 +1,5 @@ from denorm.fields import denormalized -from denorm.dependencies import depend_on_related,depend_on_q +from denorm.dependencies import depend_on_related, depend_on_q + +__all__ = ["denormalized", "depend_on_related", "depend_on_q"]
4799fbb78503e16095b72e39fa243dcbaeef94b2
lib/rapidsms/tests/test_backend_irc.py
lib/rapidsms/tests/test_backend_irc.py
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import unittest from harness import MockRouter class TestLog(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
#!/usr/bin/env python # vim: ai ts=4 sts=4 et sw=4 import unittest from harness import MockRouter class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try: import irclib from rapidsms.backends.irc import Backend backend = Backend("irc", router) backend.configure(host="localhost",nick="test",channels="#test1,#test2") self.assertEquals(type(backend), Backend, "IRC backend loads") self.assertEquals(backend.nick, "test", "IRC backend has nick set") self.assertEquals(backend.host, "localhost", "IRC backend has host set") self.assertEquals(backend.channels, ["#test1","#test2"], "IRC backend has channels correctly set") except ImportError: pass if __name__ == "__main__": unittest.main()
Rename test class (sloppy cut n' paste job)
Rename test class (sloppy cut n' paste job)
Python
bsd-3-clause
dimagi/rapidsms-core-dev,dimagi/rapidsms-core-dev,unicefuganda/edtrac,unicefuganda/edtrac,ken-muturi/rapidsms,catalpainternational/rapidsms,caktus/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,peterayeni/rapidsms,dimagi/rapidsms,catalpainternational/rapidsms,lsgunth/rapidsms,dimagi/rapidsms,lsgunth/rapidsms,caktus/rapidsms,caktus/rapidsms,eHealthAfrica/rapidsms,eHealthAfrica/rapidsms,lsgunth/rapidsms,peterayeni/rapidsms,ken-muturi/rapidsms,lsgunth/rapidsms,eHealthAfrica/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,unicefuganda/edtrac,ehealthafrica-ci/rapidsms,catalpainternational/rapidsms,peterayeni/rapidsms,ken-muturi/rapidsms
--- +++ @@ -4,7 +4,7 @@ import unittest from harness import MockRouter -class TestLog(unittest.TestCase): +class TestBackendIRC(unittest.TestCase): def test_backend_irc (self): router = MockRouter() try:
6771b83ec65f015fa58191694ad068063f61672b
amazon.py
amazon.py
from osv import osv, fields import time import datetime import inspect import xmlrpclib import netsvc import os import logging import urllib2 import base64 from tools.translate import _ import httplib, ConfigParser, urlparse from xml.dom.minidom import parse, parseString from lxml import etree from xml.etree.ElementTree import ElementTree import amazonerp_osv as mws from mako.lookup import TemplateLookup this_dir = os.path.dirname(os.path.realpath(__file__)) logger = logging.getLogger(__name__) templates = TemplateLookup(directories=[os.path.join(this_dir, 'ups')], default_filters=['unicode', 'x']) class amazon_instance(osv.osv): _inherit = 'amazon.instance' def create_orders(self, cr, uid, instance_obj, shop_id, results): res = super(amazon_instance, self).create_orders(cr, uid, instance_obj, shop_id, results) if res: amazon_order_ids = [result['AmazonOrderId'] for result in results if result.get('OrderStatus') == 'Unshipped' and 'AmazonOrderId' in result] sale_order_pool = self.pool.get('sale.order') sale_order_pool.write(cr, uid, sale_order_pool.search( cr, uid, ['amazon_order_id', 'in', amazon_order_ids]), { 'input_channel': 'amazon', 'payment_channel': 'amazon' }) return res amazon_instance()
from osv import osv, fields class amazon_instance(osv.osv): _inherit = 'amazon.instance' def create_orders(self, cr, uid, instance_obj, shop_id, results): return super(amazon_instance, self).create_orders(cr, uid, instance_obj, shop_id, results, defaults={ "payment_channel": "amazon", "input_channel": "amazon" }) amazon_instance()
Simplify defaulting the sale and payment channels for Amazon sales.
Simplify defaulting the sale and payment channels for Amazon sales.
Python
agpl-3.0
ryepdx/sale_channels
--- +++ @@ -1,41 +1,12 @@ from osv import osv, fields -import time -import datetime -import inspect -import xmlrpclib -import netsvc -import os -import logging -import urllib2 -import base64 -from tools.translate import _ -import httplib, ConfigParser, urlparse -from xml.dom.minidom import parse, parseString -from lxml import etree -from xml.etree.ElementTree import ElementTree -import amazonerp_osv as mws -from mako.lookup import TemplateLookup - -this_dir = os.path.dirname(os.path.realpath(__file__)) -logger = logging.getLogger(__name__) -templates = TemplateLookup(directories=[os.path.join(this_dir, 'ups')], default_filters=['unicode', 'x']) class amazon_instance(osv.osv): _inherit = 'amazon.instance' def create_orders(self, cr, uid, instance_obj, shop_id, results): - res = super(amazon_instance, self).create_orders(cr, uid, instance_obj, shop_id, results) - if res: - amazon_order_ids = [result['AmazonOrderId'] - for result in results - if result.get('OrderStatus') == 'Unshipped' and 'AmazonOrderId' in result] - - sale_order_pool = self.pool.get('sale.order') - sale_order_pool.write(cr, uid, sale_order_pool.search( - cr, uid, ['amazon_order_id', 'in', amazon_order_ids]), { - 'input_channel': 'amazon', 'payment_channel': 'amazon' - }) - - return res + return super(amazon_instance, self).create_orders(cr, uid, instance_obj, shop_id, results, defaults={ + "payment_channel": "amazon", + "input_channel": "amazon" + }) amazon_instance()
66461c43b3a0229d02c58ad7aae4653bb638715c
students/crobison/session03/mailroom.py
students/crobison/session03/mailroom.py
# Charles Robison # 2016.10.16 # Mailroom Lab #!/usr/bin/env python donors = { 'Smith':[100, 125, 100], 'Galloway':[50], 'Williams':[22, 43, 40, 3.25], 'Cruz':[101], 'Maples':[1.50, 225] } def print_report(): print("This will print a report") for i in donors.values(): print(sum(i)) def send_thanks(): print("This will write a thank you note") # here is where triple quoted strings can be helpful msg = """ What would you like to do? To send a thank you: type "s" To print a report: type "p" To exit: type "x" """ def main(): """ run the main interactive loop """ response = '' # keep asking until the users responds with an 'x' while True: # make sure there is a break if you have infinite loop! print(msg) response = input("==> ").strip() # strip() in case there are any spaces if response == 'p': print_report() elif response == 's': send_thanks() elif response == 'x': break else: print('please type "s", "p", or "x"') if __name__ == "__main__": main()
# Charles Robison # 2016.10.16 # Mailroom Lab #!/usr/bin/env python donors = { 'Smith':[100, 125, 100], 'Galloway':[50], 'Williams':[22, 43, 40, 3.25], 'Cruz':[101], 'Maples':[1.50, 225] } donations = {} for k, v in donors.items(): donations[k] = sum(v) def print_report(): print("This will print a report") for i in donations: print(i, donations[i]) def send_thanks(): print("This will write a thank you note") # here is where triple quoted strings can be helpful msg = """ What would you like to do? To send a thank you: type "s" To print a report: type "p" To exit: type "x" """ def main(): """ run the main interactive loop """ response = '' # keep asking until the users responds with an 'x' while True: # make sure there is a break if you have infinite loop! print(msg) response = input("==> ").strip() # strip() in case there are any spaces if response == 'p': print_report() elif response == 's': send_thanks() elif response == 'x': break else: print('please type "s", "p", or "x"') if __name__ == "__main__": main()
Add function to list donors and total donations.
Add function to list donors and total donations.
Python
unlicense
UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,Baumelbi/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,Baumelbi/IntroPython2016,UWPCE-PythonCert/IntroPython2016
--- +++ @@ -12,10 +12,14 @@ 'Maples':[1.50, 225] } +donations = {} +for k, v in donors.items(): + donations[k] = sum(v) + def print_report(): print("This will print a report") - for i in donors.values(): - print(sum(i)) + for i in donations: + print(i, donations[i]) def send_thanks():
bb8d9aa91b6d1bf2a765113d5845402c059e6969
IPython/core/payloadpage.py
IPython/core/payloadpage.py
# encoding: utf-8 """A payload based version of page.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from IPython.core.getipython import get_ipython #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- def page(strng, start=0, screen_lines=0, pager_cmd=None): """Print a string, piping through a pager. This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead. Parameters ---------- strng : str or mime-dict Text to page, or a mime-type keyed dict of already formatted data. start : int Starting line at which to place the display. """ # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) shell = get_ipython() if isinstance(strng, dict): data = strng else: data = {'text/plain' : strng} payload = dict( source='page', data=data, text=strng, start=start, screen_lines=screen_lines, ) shell.payload_manager.write_payload(payload) def install_payload_page(): """Install this version of page as IPython.core.page.page.""" from IPython.core import page as corepage corepage.page = page
# encoding: utf-8 """A payload based version of page.""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from IPython.core.getipython import get_ipython #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- def page(strng, start=0, screen_lines=0, pager_cmd=None): """Print a string, piping through a pager. This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead. Parameters ---------- strng : str or mime-dict Text to page, or a mime-type keyed dict of already formatted data. start : int Starting line at which to place the display. """ # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) shell = get_ipython() if isinstance(strng, dict): data = strng else: data = {'text/plain' : strng} payload = dict( source='page', data=data, start=start, screen_lines=screen_lines, ) shell.payload_manager.write_payload(payload) def install_payload_page(): """Install this version of page as IPython.core.page.page.""" from IPython.core import page as corepage corepage.page = page
Remove leftover text key from our own payload creation
Remove leftover text key from our own payload creation
Python
bsd-3-clause
ipython/ipython,ipython/ipython
--- +++ @@ -37,7 +37,6 @@ payload = dict( source='page', data=data, - text=strng, start=start, screen_lines=screen_lines, )
39e561b2675649279cbff4aa457216d12072160b
paws/request.py
paws/request.py
from Cookie import SimpleCookie from urlparse import parse_qs from utils import MultiDict, cached_property class Request(object): def __init__(self, event, context): self.event = event self.context = context @property def method(self): return self.event['httpMethod'] @property def query(self): return self.event['queryStringParameters'] @cached_property def post(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) @cached_property def cookies(self): jar = SimpleCookie() if self.event['headers'].get('Cookie'): jar.load(self.event['headers']['Cookie'].encode('utf-8')) return jar @property def stage(self): return self.event['stage'] @property def stageVar(self): return self.event['stageVariables'] @property def params(self): return self.event['pathParameters']
from Cookie import SimpleCookie from urlparse import parse_qs from utils import MultiDict, cached_property class Request(object): def __init__(self, event, context): self.event = event self.context = context @property def method(self): return self.event['httpMethod'] @property def query(self): return self.event['queryStringParameters'] @cached_property def form(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) @cached_property def cookies(self): jar = SimpleCookie() if self.event['headers'].get('Cookie'): jar.load(self.event['headers']['Cookie'].encode('utf-8')) return jar @property def stage(self): return self.event['stage'] @property def stageVar(self): return self.event['stageVariables'] @property def params(self): return self.event['pathParameters']
Use more sensible name for post data
Use more sensible name for post data
Python
bsd-3-clause
funkybob/paws
--- +++ @@ -18,7 +18,7 @@ return self.event['queryStringParameters'] @cached_property - def post(self): + def form(self): return MultiDict(parse_qs(self.event.get('body', '') or '')) @cached_property
4b863a659e36b1fa9887847e9dbb133b1852cf9b
examples/miniapps/bundles/run.py
examples/miniapps/bundles/run.py
"""Run 'Bundles' example application.""" import sqlite3 import boto3 from dependency_injector import containers from dependency_injector import providers from bundles.users import Users from bundles.photos import Photos class Core(containers.DeclarativeContainer): """Core container.""" config = providers.Configuration('config') sqlite = providers.Singleton(sqlite3.connect, config.database.dsn) s3 = providers.Singleton( boto3.client, 's3', aws_access_key_id=config.aws.access_key_id, aws_secret_access_key=config.aws.secret_access_key) if __name__ == '__main__': # Initializing containers core = Core() core.config.update({'database': {'dsn': ':memory:'}, 'aws': {'access_key_id': 'KEY', 'secret_access_key': 'SECRET'}}) users = Users(database=core.sqlite) photos = Photos(database=core.sqlite, file_storage=core.s3) # Fetching few users user_repository = users.user_repository() user1 = user_repository.get(id=1) user2 = user_repository.get(id=2) # Making some checks assert user1.id == 1 assert user2.id == 2 assert user_repository.db is core.sqlite()
"""Run 'Bundles' example application.""" import sqlite3 import boto3 from dependency_injector import containers from dependency_injector import providers from bundles.users import Users from bundles.photos import Photos class Core(containers.DeclarativeContainer): """Core container.""" config = providers.Configuration('config') sqlite = providers.Singleton(sqlite3.connect, config.database.dsn) s3 = providers.Singleton( boto3.client, 's3', aws_access_key_id=config.aws.access_key_id, aws_secret_access_key=config.aws.secret_access_key) if __name__ == '__main__': # Initializing containers core = Core(config={'database': {'dsn': ':memory:'}, 'aws': {'access_key_id': 'KEY', 'secret_access_key': 'SECRET'}}) users = Users(database=core.sqlite) photos = Photos(database=core.sqlite, file_storage=core.s3) # Fetching few users user_repository = users.user_repository() user1 = user_repository.get(id=1) user2 = user_repository.get(id=2) # Making some checks assert user1.id == 1 assert user2.id == 2 assert user_repository.db is core.sqlite()
Update bundles example after configuration provider refactoring
Update bundles example after configuration provider refactoring
Python
bsd-3-clause
ets-labs/dependency_injector,ets-labs/python-dependency-injector,rmk135/objects,rmk135/dependency_injector
--- +++ @@ -23,8 +23,7 @@ if __name__ == '__main__': # Initializing containers - core = Core() - core.config.update({'database': {'dsn': ':memory:'}, + core = Core(config={'database': {'dsn': ':memory:'}, 'aws': {'access_key_id': 'KEY', 'secret_access_key': 'SECRET'}}) users = Users(database=core.sqlite)
d9c005669c65d65a18b0bd8527918c5dd3fa688c
manage/fabfile/ci.py
manage/fabfile/ci.py
from fabric.api import * @task @role('ci') def install(): sudo("apt-get install git") sudo("apt-get install maven2") # TODO: maven3 sudo("apt-get install groovy") # TODO: groovy-1.8, or gradle... configure_groovy_grapes() sudo("apt-get install python-dev") sudo("apt-get install python-pip") sudo("pip install fabric") def configure_groovy_grapes(): run("mkdir -p ~/.groovy/") # TODO: #put("grapeConfig.xml", "~/.groovy/grapeConfig.xml")
from fabric.api import * @task @roles('ci') def install(): sudo("apt-get install git") sudo("apt-get install maven2") # TODO: maven3 sudo("apt-get install groovy") # TODO: groovy-1.8, or gradle... configure_groovy_grapes() sudo("apt-get install python-dev") sudo("apt-get install python-pip") sudo("pip install fabric") def configure_groovy_grapes(): run("mkdir -p ~/.groovy/") # TODO: #put("grapeConfig.xml", "~/.groovy/grapeConfig.xml")
Fix typo in fab script
Fix typo in fab script
Python
bsd-2-clause
rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl,rinfo/rdl
--- +++ @@ -1,7 +1,7 @@ from fabric.api import * @task -@role('ci') +@roles('ci') def install(): sudo("apt-get install git") sudo("apt-get install maven2") # TODO: maven3
1ed7d695eff134557990d8b1a5dffa51b6d1d2f6
distarray/run_tests.py
distarray/run_tests.py
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- """ Functions for running DistArray tests. """ from __future__ import print_function import os import sys import shlex import subprocess import distarray def _run_shell_command(specific_cmd): """Run a command with subprocess and pass the results through to stdout. First, change directory to the project directory. """ path = os.path.split(os.path.split(distarray.__file__)[0])[0] os.chdir(path) proc = subprocess.Popen(shlex.split(specific_cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: char = proc.stdout.read(1).decode() if not char: break else: print(char, end="") sys.stdout.flush() def test(): """Run all DistArray tests.""" cmd = "make test" _run_shell_command(cmd) if __name__ == "__main__": test()
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- """ Functions for running DistArray tests. """ from __future__ import print_function import os import sys import shlex import subprocess import distarray def _run_shell_command(specific_cmd): """Run a command with subprocess and pass the results through to stdout. First, change directory to the project directory. """ path = os.path.split(os.path.split(distarray.__file__)[0])[0] os.chdir(path) proc = subprocess.Popen(shlex.split(specific_cmd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: char = proc.stdout.read(1).decode() if not char: return proc.wait() else: print(char, end="") sys.stdout.flush() def test(): """Run all DistArray tests.""" cmd = "make test" return _run_shell_command(cmd) if __name__ == "__main__": sys.exit(test())
Return returncode from shell command.
Return returncode from shell command.
Python
bsd-3-clause
enthought/distarray,RaoUmer/distarray,RaoUmer/distarray,enthought/distarray
--- +++ @@ -31,7 +31,7 @@ while True: char = proc.stdout.read(1).decode() if not char: - break + return proc.wait() else: print(char, end="") sys.stdout.flush() @@ -40,8 +40,8 @@ def test(): """Run all DistArray tests.""" cmd = "make test" - _run_shell_command(cmd) + return _run_shell_command(cmd) if __name__ == "__main__": - test() + sys.exit(test())
e0cfd055540b5647b0bd5a4cfffb9c1a3399c721
tests/commands/load/test_load_coverage_qc_report_cmd.py
tests/commands/load/test_load_coverage_qc_report_cmd.py
# -*- coding: utf-8 -*- import os from scout.demo import coverage_qc_report from scout.commands import cli def test_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(coverage_qc_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], coverage_qc_report_path, "-u"], ) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], "invalid-path", "-u"], ) assert "does not exist" in result.output assert result.exit_code == 2
# -*- coding: utf-8 -*- import os from scout.demo import coverage_qc_report from scout.commands import cli def test_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" # Make sure the path to delivery report is a valid path assert os.path.isfile(coverage_qc_report_path) runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], coverage_qc_report_path, "-u"], ) assert "saved report to case!" in result.output assert result.exit_code == 0 def test_invalid_path_load_coverage_qc_report(mock_app, case_obj): """Testing the load delivery report cli command""" runner = mock_app.test_cli_runner() assert runner # Test CLI function result = runner.invoke( cli, ["load", "coverage-qc-report", case_obj["_id"], "invalid-path", "-u"], ) assert "does not exist" in result.output assert result.exit_code == 2
Fix code style issues with Black
Fix code style issues with Black
Python
bsd-3-clause
Clinical-Genomics/scout,Clinical-Genomics/scout,Clinical-Genomics/scout
--- +++ @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- import os -from scout.demo import coverage_qc_report +from scout.demo import coverage_qc_report from scout.commands import cli
b6a8c71be9595c1f2e8c76e9b9bbc49c73a9ec5c
backend/api-server/warehaus_api/auth/__init__.py
backend/api-server/warehaus_api/auth/__init__.py
from datetime import timedelta from logging import getLogger from flask import request from flask_jwt import JWT from .models import User from .roles import roles from .roles import user_required from .roles import admin_required from .login import validate_user logger = getLogger(__name__) def authenticate(username, password): try: user = validate_user(username, password) logger.info('Successfully authenticated {!r}'.format(username)) return user except Exception as error: logger.exception('Error authenticating {!r}'.format(username)) def identify(payload): logger.debug('Got payload: {!r}'.format(payload)) jwt_subject = payload.get('sub', None) if jwt_subject is None: return None return User.query.get(jwt_subject) def init_auth(app): app.config['JWT_AUTH_URL_RULE'] = '/api/v1/auth/login' app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) app.config['JWT_AUTH_HEADER_PREFIX'] = 'JWT' jwt = JWT(app, authenticate, identify)
from datetime import datetime from datetime import timedelta from logging import getLogger from flask import request from flask import current_app from flask_jwt import JWT from .models import User from .roles import roles from .roles import user_required from .roles import admin_required from .login import validate_user logger = getLogger(__name__) def authenticate(username, password): try: user = validate_user(username, password) logger.info('Successfully authenticated {!r}'.format(username)) return user except Exception as error: logger.exception('Error authenticating {!r}'.format(username)) def identify(payload): logger.debug('Got payload: {!r}'.format(payload)) jwt_subject = payload.get('sub', None) if jwt_subject is None: return None return User.query.get(jwt_subject) def payload_handler(identity): iat = datetime.utcnow() exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA') nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA') identity = getattr(identity, 'id') or identity['id'] return {'exp': exp, 'iat': iat, 'nbf': nbf, 'sub': identity} def init_auth(app): app.config['JWT_AUTH_URL_RULE'] = '/api/v1/auth/login' app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) app.config['JWT_AUTH_HEADER_PREFIX'] = 'JWT' jwt = JWT(app, authenticate, identify) jwt.jwt_payload_handler(payload_handler)
Fix payload_handler in api-server to generate proper JWTs
Fix payload_handler in api-server to generate proper JWTs
Python
agpl-3.0
warehaus/warehaus,labsome/labsome,warehaus/warehaus,labsome/labsome,labsome/labsome,warehaus/warehaus
--- +++ @@ -1,6 +1,8 @@ +from datetime import datetime from datetime import timedelta from logging import getLogger from flask import request +from flask import current_app from flask_jwt import JWT from .models import User from .roles import roles @@ -25,8 +27,16 @@ return None return User.query.get(jwt_subject) +def payload_handler(identity): + iat = datetime.utcnow() + exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA') + nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA') + identity = getattr(identity, 'id') or identity['id'] + return {'exp': exp, 'iat': iat, 'nbf': nbf, 'sub': identity} + def init_auth(app): app.config['JWT_AUTH_URL_RULE'] = '/api/v1/auth/login' app.config['JWT_EXPIRATION_DELTA'] = timedelta(days=7) app.config['JWT_AUTH_HEADER_PREFIX'] = 'JWT' jwt = JWT(app, authenticate, identify) + jwt.jwt_payload_handler(payload_handler)
9cbfed00905fb8b360b60cce1afc293b71a2aced
check_access.py
check_access.py
#!/usr/bin/env python import os import sys from parse_docker_args import parse_mount def can_access(path, perm): mode = None if perm == 'r': mode = os.R_OK elif perm == 'w': mode = os.W_OK else: return False return os.access(path, mode) if __name__ == '__main__': if len(sys.argv) < 2: exit volume_spec = sys.argv[1] path, perm = parse_mount(volume_spec) uid = os.getuid() if can_access(path, perm): print "PASS: UID {} has {} access to {}".format(uid, perm, path) exit(0) else: print "ERROR: UID {} has no {} access to {}".format(uid, perm, path) exit(1)
#!/usr/bin/env python import os import sys from parse_docker_args import parse_mount def can_access(path, perm): mode = None if perm == 'r': mode = os.R_OK elif perm == 'w': mode = os.W_OK else: return False return os.access(path, mode) if __name__ == '__main__': if len(sys.argv) < 2: print "USAGE: {} <docker volume spec>".format(sys.argv[0]) print "e.g. {} /data/somelab:/input:rw".format(sys.argv[0]) exit(1) volume_spec = sys.argv[1] path, perm = parse_mount(volume_spec) uid = os.getuid() if can_access(path, perm): print "PASS: UID {} has {} access to {}".format(uid, perm, path) exit(0) else: print "ERROR: UID {} has no {} access to {}".format(uid, perm, path) exit(1)
Print usage if not enough args
Print usage if not enough args
Python
mit
Duke-GCB/docker-wrapper,Duke-GCB/docker-wrapper
--- +++ @@ -16,7 +16,9 @@ if __name__ == '__main__': if len(sys.argv) < 2: - exit + print "USAGE: {} <docker volume spec>".format(sys.argv[0]) + print "e.g. {} /data/somelab:/input:rw".format(sys.argv[0]) + exit(1) volume_spec = sys.argv[1] path, perm = parse_mount(volume_spec) uid = os.getuid()
f4dfcf91c11fd06b5b71135f888b6979548a5147
conveyor/__main__.py
conveyor/__main__.py
from __future__ import absolute_import from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from .core import Conveyor def main(): Conveyor().run() if __name__ == "__main__": main()
Bring the standard __future__ imports over
Bring the standard __future__ imports over
Python
bsd-2-clause
crateio/carrier
--- +++ @@ -1,4 +1,6 @@ from __future__ import absolute_import +from __future__ import division +from __future__ import unicode_literals from .core import Conveyor @@ -6,5 +8,6 @@ def main(): Conveyor().run() + if __name__ == "__main__": main()
fca88336777b9c47404e7b397d39ef8d3676b7b5
src/zone_iterator/__main__.py
src/zone_iterator/__main__.py
import gzip import sys from . import zone_iterator, zone_dict_to_str, ZONE_FMT_STR try: from colorama import Fore, init as colorama_init except ImportError: HAS_COLOR = False else: HAS_COLOR = True def main(): if HAS_COLOR: colors = [Fore.GREEN, Fore.MAGENTA, Fore.BLUE, Fore.CYAN, Fore.YELLOW] colorama_init(autoreset=True) unpacked_fmt = ZONE_FMT_STR.split() color_format = " ".join([color for segment in zip(colors, unpacked_fmt) for color in segment]) zone_file = sys.argv[1] if zone_file[-2:] == 'gz': our_open = gzip.open else: our_open = open with our_open(zone_file, mode='rt') as zonefh: for record in zone_iterator(zonefh): print(zone_dict_to_str(record, fmt_str=color_format)) if __name__ == "__main__": main()
import argparse import gzip import sys from . import zone_iterator, zone_dict_to_str, ZONE_FMT_STR try: from colorama import Fore, init as colorama_init except ImportError: HAS_COLOR = False else: HAS_COLOR = True def maybe_compressed_file(filename): if filename[-2:] == 'gz': our_open = gzip.open else: our_open = open return our_open(filename, mode='rt') def main(): parser = argparse.ArgumentParser() parser.add_argument('inputs', nargs='*', type=maybe_compressed_file) args = parser.parse_args() if HAS_COLOR: colors = [Fore.GREEN, Fore.MAGENTA, Fore.BLUE, Fore.CYAN, Fore.YELLOW] colorama_init(autoreset=True) unpacked_fmt = ZONE_FMT_STR.split() color_format = " ".join([color for segment in zip(colors, unpacked_fmt) for color in segment]) for inputfile in args.inputs: with inputfile as zonefh: for record in zone_iterator(zonefh): print(zone_dict_to_str(record, fmt_str=color_format)) if __name__ == "__main__": main()
Switch to using argparse for the main script.
Switch to using argparse for the main script.
Python
agpl-3.0
maxrp/zone_normalize
--- +++ @@ -1,3 +1,4 @@ +import argparse import gzip import sys @@ -11,7 +12,20 @@ HAS_COLOR = True +def maybe_compressed_file(filename): + if filename[-2:] == 'gz': + our_open = gzip.open + else: + our_open = open + + return our_open(filename, mode='rt') + + def main(): + parser = argparse.ArgumentParser() + parser.add_argument('inputs', nargs='*', type=maybe_compressed_file) + args = parser.parse_args() + if HAS_COLOR: colors = [Fore.GREEN, Fore.MAGENTA, Fore.BLUE, Fore.CYAN, Fore.YELLOW] @@ -21,15 +35,11 @@ zip(colors, unpacked_fmt) for color in segment]) - zone_file = sys.argv[1] - if zone_file[-2:] == 'gz': - our_open = gzip.open - else: - our_open = open + for inputfile in args.inputs: + with inputfile as zonefh: + for record in zone_iterator(zonefh): + print(zone_dict_to_str(record, fmt_str=color_format)) - with our_open(zone_file, mode='rt') as zonefh: - for record in zone_iterator(zonefh): - print(zone_dict_to_str(record, fmt_str=color_format)) if __name__ == "__main__": main()
c1756ab481f3bf72ab33465c8eb1d5a3e729ce4e
model_logging/migrations/0003_data_migration.py
model_logging/migrations/0003_data_migration.py
# -*- coding: utf-8 -*- from django.db import migrations app = 'model_logging' model = 'LogEntry' def move_data(apps, schema_editor): LogEntry = apps.get_model(app, model) for entry in LogEntry.objects.all(): entry.data_temp = entry.data entry.save() class Migration(migrations.Migration): dependencies = [ ('model_logging', '0002_add_new_data_field'), ] operations = [ migrations.RunPython(move_data), ]
# -*- coding: utf-8 -*- from django.db import migrations app = 'model_logging' model = 'LogEntry' def move_data(apps, schema_editor): try: from pgcrypto.fields import TextPGPPublicKeyField except ImportError: raise ImportError('Please install django-pgcrypto-fields to perform migration') LogEntry = apps.get_model(app, model) for entry in LogEntry.objects.all(): entry.data_temp = entry.data entry.save() class Migration(migrations.Migration): dependencies = [ ('model_logging', '0002_add_new_data_field'), ] operations = [ migrations.RunPython(move_data), ]
Add try, catch statement to ensure data migration can be performed.
Add try, catch statement to ensure data migration can be performed.
Python
bsd-2-clause
incuna/django-model-logging
--- +++ @@ -6,6 +6,11 @@ def move_data(apps, schema_editor): + try: + from pgcrypto.fields import TextPGPPublicKeyField + except ImportError: + raise ImportError('Please install django-pgcrypto-fields to perform migration') + LogEntry = apps.get_model(app, model) for entry in LogEntry.objects.all(): entry.data_temp = entry.data
ba57b3c016ed3bc3c8db9ccc3c637c2c58de1e1d
reddit/admin.py
reddit/admin.py
from django.contrib import admin from reddit.models import RedditUser,Submission,Comment,Vote # Register your models here. class SubmissionInline(admin.TabularInline): model = Submission max_num = 10 class CommentsInline(admin.StackedInline): model = Comment max_num = 10 class SubmissionAdmin(admin.ModelAdmin): list_display = ('title', 'url', 'author') inlines = [CommentsInline] class RedditUserAdmin(admin.ModelAdmin): inlines = [ SubmissionInline, CommentsInline ] admin.site.register(RedditUser, RedditUserAdmin) admin.site.register(Submission, SubmissionAdmin) admin.site.register(Comment) admin.site.register(Vote)
from django.contrib import admin from reddit.models import RedditUser,Submission,Comment,Vote # Register your models here. class SubmissionInline(admin.TabularInline): model = Submission max_num = 10 class CommentsInline(admin.StackedInline): model = Comment max_num = 10 class SubmissionAdmin(admin.ModelAdmin): list_display = ('title', 'url', 'author') inlines = [CommentsInline] class RedditUserAdmin(admin.ModelAdmin): inlines = [ SubmissionInline, ] admin.site.register(RedditUser, RedditUserAdmin) admin.site.register(Submission, SubmissionAdmin) admin.site.register(Comment) admin.site.register(Vote)
Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser
Remove commentsInLine for RedditUser because there is no longer foreignKey from Comment to RedditUser
Python
apache-2.0
Nikola-K/django_reddit,Nikola-K/django_reddit,Nikola-K/django_reddit
--- +++ @@ -17,7 +17,6 @@ class RedditUserAdmin(admin.ModelAdmin): inlines = [ SubmissionInline, - CommentsInline ] admin.site.register(RedditUser, RedditUserAdmin)
5c0a64eb2f580225c07f09494ac723da16b38d18
openedx/features/job_board/views.py
openedx/features/job_board/views.py
from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobListView(ListView): model = Job context_object_name = 'jobs_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] template_engine = 'mako' def get_context_data(self, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) context['total_job_count'] = Job.objects.all().count() return context def show_job_detail(request): return render_to_response('features/job_board/job_detail.html', {})
from django.views.generic.list import ListView from edxmako.shortcuts import render_to_response from .models import Job class JobListView(ListView): model = Job context_object_name = 'job_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created'] template_engine = 'mako' def get_context_data(self, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) context['total_job_count'] = Job.objects.all().count() return context def show_job_detail(request): return render_to_response('features/job_board/job_detail.html', {})
Change jobs_list object name to job_list
Change jobs_list object name to job_list
Python
agpl-3.0
philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform
--- +++ @@ -8,7 +8,7 @@ class JobListView(ListView): model = Job - context_object_name = 'jobs_list' + context_object_name = 'job_list' paginate_by = 10 template_name = 'features/job_board/job_list.html' ordering = ['-created']
dd75314f203b907f25a7b7e158c7e5d988a5b6ae
neo/test/rawiotest/test_openephysbinaryrawio.py
neo/test/rawiotest/test_openephysbinaryrawio.py
import unittest from neo.rawio.openephysbinaryrawio import OpenEphysBinaryRawIO from neo.test.rawiotest.common_rawio_test import BaseTestRawIO class TestOpenEphysBinaryRawIO(BaseTestRawIO, unittest.TestCase): rawioclass = OpenEphysBinaryRawIO entities_to_download = [ 'openephysbinary' ] entities_to_test = [ 'openephysbinary/v0.5.3_two_neuropixels_stream', 'openephysbinary/v0.4.4.1_with_video_tracking', 'openephysbinary/v0.5.x_two_nodes', ] if __name__ == "__main__": unittest.main()
import unittest from neo.rawio.openephysbinaryrawio import OpenEphysBinaryRawIO from neo.test.rawiotest.common_rawio_test import BaseTestRawIO class TestOpenEphysBinaryRawIO(BaseTestRawIO, unittest.TestCase): rawioclass = OpenEphysBinaryRawIO entities_to_download = [ 'openephysbinary' ] entities_to_test = [ 'openephysbinary/v0.5.3_two_neuropixels_stream', 'openephysbinary/v0.4.4.1_with_video_tracking', 'openephysbinary/v0.5.x_two_nodes', 'openephysbinary/v0.6.x_neuropixels_multiexp_multistream', ] if __name__ == "__main__": unittest.main()
Add new OE test folder
Add new OE test folder
Python
bsd-3-clause
apdavison/python-neo,JuliaSprenger/python-neo,NeuralEnsemble/python-neo,INM-6/python-neo
--- +++ @@ -13,6 +13,7 @@ 'openephysbinary/v0.5.3_two_neuropixels_stream', 'openephysbinary/v0.4.4.1_with_video_tracking', 'openephysbinary/v0.5.x_two_nodes', + 'openephysbinary/v0.6.x_neuropixels_multiexp_multistream', ]
7c9d2ace7de2727c43b0ee00f8f2280d8a465301
Python/brewcaskupgrade.py
Python/brewcaskupgrade.py
#! /usr/bin/env python # -*- coding: utf8 -*- import argparse import shutil from subprocess import check_output, run parser = argparse.ArgumentParser(description='Update every entries found in cask folder.') parser.add_argument('--pretend', dest='pretend', action='store_true', help='Pretend to take action.') parser.set_defaults(pretend=False) args = parser.parse_args() brew_bin = 'brew' if not shutil.which(brew_bin): raise FileExistsError(brew_bin + ' not exists') list_command = [ brew_bin, 'cask', 'list' ] list_installed = str.split(check_output(list_command).decode(), '\n') list_installed = [i for i in list_installed if i is not ''] for cask in list_installed: info_command = [ brew_bin, 'cask', 'info', cask ] try: install_status = check_output(info_command).decode() except: install_status = 'Not installed' if 'Not installed' in install_status: print('Installing', cask) install_command = [ brew_bin, 'cask', 'install', '--force', cask ] if args.pretend: print(' '.join(install_command)) else: run(install_command) print('Installed', cask)
#! /usr/bin/env python # -*- coding: utf8 -*- import argparse import shutil from subprocess import check_output, run parser = argparse.ArgumentParser(description='Update every entries found in cask folder.') parser.add_argument('--pretend', dest='pretend', action='store_true', help='Pretend to take action.') parser.set_defaults(pretend=False) args = parser.parse_args() brew_bin = 'brew' if not shutil.which(brew_bin): raise FileExistsError(brew_bin + ' not exists') list_command = [ brew_bin, 'cask', 'list' ] list_installed = str.split(check_output(list_command).decode(), '\n') list_installed = [i for i in list_installed if i is not ''] for cask in list_installed: info_command = [ brew_bin, 'cask', 'info', cask ] try: install_status = str.splitlines(check_output(info_command).decode()) except: install_status = 'Not installed' version = str.strip(str.split(install_status[0], ':')[1]) is_version_installed = False for line in install_status: if not line.startswith(cask) and line.__contains__(cask) and line.__contains__(version): is_version_installed = True if not is_version_installed: print('Installing', cask) install_command = [ brew_bin, 'cask', 'install', '--force', cask ] if args.pretend: print(' '.join(install_command)) else: run(install_command) print('Installed', cask)
Check version for latest cask behaviour changed
Check version for latest cask behaviour changed
Python
cc0-1.0
boltomli/MyMacScripts,boltomli/MyMacScripts
--- +++ @@ -32,11 +32,17 @@ cask ] try: - install_status = check_output(info_command).decode() + install_status = str.splitlines(check_output(info_command).decode()) except: install_status = 'Not installed' - if 'Not installed' in install_status: + version = str.strip(str.split(install_status[0], ':')[1]) + is_version_installed = False + for line in install_status: + if not line.startswith(cask) and line.__contains__(cask) and line.__contains__(version): + is_version_installed = True + + if not is_version_installed: print('Installing', cask) install_command = [ brew_bin,
703e61104317332d60bd0bde49652b8618cd0e6b
var/spack/packages/mrnet/package.py
var/spack/packages/mrnet/package.py
from spack import * class Mrnet(Package): """The MRNet Multi-Cast Reduction Network.""" homepage = "http://paradyn.org/mrnet" url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz" versions = { '4.0.0' : 'd00301c078cba57ef68613be32ceea2f', } parallel = False def install(self, spec, prefix): configure("--prefix=%s" %prefix, "--enable-shared") make() make("install") # TODO: copy configuration header files to include directory # this can be removed once we have STAT-2.1.0 import shutil shutil.copy2('%s/lib/mrnet-%s/include/mrnet_config.h' % (prefix, self.version), '%s/include/mrnet_config.h' % prefix) shutil.copy2('%s/lib/xplat-%s/include/xplat_config.h' % (prefix, self.version), '%s/include/xplat_config.h' % prefix)
from spack import * class Mrnet(Package): """The MRNet Multi-Cast Reduction Network.""" homepage = "http://paradyn.org/mrnet" url = "ftp://ftp.cs.wisc.edu/paradyn/mrnet/mrnet_4.0.0.tar.gz" versions = { '4.0.0' : 'd00301c078cba57ef68613be32ceea2f', } parallel = False depends_on("boost") def install(self, spec, prefix): configure("--prefix=%s" %prefix, "--enable-shared") make() make("install") # TODO: copy configuration header files to include directory # this can be removed once we have STAT-2.1.0 import shutil shutil.copy2('%s/lib/mrnet-%s/include/mrnet_config.h' % (prefix, self.version), '%s/include/mrnet_config.h' % prefix) shutil.copy2('%s/lib/xplat-%s/include/xplat_config.h' % (prefix, self.version), '%s/include/xplat_config.h' % prefix)
Make mrnet depend on boost.
Make mrnet depend on boost.
Python
lgpl-2.1
mfherbst/spack,iulian787/spack,tmerrick1/spack,LLNL/spack,mfherbst/spack,TheTimmy/spack,krafczyk/spack,LLNL/spack,krafczyk/spack,TheTimmy/spack,mfherbst/spack,TheTimmy/spack,krafczyk/spack,tmerrick1/spack,skosukhin/spack,EmreAtes/spack,lgarren/spack,matthiasdiener/spack,EmreAtes/spack,iulian787/spack,EmreAtes/spack,matthiasdiener/spack,lgarren/spack,tmerrick1/spack,LLNL/spack,EmreAtes/spack,tmerrick1/spack,lgarren/spack,iulian787/spack,EmreAtes/spack,matthiasdiener/spack,matthiasdiener/spack,LLNL/spack,skosukhin/spack,tmerrick1/spack,mfherbst/spack,TheTimmy/spack,iulian787/spack,krafczyk/spack,mfherbst/spack,iulian787/spack,LLNL/spack,matthiasdiener/spack,lgarren/spack,TheTimmy/spack,skosukhin/spack,krafczyk/spack,skosukhin/spack,skosukhin/spack,lgarren/spack
--- +++ @@ -8,6 +8,8 @@ versions = { '4.0.0' : 'd00301c078cba57ef68613be32ceea2f', } parallel = False + depends_on("boost") + def install(self, spec, prefix): configure("--prefix=%s" %prefix, "--enable-shared") @@ -17,5 +19,7 @@ # TODO: copy configuration header files to include directory # this can be removed once we have STAT-2.1.0 import shutil - shutil.copy2('%s/lib/mrnet-%s/include/mrnet_config.h' % (prefix, self.version), '%s/include/mrnet_config.h' % prefix) - shutil.copy2('%s/lib/xplat-%s/include/xplat_config.h' % (prefix, self.version), '%s/include/xplat_config.h' % prefix) + shutil.copy2('%s/lib/mrnet-%s/include/mrnet_config.h' % (prefix, self.version), + '%s/include/mrnet_config.h' % prefix) + shutil.copy2('%s/lib/xplat-%s/include/xplat_config.h' % (prefix, self.version), + '%s/include/xplat_config.h' % prefix)
9504529dd4b9140be0026d0b30a0e88e5dea5e25
rtrss/config.py
rtrss/config.py
import os import logging import importlib # All configuration defaults are set in this module TRACKER_HOST = 'rutracker.org' # Timeone for the tracker times TZNAME = 'Europe/Moscow' LOGLEVEL = logging.INFO LOG_FORMAT_LOGENTRIES = '%(levelname)s %(name)s %(message)s' LOG_FORMAT_BRIEF = '%(asctime)s %(levelname)s %(name)s %(message)s' ADMIN_LOGIN = os.environ.get('ADMIN_LOGIN', 'admin') ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin') ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL', 'admin@localhost') # path to save torrent files TORRENT_PATH_PATTERN = 'torrents/{}.torrent' APP_ENVIRONMENT = os.environ.get('RTRSS_ENVIRONMENT') if not APP_ENVIRONMENT: raise EnvironmentError('RTRSS_ENVIRONMENT must be set') _mod = importlib.import_module('rtrss.config_{}'.format(APP_ENVIRONMENT)) _envconf = {k: v for k, v in _mod.__dict__.items() if k == k.upper()} globals().update(_envconf)
import os import logging import importlib # All configuration defaults are set in this module TRACKER_HOST = 'rutracker.org' # Timeone for the tracker times TZNAME = 'Europe/Moscow' LOGLEVEL = logging.INFO LOG_FORMAT_LOGENTRIES = '%(levelname)s %(name)s %(message)s' LOG_FORMAT_BRIEF = '%(asctime)s %(levelname)s %(name)s %(message)s' ADMIN_LOGIN = os.environ.get('ADMIN_LOGIN', 'admin') ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin') ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL', 'admin@localhost') # path to save torrent files TORRENT_PATH_PATTERN = 'torrents/{}.torrent' APP_ENVIRONMENT = os.environ.get('RTRSS_ENVIRONMENT') if not APP_ENVIRONMENT: raise EnvironmentError('RTRSS_ENVIRONMENT must be set') IP = '0.0.0.0' PORT = 8080 _mod = importlib.import_module('rtrss.config_{}'.format(APP_ENVIRONMENT)) _envconf = {k: v for k, v in _mod.__dict__.items() if k == k.upper()} globals().update(_envconf)
Add default IP and PORT
Add default IP and PORT
Python
apache-2.0
notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss
--- +++ @@ -26,6 +26,9 @@ if not APP_ENVIRONMENT: raise EnvironmentError('RTRSS_ENVIRONMENT must be set') +IP = '0.0.0.0' +PORT = 8080 + _mod = importlib.import_module('rtrss.config_{}'.format(APP_ENVIRONMENT)) _envconf = {k: v for k, v in _mod.__dict__.items() if k == k.upper()} globals().update(_envconf)
87df9686444c46796475da06c67eeca01c4a46cc
scikits/audiolab/pysndfile/__init__.py
scikits/audiolab/pysndfile/__init__.py
from pysndfile import formatinfo, sndfile from pysndfile import supported_format, supported_endianness, \ supported_encoding from pysndfile import PyaudioException, PyaudioIOError from _sndfile import Sndfile, Format, available_file_formats, available_encodings
from _sndfile import Sndfile, Format, available_file_formats, available_encodings from compat import formatinfo, sndfile, PyaudioException, PyaudioIOError from pysndfile import supported_format, supported_endianness, \ supported_encoding
Use compat module instead of ctypes-based implementation.
Use compat module instead of ctypes-based implementation.
Python
lgpl-2.1
cournape/audiolab,cournape/audiolab,cournape/audiolab
--- +++ @@ -1,5 +1,4 @@ -from pysndfile import formatinfo, sndfile +from _sndfile import Sndfile, Format, available_file_formats, available_encodings +from compat import formatinfo, sndfile, PyaudioException, PyaudioIOError from pysndfile import supported_format, supported_endianness, \ supported_encoding -from pysndfile import PyaudioException, PyaudioIOError -from _sndfile import Sndfile, Format, available_file_formats, available_encodings
c767ee0b4392c519335a6055f64bbbb5a500e997
api_tests/base/test_pagination.py
api_tests/base/test_pagination.py
# -*- coding: utf-8 -*- from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from api.base.pagination import MaxSizePagination class TestMaxPagination(ApiTestCase): def test_no_query_param_alters_page_size(self): assert_is_none(MaxSizePagination.page_size_query_param)
# -*- coding: utf-8 -*- from nose.tools import * # flake8: noqa from tests.base import ApiTestCase from api.base.pagination import MaxSizePagination class TestMaxPagination(ApiTestCase): def test_no_query_param_alters_page_size(self): assert MaxSizePagination.page_size_query_param is None, 'Adding variable page sizes to the paginator ' +\ 'requires tests to ensure that you can\'t request more than the class\'s maximum number of values.'
Add error message for future breakers-of-tests
Add error message for future breakers-of-tests
Python
apache-2.0
HalcyonChimera/osf.io,DanielSBrown/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,crcresearch/osf.io,crcresearch/osf.io,alexschiller/osf.io,hmoco/osf.io,rdhyee/osf.io,caneruguz/osf.io,SSJohns/osf.io,laurenrevere/osf.io,icereval/osf.io,sloria/osf.io,emetsger/osf.io,felliott/osf.io,HalcyonChimera/osf.io,mattclark/osf.io,leb2dg/osf.io,cwisecarver/osf.io,chrisseto/osf.io,icereval/osf.io,SSJohns/osf.io,binoculars/osf.io,wearpants/osf.io,emetsger/osf.io,monikagrabowska/osf.io,amyshi188/osf.io,sloria/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,pattisdr/osf.io,crcresearch/osf.io,chrisseto/osf.io,hmoco/osf.io,saradbowman/osf.io,mfraezz/osf.io,alexschiller/osf.io,mluo613/osf.io,wearpants/osf.io,baylee-d/osf.io,cslzchen/osf.io,mfraezz/osf.io,mfraezz/osf.io,Nesiehr/osf.io,felliott/osf.io,acshi/osf.io,samchrisinger/osf.io,SSJohns/osf.io,pattisdr/osf.io,laurenrevere/osf.io,aaxelb/osf.io,caneruguz/osf.io,baylee-d/osf.io,monikagrabowska/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,hmoco/osf.io,Johnetordoff/osf.io,acshi/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,caseyrollins/osf.io,samchrisinger/osf.io,acshi/osf.io,laurenrevere/osf.io,chennan47/osf.io,amyshi188/osf.io,Nesiehr/osf.io,DanielSBrown/osf.io,adlius/osf.io,rdhyee/osf.io,aaxelb/osf.io,pattisdr/osf.io,samchrisinger/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,alexschiller/osf.io,rdhyee/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,leb2dg/osf.io,alexschiller/osf.io,erinspace/osf.io,felliott/osf.io,mluo613/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,amyshi188/osf.io,CenterForOpenScience/osf.io,emetsger/osf.io,sloria/osf.io,DanielSBrown/osf.io,leb2dg/osf.io,acshi/osf.io,chrisseto/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,binoculars/osf.io,mattclark/osf.io,chennan47/osf.io,rdhyee/osf.io,caneruguz/osf.io,chennan47/osf.io,adlius/osf.io,aaxelb/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,mluo613/osf.io,cslzchen/osf.io,Nesiehr/osf.io,erinspace/osf.io,Johnetordoff/osf.io,samchrisinger/osf.io,binoculars/osf.io,icereval/osf.io,adlius/osf.io,TomBaxter/osf.io,brianjgeiger/osf.io,hmoco/osf.io,amyshi188/osf.io,erinspace/osf.io,caseyrollins/osf.io,acshi/osf.io,emetsger/osf.io,felliott/osf.io,cslzchen/osf.io,mluo613/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,cwisecarver/osf.io,mfraezz/osf.io,Nesiehr/osf.io,alexschiller/osf.io,DanielSBrown/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,mattclark/osf.io,caneruguz/osf.io,wearpants/osf.io,wearpants/osf.io,SSJohns/osf.io
--- +++ @@ -7,4 +7,5 @@ class TestMaxPagination(ApiTestCase): def test_no_query_param_alters_page_size(self): - assert_is_none(MaxSizePagination.page_size_query_param) + assert MaxSizePagination.page_size_query_param is None, 'Adding variable page sizes to the paginator ' +\ + 'requires tests to ensure that you can\'t request more than the class\'s maximum number of values.'
d531ea281b546d31724c021011a7145d3095dbf8
SoftLayer/tests/CLI/modules/import_test.py
SoftLayer/tests/CLI/modules/import_test.py
""" SoftLayer.tests.CLI.modules.import_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer.tests import unittest from SoftLayer.CLI.modules import get_module_list from importlib import import_module class TestImportCLIModules(unittest.TestCase): def test_import_all(self): modules = get_module_list() for module in modules: module_path = 'SoftLayer.CLI.modules.' + module import_module(module_path)
""" SoftLayer.tests.CLI.modules.import_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ from SoftLayer.tests import unittest from SoftLayer.CLI.modules import get_module_list from importlib import import_module class TestImportCLIModules(unittest.TestCase): def test_import_all(self): modules = get_module_list() for module in modules: module_path = 'SoftLayer.CLI.modules.' + module print("Importing %s" % module_path) import_module(module_path)
Print modules being imported (for easier debugging)
Print modules being imported (for easier debugging)
Python
mit
allmightyspiff/softlayer-python,underscorephil/softlayer-python,cloudify-cosmo/softlayer-python,iftekeriba/softlayer-python,skraghu/softlayer-python,kyubifire/softlayer-python,nanjj/softlayer-python,Neetuj/softlayer-python,softlayer/softlayer-python,briancline/softlayer-python
--- +++ @@ -16,5 +16,5 @@ modules = get_module_list() for module in modules: module_path = 'SoftLayer.CLI.modules.' + module - + print("Importing %s" % module_path) import_module(module_path)
39a743463f55c3cfbbea05b4d471d01f66dd93f8
permamodel/tests/test_perma_base.py
permamodel/tests/test_perma_base.py
""" test_perma_base.py tests of the perma_base component of permamodel """ from permamodel.components import frost_number import os import numpy as np from .. import permamodel_directory, data_directory, examples_directory def test_directory_names_are_set(): assert(permamodel_directory is not None)
""" test_perma_base.py tests of the perma_base component of permamodel """ import os from nose.tools import assert_true from .. import (permamodel_directory, data_directory, examples_directory, tests_directory) def test_permamodel_directory_is_set(): assert(permamodel_directory is not None) def test_data_directory_is_set(): assert(data_directory is not None) def test_examples_directory_is_set(): assert(examples_directory is not None) def test_tests_directory_is_set(): assert(tests_directory is not None) def test_permamodel_directory_exists(): assert_true(os.path.isdir(permamodel_directory)) def test_data_directory_exists(): assert_true(os.path.isdir(data_directory)) def test_examples_directory_exists(): assert_true(os.path.isdir(examples_directory)) def test_tests_directory_exists(): assert_true(os.path.isdir(tests_directory))
Add unit tests for all package directories
Add unit tests for all package directories
Python
mit
permamodel/permamodel,permamodel/permamodel
--- +++ @@ -3,11 +3,39 @@ tests of the perma_base component of permamodel """ -from permamodel.components import frost_number import os -import numpy as np -from .. import permamodel_directory, data_directory, examples_directory +from nose.tools import assert_true +from .. import (permamodel_directory, data_directory, + examples_directory, tests_directory) -def test_directory_names_are_set(): + +def test_permamodel_directory_is_set(): assert(permamodel_directory is not None) + +def test_data_directory_is_set(): + assert(data_directory is not None) + + +def test_examples_directory_is_set(): + assert(examples_directory is not None) + + +def test_tests_directory_is_set(): + assert(tests_directory is not None) + + +def test_permamodel_directory_exists(): + assert_true(os.path.isdir(permamodel_directory)) + + +def test_data_directory_exists(): + assert_true(os.path.isdir(data_directory)) + + +def test_examples_directory_exists(): + assert_true(os.path.isdir(examples_directory)) + + +def test_tests_directory_exists(): + assert_true(os.path.isdir(tests_directory))
1cdcacb8ab8e78c9b325f454382d591da10b06fd
senlin_dashboard/enabled/_50_senlin.py
senlin_dashboard/enabled/_50_senlin.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from senlin_dashboard import exceptions DASHBOARD = 'cluster' ADD_INSTALLED_APPS = [ 'senlin_dashboard', 'senlin_dashboard.cluster' ] DEFAULT = True AUTO_DISCOVER_STATIC_FILES = True ADD_ANGULAR_MODULES = ['horizon.cluster'] ADD_SCSS_FILES = [ 'app/core/cluster.scss' ] ADD_EXCEPTIONS = { 'recoverable': exceptions.RECOVERABLE, 'not_found': exceptions.NOT_FOUND, 'unauthorized': exceptions.UNAUTHORIZED, }
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from senlin_dashboard import exceptions DASHBOARD = 'cluster' ADD_INSTALLED_APPS = [ 'senlin_dashboard', 'senlin_dashboard.cluster' ] DEFAULT = False AUTO_DISCOVER_STATIC_FILES = True ADD_ANGULAR_MODULES = ['horizon.cluster'] ADD_SCSS_FILES = [ 'app/core/cluster.scss' ] ADD_EXCEPTIONS = { 'recoverable': exceptions.RECOVERABLE, 'not_found': exceptions.NOT_FOUND, 'unauthorized': exceptions.UNAUTHORIZED, }
Change senlin dashboard to not be the default dashboard
Change senlin dashboard to not be the default dashboard Change-Id: I81d492bf8998e74f5bf53b0226047a070069b060 Closes-Bug: #1754183
Python
apache-2.0
stackforge/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard,openstack/senlin-dashboard,openstack/senlin-dashboard,stackforge/senlin-dashboard,openstack/senlin-dashboard
--- +++ @@ -17,7 +17,7 @@ 'senlin_dashboard', 'senlin_dashboard.cluster' ] -DEFAULT = True +DEFAULT = False AUTO_DISCOVER_STATIC_FILES = True ADD_ANGULAR_MODULES = ['horizon.cluster'] ADD_SCSS_FILES = [
82217bab5263984c3507a68c1b94f9d315bafc63
src/masterfile/__init__.py
src/masterfile/__init__.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from ._metadata import version as __version__, author as __author__, email as __email__
# -*- coding: utf-8 -*- from __future__ import absolute_import from ._metadata import version as __version__, author as __author__, email as __email__ __package_version__ = 'masterfile {}'.format(__version__)
Add __package_version__ for version description
Add __package_version__ for version description Example: "masterfile 0.1.0dev"
Python
mit
njvack/masterfile
--- +++ @@ -3,3 +3,5 @@ from __future__ import absolute_import from ._metadata import version as __version__, author as __author__, email as __email__ + +__package_version__ = 'masterfile {}'.format(__version__)
8525465c4f428cc0df02df7eb4fca165a9af6bdc
knowledge_repo/utils/registry.py
knowledge_repo/utils/registry.py
from abc import ABCMeta import logging logger = logging.getLogger(__name__) class SubclassRegisteringABCMeta(ABCMeta): def __init__(cls, name, bases, dct): super(SubclassRegisteringABCMeta, cls).__init__(name, bases, dct) if not hasattr(cls, '_registry'): cls._registry = {} registry_keys = getattr(cls, '_registry_keys', []) if registry_keys: for key in registry_keys: if key in cls._registry and cls.__name__ != cls._registry[key].__name__: logger.info("Ignoring attempt by class `{}` to register key '{}', which is already registered for class `{}`.".format(cls.__name__, key, cls._registry[key].__name__)) else: cls._registry[key] = cls def _get_subclass_for(cls, key): return cls._registry[key]
from abc import ABCMeta import logging logger = logging.getLogger(__name__) class SubclassRegisteringABCMeta(ABCMeta): def __init__(cls, name, bases, dct): super(SubclassRegisteringABCMeta, cls).__init__(name, bases, dct) if not hasattr(cls, '_registry'): cls._registry = {} registry_keys = getattr(cls, '_registry_keys', []) if registry_keys: for key in registry_keys: if key in cls._registry and cls.__name__ != cls._registry[key].__name__: logger.info(f"Ignoring attempt by class `{cls.__name__}` to register key '{key}', " f"which is already registered for class `{cls._registry[key].__name__}`.") else: cls._registry[key] = cls def _get_subclass_for(cls, key): return cls._registry[key]
Update a string with the latest formatting approach
Update a string with the latest formatting approach
Python
apache-2.0
airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo
--- +++ @@ -16,7 +16,8 @@ if registry_keys: for key in registry_keys: if key in cls._registry and cls.__name__ != cls._registry[key].__name__: - logger.info("Ignoring attempt by class `{}` to register key '{}', which is already registered for class `{}`.".format(cls.__name__, key, cls._registry[key].__name__)) + logger.info(f"Ignoring attempt by class `{cls.__name__}` to register key '{key}', " + f"which is already registered for class `{cls._registry[key].__name__}`.") else: cls._registry[key] = cls
b3b216a95c4254302776fdbb67bab948ba12d3d3
ddsc_worker/tasks.py
ddsc_worker/tasks.py
from __future__ import absolute_import from ddsc_worker.celery import celery @celery.task def add(x, y): return x + y @celery.task def mul(x, y): return x + y
from __future__ import absolute_import from ddsc_worker.celery import celery import time @celery.task def add(x, y): time.sleep(10) return x + y @celery.task def mul(x, y): time.sleep(2) return x * y
Add sleep to simulate work
Add sleep to simulate work
Python
mit
ddsc/ddsc-worker
--- +++ @@ -1,12 +1,15 @@ from __future__ import absolute_import from ddsc_worker.celery import celery +import time @celery.task def add(x, y): + time.sleep(10) return x + y @celery.task def mul(x, y): - return x + y + time.sleep(2) + return x * y
ee5cd9196fc273c74fce29e4ac9c3726d3da03b6
deployer/__init__.py
deployer/__init__.py
__version__ = '0.1.6' __author__ = 'sukrit' import logging from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=LOG_ROOT_LEVEL)
__version__ = '0.1.7' __author__ = 'sukrit' import logging from conf.appconfig import LOG_FORMAT, LOG_DATE, LOG_ROOT_LEVEL logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=LOG_ROOT_LEVEL)
Change development version to 0.1.7
Change development version to 0.1.7
Python
mit
totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer
--- +++ @@ -1,4 +1,4 @@ -__version__ = '0.1.6' +__version__ = '0.1.7' __author__ = 'sukrit' import logging
73344151ce39ebc093b7915d6625096ddc2a125d
git_update/__main__.py
git_update/__main__.py
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo @click.command() @click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True) @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') log = logging.getLogger(__name__) if kwargs['debug']: logging.root.setLevel(logging.DEBUG) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = kwargs['dir'] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
#!/usr/bin/env python """Script for updating a directory of repositories.""" import logging import os import click from .actions import update_repo @click.command() @click.option('-d', '--debug', help='Set DEBUG level logging.', is_flag=True) @click.argument('dir', default='.') def main(**kwargs): """Update repositories in a directory. By default, the current working directory list is used for finding valid repositories. """ logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(name)s:%(funcName)s - %(message)s') log = logging.getLogger(__name__) if kwargs['debug']: logging.root.setLevel(logging.DEBUG) main_dir = kwargs['dir'] log.info('Finding directories in %s', main_dir) dir_list = os.listdir(main_dir) log.debug('List of directories: %s', dir_list) # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: dir_list = [kwargs['dir']] for directory in dir_list: update_repo(os.path.join(main_dir, directory)) if __name__ == '__main__': main()
Fix bux when using Git directory
main: Fix bux when using Git directory If a Git directory is passed in, it needs to be in a list of one.
Python
mit
e4r7hbug/git_update
--- +++ @@ -34,7 +34,7 @@ # Git directory was passed in, not a directory of Git directories if '.git' in dir_list: - dir_list = kwargs['dir'] + dir_list = [kwargs['dir']] for directory in dir_list: update_repo(os.path.join(main_dir, directory))
2dc56ab04ea17bea05654eaec12bb27b48b0b225
robotd/cvcapture.py
robotd/cvcapture.py
import threading from robotd.native import _cvcapture class CaptureDevice(object): def __init__(self, path=None): if path is not None: argument_c = _cvcapture.ffi.new( 'char[]', path.encode('utf-8'), ) else: argument_c = _cvcapture.ffi.NULL self.instance = _cvcapture.lib.cvopen(argument_c) self.lock = threading.Lock() def capture(self, width, height): if self.instance is None: raise RuntimeError("capture device is closed") capture_buffer = _cvcapture.ffi.new( 'uint8_t[{}]'.format(width * height), ) with self.lock: status = _cvcapture.lib.cvcapture( self.instance, capture_buffer, width, height, ) if status == 0: raise RuntimeError("cvcapture() failed") return bytes(_cvcapture.ffi.buffer(capture_buffer)) def __enter__(self): return self def __exit__(self, exc_value, exc_type, exc_traceback): self.close() def close(self): if self.instance is not None: with self.lock: _cvcapture.lib.cvclose(self.instance) self.instance = None __del__ = close
import threading from robotd.native import _cvcapture class CaptureDevice(object): def __init__(self, path=None): if path is not None: argument_c = _cvcapture.ffi.new( 'char[]', path.encode('utf-8'), ) else: argument_c = _cvcapture.ffi.NULL self.instance = _cvcapture.lib.cvopen(argument_c) if self.instance == _cvcapture.ffi.NULL: raise RuntimeError("Unable to open capture device") self.lock = threading.Lock() def capture(self, width, height): if self.instance is None: raise RuntimeError("capture device is closed") capture_buffer = _cvcapture.ffi.new( 'uint8_t[{}]'.format(width * height), ) with self.lock: status = _cvcapture.lib.cvcapture( self.instance, capture_buffer, width, height, ) if status == 0: raise RuntimeError("cvcapture() failed") return bytes(_cvcapture.ffi.buffer(capture_buffer)) def __enter__(self): return self def __exit__(self, exc_value, exc_type, exc_traceback): self.close() def close(self): if self.instance is not None: with self.lock: _cvcapture.lib.cvclose(self.instance) self.instance = None __del__ = close
Raise a `RuntimeError` if the device cannot be opened
Raise a `RuntimeError` if the device cannot be opened
Python
mit
sourcebots/robotd,sourcebots/robotd
--- +++ @@ -12,6 +12,8 @@ else: argument_c = _cvcapture.ffi.NULL self.instance = _cvcapture.lib.cvopen(argument_c) + if self.instance == _cvcapture.ffi.NULL: + raise RuntimeError("Unable to open capture device") self.lock = threading.Lock() def capture(self, width, height):
5b88a7068a6b245d99ef5998bbf659480fb85199
cbc/environment.py
cbc/environment.py
import os from .exceptions import IncompleteEnv from tempfile import TemporaryDirectory import time class Environment(object): def __init__(self, *args, **kwargs): self.environ = os.environ.copy() self.config = {} self.cbchome = None if 'CBC_HOME' in kwargs: self.cbchome = kwargs['CBC_HOME'] if 'CBC_HOME' in self.environ: self.cbchome = self.environ['CBC_HOME'] if self.cbchome is None: raise IncompleteEnv('Environment.cbchome is undefined') if not os.path.exists(self.cbchome): os.makedirs(self.cbchome) temp_prefix = os.path.basename(os.path.splitext(__name__)[0]) tempdir = TemporaryDirectory(prefix=temp_prefix, dir=self.cbchome) self.working_dir = tempdir.name self.config['meta'] = self.join('meta.yaml') self.config['build'] = self.join('build.sh') self.config['build_windows'] = self.join('bld.bat') print(self.working_dir) def join(self, path): return os.path.join(self.cbchome, path)
import os from .exceptions import IncompleteEnv from tempfile import TemporaryDirectory import time class Environment(object): def __init__(self, *args, **kwargs): self.environ = os.environ.copy() self.config = {} self.cbchome = None if 'CBC_HOME' in kwargs: self.cbchome = kwargs['CBC_HOME'] # I want the local user environment to override what is # passed to the class. if 'CBC_HOME' in self.environ: self.cbchome = self.environ['CBC_HOME'] if self.cbchome is None: raise IncompleteEnv('Environment.cbchome is undefined') if not os.path.exists(self.cbchome): os.makedirs(self.cbchome) self.config['script'] = {} self.config['script']['meta'] = self.join('meta.yaml') self.config['script']['build_linux'] = self.join('build.sh') self.config['script']['build_windows'] = self.join('bld.bat') def join(self, path): return os.path.join(self.cbchome, path) ''' def local_temp(self): temp_prefix = os.path.basename(os.path.splitext(__name__)[0]) return TemporaryDirectory(prefix=temp_prefix, dir=self.cbchome) '''
Remove temp directory creation... not worth it
Remove temp directory creation... not worth it
Python
bsd-3-clause
jhunkeler/cbc,jhunkeler/cbc,jhunkeler/cbc
--- +++ @@ -12,6 +12,9 @@ if 'CBC_HOME' in kwargs: self.cbchome = kwargs['CBC_HOME'] + + # I want the local user environment to override what is + # passed to the class. if 'CBC_HOME' in self.environ: self.cbchome = self.environ['CBC_HOME'] @@ -21,15 +24,17 @@ if not os.path.exists(self.cbchome): os.makedirs(self.cbchome) - temp_prefix = os.path.basename(os.path.splitext(__name__)[0]) - tempdir = TemporaryDirectory(prefix=temp_prefix, dir=self.cbchome) - self.working_dir = tempdir.name - self.config['meta'] = self.join('meta.yaml') - self.config['build'] = self.join('build.sh') - self.config['build_windows'] = self.join('bld.bat') - print(self.working_dir) + self.config['script'] = {} + self.config['script']['meta'] = self.join('meta.yaml') + self.config['script']['build_linux'] = self.join('build.sh') + self.config['script']['build_windows'] = self.join('bld.bat') def join(self, path): return os.path.join(self.cbchome, path) - + + ''' + def local_temp(self): + temp_prefix = os.path.basename(os.path.splitext(__name__)[0]) + return TemporaryDirectory(prefix=temp_prefix, dir=self.cbchome) + '''
c05ec7f6a869712ec49c2366016b325cf18f7433
tests/test_no_broken_links.py
tests/test_no_broken_links.py
# -*- encoding: utf-8 """ This test checks that all the internal links in the site (links that point to other pages on the site) are pointing at working pages. """ from http_crawler import crawl def test_no_links_are_broken(): responses = [] for rsp in crawl('http://0.0.0.0:5757/', follow_external_links=False): responses.append(rsp) failed_responses = [rsp for rsp in responses if rsp.status_code != 200] failures = [f'{rsp.url} ({rsp.status_code})' for rsp in failed_responses] print('\n'.join(failures)) assert len(failures) == 0
# -*- encoding: utf-8 """ This test checks that all the internal links in the site (links that point to other pages on the site) are pointing at working pages. """ from http_crawler import crawl def test_no_links_are_broken(baseurl): responses = [] for rsp in crawl(baseurl, follow_external_links=False): responses.append(rsp) failed_responses = [rsp for rsp in responses if rsp.status_code != 200] failures = [f'{rsp.url} ({rsp.status_code})' for rsp in failed_responses] print('\n'.join(failures)) assert len(failures) == 0
Use the pytest fixture for the URL
Use the pytest fixture for the URL
Python
mit
alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net
--- +++ @@ -7,9 +7,9 @@ from http_crawler import crawl -def test_no_links_are_broken(): +def test_no_links_are_broken(baseurl): responses = [] - for rsp in crawl('http://0.0.0.0:5757/', follow_external_links=False): + for rsp in crawl(baseurl, follow_external_links=False): responses.append(rsp) failed_responses = [rsp for rsp in responses if rsp.status_code != 200]
c1473e77a9b92c9bdf292017cb2f46bf8695dfd5
afnumpy/lib/shape_base.py
afnumpy/lib/shape_base.py
import afnumpy import arrayfire import numpy from .. import private_utils as pu def tile(A, reps): try: tup = tuple(reps) except TypeError: tup = (reps,) if(len(tup) > 4): raise NotImplementedError('Only up to 4 dimensions are supported') d = len(tup) shape = list(A.shape) n = max(A.size, 1) if (d < A.ndim): tup = (1,)*(A.ndim-d) + tup # Calculate final shape while len(shape) < len(tup): shape.insert(0,1) shape = tuple(numpy.array(shape) * numpy.array(tup)) # Prepend ones to simplify calling if (d < 4): tup = (1,)*(4-d) + tup tup = pu.c2f(tup) s = arrayfire.tile(A.d_array, tup[0], tup[1], tup[2], tup[3]) return afnumpy.ndarray(shape, dtype=pu.typemap(s.type()), af_array=s)
import afnumpy import arrayfire import numpy from IPython.core.debugger import Tracer from .. import private_utils as pu def tile(A, reps): try: tup = tuple(reps) except TypeError: tup = (reps,) if(len(tup) > 4): raise NotImplementedError('Only up to 4 dimensions are supported') d = len(tup) shape = list(A.shape) n = max(A.size, 1) if (d < A.ndim): tup = (1,)*(A.ndim-d) + tup # Calculate final shape while len(shape) < len(tup): shape.insert(0,1) shape = tuple(numpy.array(shape) * numpy.array(tup)) # Prepend ones to simplify calling if (d < 4): tup = (1,)*(4-d) + tup tup = pu.c2f(tup) s = arrayfire.tile(A.d_array, int(tup[0]), int(tup[1]), int(tup[2]), int(tup[3])) return afnumpy.ndarray(shape, dtype=pu.typemap(s.type()), af_array=s)
Make sure to cast to int as this does not work on old numpy versions
Make sure to cast to int as this does not work on old numpy versions
Python
bsd-2-clause
FilipeMaia/afnumpy,daurer/afnumpy
--- +++ @@ -1,6 +1,7 @@ import afnumpy import arrayfire import numpy +from IPython.core.debugger import Tracer from .. import private_utils as pu def tile(A, reps): @@ -26,6 +27,6 @@ if (d < 4): tup = (1,)*(4-d) + tup tup = pu.c2f(tup) - s = arrayfire.tile(A.d_array, tup[0], tup[1], tup[2], tup[3]) + s = arrayfire.tile(A.d_array, int(tup[0]), int(tup[1]), int(tup[2]), int(tup[3])) return afnumpy.ndarray(shape, dtype=pu.typemap(s.type()), af_array=s)
8f188022d3e1ede210cfac2177dd924c9afe8f23
tests/runalldoctests.py
tests/runalldoctests.py
import doctest import glob import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass testfiles = glob.glob('*.txt') for file in testfiles: doctest.testfile(file)
import doctest import getopt import glob import sys import pkg_resources try: pkg_resources.require('OWSLib') except (ImportError, pkg_resources.DistributionNotFound): pass def run(pattern): if pattern is None: testfiles = glob.glob('*.txt') else: testfiles = glob.glob(pattern) for file in testfiles: doctest.testfile(file) if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "t:v") except getopt.GetoptError: print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" sys.exit(2) pattern = None for o, a in opts: if o == '-t': pattern = a run(pattern)
Add option to pick single test file from the runner
Add option to pick single test file from the runner git-svn-id: 150a648d6f30c8fc6b9d405c0558dface314bbdd@620 b426a367-1105-0410-b9ff-cdf4ab011145
Python
bsd-3-clause
kwilcox/OWSLib,bird-house/OWSLib,ocefpaf/OWSLib,b-cube/OWSLib,geographika/OWSLib,jaygoldfinch/OWSLib,tomkralidis/OWSLib,datagovuk/OWSLib,mbertrand/OWSLib,gfusca/OWSLib,KeyproOy/OWSLib,daf/OWSLib,dblodgett-usgs/OWSLib,geopython/OWSLib,jaygoldfinch/OWSLib,daf/OWSLib,kalxas/OWSLib,Jenselme/OWSLib,jachym/OWSLib,QuLogic/OWSLib,datagovuk/OWSLib,menegon/OWSLib,datagovuk/OWSLib,JuergenWeichand/OWSLib,robmcmullen/OWSLib,daf/OWSLib
--- +++ @@ -1,5 +1,8 @@ import doctest +import getopt import glob +import sys + import pkg_resources try: @@ -7,8 +10,23 @@ except (ImportError, pkg_resources.DistributionNotFound): pass -testfiles = glob.glob('*.txt') +def run(pattern): + if pattern is None: + testfiles = glob.glob('*.txt') + else: + testfiles = glob.glob(pattern) + for file in testfiles: + doctest.testfile(file) -for file in testfiles: - doctest.testfile(file) +if __name__ == "__main__": + try: + opts, args = getopt.getopt(sys.argv[1:], "t:v") + except getopt.GetoptError: + print "Usage: python runalldoctests.py [-t GLOB_PATTERN]" + sys.exit(2) + pattern = None + for o, a in opts: + if o == '-t': + pattern = a + run(pattern)
acb10d5bf03be9681b222951c1accb6d419f9b32
inboxen/tests/utils.py
inboxen/tests/utils.py
## # Copyright (C) 2014 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Inboxen is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpRequest from django.contrib.messages.storage.session import SessionStorage class MockRequest(HttpRequest): """Mock up a request object""" def __init__(self, user, session_id=1): super(MockRequest, self).__init__() self.user = user session = SessionMiddleware() self.session = session.SessionStore(session_id) self._messages = SessionStorage(self)
## # Copyright (C) 2014 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Inboxen is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.contrib.sessions.middleware import SessionMiddleware from django.http import HttpRequest from django.contrib.messages.storage.session import SessionStorage class MockRequest(HttpRequest): """Mock up a request object""" def __init__(self, user, session_id="12345678"): super(MockRequest, self).__init__() self.user = user session = SessionMiddleware() self.session = session.SessionStore(session_id) self._messages = SessionStorage(self)
Update MockRequest to work with Django 1.9's session validation
Update MockRequest to work with Django 1.9's session validation touch #124
Python
agpl-3.0
Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen
--- +++ @@ -25,7 +25,7 @@ class MockRequest(HttpRequest): """Mock up a request object""" - def __init__(self, user, session_id=1): + def __init__(self, user, session_id="12345678"): super(MockRequest, self).__init__() self.user = user session = SessionMiddleware()
7b5896700a6c7408d0b25bb4dde4942eaa9032bb
solum/tests/base.py
solum/tests/base.py
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg from solum.openstack.common import test class BaseTestCase(test.BaseTestCase): """Test base class.""" def setUp(self): super(BaseTestCase, self).setUp() self.addCleanup(cfg.CONF.reset)
# -*- coding: utf-8 -*- # # Copyright 2013 - Noorul Islam K M # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg import testscenarios from solum.openstack.common import test class BaseTestCase(testscenarios.WithScenarios, test.BaseTestCase): """Test base class.""" def setUp(self): super(BaseTestCase, self).setUp() self.addCleanup(cfg.CONF.reset)
Support testscenarios by default in BaseTestCase
Support testscenarios by default in BaseTestCase This allows one to use the scenario framework easily from any test class. Change-Id: Ie736138fe2d1e1d38f225547dde54df3f4b21032
Python
apache-2.0
devdattakulkarni/test-solum,gilbertpilz/solum,gilbertpilz/solum,stackforge/solum,openstack/solum,ed-/solum,ed-/solum,gilbertpilz/solum,openstack/solum,stackforge/solum,ed-/solum,ed-/solum,devdattakulkarni/test-solum,gilbertpilz/solum
--- +++ @@ -15,11 +15,12 @@ # under the License. from oslo.config import cfg +import testscenarios from solum.openstack.common import test -class BaseTestCase(test.BaseTestCase): +class BaseTestCase(testscenarios.WithScenarios, test.BaseTestCase): """Test base class.""" def setUp(self):
8c10646768818a56ee89ff857318463da838f813
connect_ffi.py
connect_ffi.py
from cffi import FFI ffi = FFI() #Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h with open("spotify.processed.h") as file: header = file.read() ffi.cdef(header) ffi.cdef(""" void *malloc(size_t size); void exit(int status); """) C = ffi.dlopen(None) lib = ffi.verify(""" #include "spotify.h" """, include_dirs=['./'], library_dirs=['./'], libraries=[str('spotify_embedded_shared')])
import os from cffi import FFI ffi = FFI() library_name = "spotify.processed.h" library_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), libraryName) #Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h with open(library_path) as file: header = file.read() ffi.cdef(header) ffi.cdef(""" void *malloc(size_t size); void exit(int status); """) C = ffi.dlopen(None) lib = ffi.verify(""" #include "spotify.h" """, include_dirs=['./'], library_dirs=['./'], libraries=[str('spotify_embedded_shared')])
Add complete path of spotify.processed.h
Add complete path of spotify.processed.h Add complete path of spotify.processed.h so it points to the same directory where is the file
Python
apache-2.0
chukysoria/spotify-connect-web,chukysoria/spotify-connect-web,chukysoria/spotify-connect-web,chukysoria/spotify-connect-web
--- +++ @@ -1,8 +1,12 @@ +import os from cffi import FFI ffi = FFI() +library_name = "spotify.processed.h" + +library_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), libraryName) #Header generated with cpp spotify.h > spotify.processed.h && sed -i 's/__extension__//g' spotify.processed.h -with open("spotify.processed.h") as file: +with open(library_path) as file: header = file.read() ffi.cdef(header)
ede7158c611bf618ee03989d33c5fe6a091b7d66
tests/testapp/models.py
tests/testapp/models.py
from __future__ import absolute_import import sys from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible import rules @python_2_unicode_compatible class Book(models.Model): isbn = models.CharField(max_length=50, unique=True) title = models.CharField(max_length=100) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title if sys.version_info.major >= 3: from rules.contrib.models import RulesModel class TestModel(RulesModel): class Meta: rules_permissions = {"add": rules.always_true, "view": rules.always_true} @classmethod def preprocess_rules_permissions(cls, perms): perms["custom"] = rules.always_true
from __future__ import absolute_import import sys from django.conf import settings from django.db import models try: from django.utils.encoding import python_2_unicode_compatible except ImportError: def python_2_unicode_compatible(c): return c import rules @python_2_unicode_compatible class Book(models.Model): isbn = models.CharField(max_length=50, unique=True) title = models.CharField(max_length=100) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.title if sys.version_info.major >= 3: from rules.contrib.models import RulesModel class TestModel(RulesModel): class Meta: rules_permissions = {"add": rules.always_true, "view": rules.always_true} @classmethod def preprocess_rules_permissions(cls, perms): perms["custom"] = rules.always_true
Add shim for python_2_unicode_compatible in tests
Add shim for python_2_unicode_compatible in tests
Python
mit
dfunckt/django-rules,dfunckt/django-rules,ticosax/django-rules,ticosax/django-rules,dfunckt/django-rules,ticosax/django-rules
--- +++ @@ -4,7 +4,12 @@ from django.conf import settings from django.db import models -from django.utils.encoding import python_2_unicode_compatible + +try: + from django.utils.encoding import python_2_unicode_compatible +except ImportError: + def python_2_unicode_compatible(c): + return c import rules
0f546ce883bffa52d81ebfdc6eba005d6f2eca22
build.py
build.py
#!/usr/bin/env python import os import subprocess import sys def build(pkgpath): os.chdir(pkgpath) targets = [ 'build', 'package', 'install', 'clean', 'clean-depends', ] for target in targets: p = subprocess.Popen( ['bmake', target], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) out, err = p.communicate() log = 'bmake-' + target + '-log.txt' with open(log, 'w+') as f: f.write(out) f.write(err) assert p.returncode == 0, '%s %s' % (pkg, target) if __name__ == '__main__': home = os.environ['HOME'] localbase = os.path.join(home, 'usr', 'pkgsrc') lines = sys.stdin.readlines() pkgs = [line.rstrip('\n') for line in lines] pkgs = [pkg.split(' ')[0] for pkg in pkgs] for pkg in pkgs: print pkg os.chdir(localbase) assert os.path.exists(os.path.join(localbase, pkg)) build(pkg)
#!/usr/bin/env python import os import subprocess import sys def build(pkgpath): os.chdir(pkgpath) targets = [ 'build', 'package', 'install', 'clean', 'clean-depends', ] for target in targets: p = subprocess.Popen( ['bmake', target], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) out, err = p.communicate() log = 'bmake-' + target + '-log.txt' with open(log, 'w+') as f: f.write(out) f.write(err) assert p.returncode == 0, '%s %s' % (pkg, target) if __name__ == '__main__': home = os.environ['HOME'] localbase = os.path.join(home, 'usr', 'pkgsrc') lines = sys.stdin.readlines() pkgs = [line.rstrip('\n') for line in lines] pkgpaths = [pkg.split(' ')[0] for pkg in pkgs] for pkgpath in pkgpaths: print pkgpath os.chdir(localbase) assert os.path.exists(os.path.join(localbase, pkgpath)) build(pkgpath)
Use more explicit variable names.
Use more explicit variable names.
Python
isc
eliteraspberries/minipkg,eliteraspberries/minipkg
--- +++ @@ -35,9 +35,9 @@ lines = sys.stdin.readlines() pkgs = [line.rstrip('\n') for line in lines] - pkgs = [pkg.split(' ')[0] for pkg in pkgs] - for pkg in pkgs: - print pkg + pkgpaths = [pkg.split(' ')[0] for pkg in pkgs] + for pkgpath in pkgpaths: + print pkgpath os.chdir(localbase) - assert os.path.exists(os.path.join(localbase, pkg)) - build(pkg) + assert os.path.exists(os.path.join(localbase, pkgpath)) + build(pkgpath)
fa85cbfe499599e8a0d667f25acae7fedcc13fb2
invocations/testing.py
invocations/testing.py
from invoke import ctask as task @task(help={ 'module': "Just runs tests/STRING.py.", 'runner': "Use STRING to run tests instead of 'spec'." }) def test(ctx, module=None, runner='spec'): """ Run a Spec or Nose-powered internal test suite. """ # Allow selecting specific submodule specific_module = " --tests=tests/%s.py" % module args = (specific_module if module else "") # Use pty so the spec/nose/Python process buffers "correctly" ctx.run(runner + args, pty=True)
from invoke import ctask as task @task(help={ 'module': "Just runs tests/STRING.py.", 'runner': "Use STRING to run tests instead of 'spec'.", 'opts': "Extra flags for the test runner", }) def test(ctx, module=None, runner='spec', opts=None): """ Run a Spec or Nose-powered internal test suite. """ # Allow selecting specific submodule specific_module = " --tests=tests/%s.py" % module args = (specific_module if module else "") if opts: args += " " + opts # Use pty so the spec/nose/Python process buffers "correctly" ctx.run(runner + args, pty=True)
Add flag passthrough for 'test'
Add flag passthrough for 'test'
Python
bsd-2-clause
singingwolfboy/invocations,pyinvoke/invocations,mrjmad/invocations,alex/invocations
--- +++ @@ -3,14 +3,17 @@ @task(help={ 'module': "Just runs tests/STRING.py.", - 'runner': "Use STRING to run tests instead of 'spec'." + 'runner': "Use STRING to run tests instead of 'spec'.", + 'opts': "Extra flags for the test runner", }) -def test(ctx, module=None, runner='spec'): +def test(ctx, module=None, runner='spec', opts=None): """ Run a Spec or Nose-powered internal test suite. """ # Allow selecting specific submodule specific_module = " --tests=tests/%s.py" % module args = (specific_module if module else "") + if opts: + args += " " + opts # Use pty so the spec/nose/Python process buffers "correctly" ctx.run(runner + args, pty=True)
2fa2a2741a4f8e48d92d476859f73d46dc84a19a
apps/curia_vista/testing/test_council.py
apps/curia_vista/testing/test_council.py
from django.test import TestCase from apps.curia_vista.models import Council class TestCouncil(TestCase): def setUp(self): self.T = Council(id=1, updated='2010-12-26T13:07:49Z', abbreviation='NR', code='RAT_1_', type='N', name='Nationalrat') self.T.save() def test___str__(self): self.assertEqual('Nationalrat', self.T.name) def test_name_translation(self): from django.utils import translation translation.activate('fr') T, created = Council.objects.update_or_create(id=1, updated='2010-12-26T13:07:49Z', code='RAT_1_', type='N', defaults={'abbreviation': 'CN', 'name': 'Conseil national'}) self.assertFalse(created) self.assertEqual('Conseil national', T.name) translation.activate('de') self.assertEqual('Nationalrat', T.name)
from django.test import TestCase from apps.curia_vista.models import Council class TestCouncil(TestCase): def setUp(self): self.T = Council(id=1, updated='2010-12-26T13:07:49Z', abbreviation='NR', code='RAT_1_', type='N', name='Nationalrat') self.T.save() def test___str__(self): self.assertEqual('Nationalrat', str(self.T)) def test_name_translation(self): from django.utils import translation translation.activate('fr') T, created = Council.objects.update_or_create(id=1, updated='2010-12-26T13:07:49Z', code='RAT_1_', type='N', defaults={'abbreviation': 'CN', 'name': 'Conseil national'}) self.assertFalse(created) self.assertEqual('Conseil national', T.name) translation.activate('de') self.assertEqual('Nationalrat', T.name)
Make the testing coverage great again
Make the testing coverage great again
Python
agpl-3.0
rettichschnidi/politkarma,rettichschnidi/politkarma,rettichschnidi/politkarma,rettichschnidi/politkarma
--- +++ @@ -10,7 +10,7 @@ self.T.save() def test___str__(self): - self.assertEqual('Nationalrat', self.T.name) + self.assertEqual('Nationalrat', str(self.T)) def test_name_translation(self): from django.utils import translation
7f711f7da0003cf6f0335f33fb358e91d4e91cf7
simpleadmindoc/management/commands/docgenapp.py
simpleadmindoc/management/commands/docgenapp.py
from django.core.management.base import AppCommand class Command(AppCommand): help = "Generate sphinx documentation skeleton for given apps." def handle_app(self, app, **options): # check if simpleadmindoc directory is setup from django.db import models from simpleadmindoc.generate import generate_model_doc, generate_app_doc, generate_index_doc generate_index_doc() generate_app_doc(app) for model in models.get_models(app): generate_model_doc(model)
from optparse import make_option from django.core.management.base import AppCommand class Command(AppCommand): help = "Generate sphinx documentation skeleton for given apps." option_list = AppCommand.option_list + ( make_option('--locale', '-l', default=None, dest='locale', help='Use given locale'), ) def handle_app(self, app, **options): # check if simpleadmindoc directory is setup locale = options.get('locale', None) if locale: from django.utils import translation translation.activate(locale) from django.db import models from simpleadmindoc.generate import generate_model_doc, generate_app_doc, generate_index_doc generate_index_doc() generate_app_doc(app) for model in models.get_models(app): generate_model_doc(model)
Add option to set locale for created documentation
Add option to set locale for created documentation
Python
bsd-3-clause
bmihelac/django-simpleadmindoc,bmihelac/django-simpleadmindoc
--- +++ @@ -1,11 +1,22 @@ +from optparse import make_option + from django.core.management.base import AppCommand class Command(AppCommand): help = "Generate sphinx documentation skeleton for given apps." + option_list = AppCommand.option_list + ( + make_option('--locale', '-l', default=None, dest='locale', + help='Use given locale'), + ) def handle_app(self, app, **options): # check if simpleadmindoc directory is setup + locale = options.get('locale', None) + if locale: + from django.utils import translation + translation.activate(locale) + from django.db import models from simpleadmindoc.generate import generate_model_doc, generate_app_doc, generate_index_doc generate_index_doc()
e858be9072b175545e17631ccd838f9f7d8a7e21
tensorflow_datasets/dataset_collections/longt5/longt5.py
tensorflow_datasets/dataset_collections/longt5/longt5.py
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Long T5 dataset collection.""" import collections from typing import Mapping from tensorflow_datasets.core import dataset_collection_builder from tensorflow_datasets.core import naming class Longt5(dataset_collection_builder.DatasetCollection): """Long T5 dataset collection.""" @property def info(self) -> dataset_collection_builder.DatasetCollectionInfo: return dataset_collection_builder.DatasetCollectionInfo.from_cls( dataset_collection_class=self.__class__, release_notes={ "1.0.0": "Initial release", }, ) @property def datasets(self,) -> Mapping[str, Mapping[str, naming.DatasetReference]]: return collections.OrderedDict({ "1.0.0": naming.references_for({ "natural_questions": "natural_questions/longt5:0.1.0", "media_sum": "media_sum:1.0.0", }) })
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Long T5 dataset collection.""" import collections from typing import Mapping from tensorflow_datasets.core import dataset_collection_builder from tensorflow_datasets.core import naming class Longt5(dataset_collection_builder.DatasetCollection): """Long T5 dataset collection.""" @property def info(self) -> dataset_collection_builder.DatasetCollectionInfo: return dataset_collection_builder.DatasetCollectionInfo.from_cls( dataset_collection_class=self.__class__, release_notes={ "1.0.0": "Initial release", }, homepage="https://github.com/google-research/longt5", ) @property def datasets(self,) -> Mapping[str, Mapping[str, naming.DatasetReference]]: return collections.OrderedDict({ "1.0.0": naming.references_for({ "natural_questions": "natural_questions/longt5:0.1.0", "media_sum": "media_sum:1.0.0", }) })
Add homepage to LongT5 dataset collection
Add homepage to LongT5 dataset collection PiperOrigin-RevId: 479013251
Python
apache-2.0
tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets
--- +++ @@ -32,6 +32,7 @@ release_notes={ "1.0.0": "Initial release", }, + homepage="https://github.com/google-research/longt5", ) @property
af10508437be2001e9e12a369c4e8a973fd50ee8
astral/api/handlers/node.py
astral/api/handlers/node.py
from astral.api.handlers.base import BaseHandler from astral.models.node import Node from astral.api.client import NodesAPI import sys import logging log = logging.getLogger(__name__) class NodeHandler(BaseHandler): def delete(self, node_uuid=None): """Remove the requesting node from the list of known nodes, unregistering the from the network. """ if node_uuid: node = Node.get_by(uuid=node_uuid) else: node = Node.me() temp = node node.delete() if node_uuid: node = Node.get_by(uuid=node_uuid) else: node = Node.me() node.delete() closest_supernode = Node.closest_supernode() if closest_supernode: log.info("Notifying closest supernode %s that %s was deleted", closest_supernode, node) NodesAPI(closest_supernode.absolute_url()).unregister(node) sys.exit() if temp == Node.me(): # TODO kind of a shortcut to shutting down, but should be a bit more # formal GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) """shut = Daemon() shut.stop() raise KeyboardInterrupt""" if node == Node.me(): # TODO kind of a shortcut to shutting down, but should be a bit more # formal raise KeyboardInterrupt
from astral.api.handlers.base import BaseHandler from astral.models.node import Node from astral.api.client import NodesAPI import logging log = logging.getLogger(__name__) class NodeHandler(BaseHandler): def delete(self, node_uuid=None): """Remove the requesting node from the list of known nodes, unregistering the from the network. """ if not node_uuid: log.info("Shutting down because of request from %s", self.request.remote_ip) self.stop() return node = Node.get_by(uuid=node_uuid) closest_supernode = Node.closest_supernode() if closest_supernode: log.info("Notifying closest supernode %s that %s was deleted", closest_supernode, node) NodesAPI(closest_supernode.absolute_url()).unregister(node) node.delete()
Clean up Node delete handler.
Clean up Node delete handler.
Python
mit
peplin/astral
--- +++ @@ -1,8 +1,6 @@ from astral.api.handlers.base import BaseHandler from astral.models.node import Node from astral.api.client import NodesAPI -import sys - import logging log = logging.getLogger(__name__) @@ -14,36 +12,16 @@ unregistering the from the network. """ - if node_uuid: - node = Node.get_by(uuid=node_uuid) - else: - node = Node.me() - temp = node - node.delete() + if not node_uuid: + log.info("Shutting down because of request from %s", + self.request.remote_ip) + self.stop() + return - if node_uuid: - node = Node.get_by(uuid=node_uuid) - else: - node = Node.me() - node.delete() - + node = Node.get_by(uuid=node_uuid) closest_supernode = Node.closest_supernode() if closest_supernode: log.info("Notifying closest supernode %s that %s was deleted", closest_supernode, node) NodesAPI(closest_supernode.absolute_url()).unregister(node) - - sys.exit() - - if temp == Node.me(): - # TODO kind of a shortcut to shutting down, but should be a bit more - # formal - GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0) - """shut = Daemon() - shut.stop() - raise KeyboardInterrupt""" - - if node == Node.me(): - # TODO kind of a shortcut to shutting down, but should be a bit more - # formal - raise KeyboardInterrupt + node.delete()
75536b58ab934b3870236f2124dfb505e0a9299f
dvox/models/types.py
dvox/models/types.py
from bloop import String class Position(String): """ stores [2, 3, 4] as '2:3:4' """ def dynamo_load(self, value): values = value.split(":") return list(map(int, values)) def dynamo_dump(self, value): return ":".join(map(str, value))
from bloop import String class Position(String): """ stores [2, 3, 4] as '2:3:4' """ def dynamo_load(self, value): values = value.split(":") return list(map(int, values)) def dynamo_dump(self, value): return ":".join(map(str, value)) class StringEnum(String): """Store an enum by the names of its values""" def __init__(self, enum): self.enum = enum super().__init__() def dynamo_load(self, value): value = super().dynamo_load(value) return self.enum[value] def dynamo_dump(self, value): value = value.name return super().dynamo_dump(value)
Add type for storing enums
Add type for storing enums
Python
mit
numberoverzero/dvox
--- +++ @@ -9,3 +9,18 @@ def dynamo_dump(self, value): return ":".join(map(str, value)) + + +class StringEnum(String): + """Store an enum by the names of its values""" + def __init__(self, enum): + self.enum = enum + super().__init__() + + def dynamo_load(self, value): + value = super().dynamo_load(value) + return self.enum[value] + + def dynamo_dump(self, value): + value = value.name + return super().dynamo_dump(value)
46259730666b967675336e7bda5014b17419614d
test/parse_dive.py
test/parse_dive.py
#! /usr/bin/python import argparse from xml.dom import minidom parser = argparse.ArgumentParser(description='Parse a dive in xml formt.') parser.add_argument('-f', '--file', required=True, dest='path', help='path to xml file') args = parser.parse_args() path = args.path doc = minidom.parse(path) nodes = doc.getElementsByTagName('Dive.Sample') for node in nodes: if node.hasChildNodes() and len(node.childNodes) > 8: for subNode in node.childNodes: if (subNode.nodeName == "Depth" and subNode.hasChildNodes()): depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1 if (subNode.nodeName == "Time" and subNode.hasChildNodes()): time = float(subNode.childNodes[0].nodeValue) / 60 print ("%.2f %.2f" % (time , depth))
#! /usr/bin/python import argparse from xml.dom import minidom O2=21 H2=0 parser = argparse.ArgumentParser(description='Parse a dive in xml formt.') parser.add_argument('-f', '--file', required=True, dest='path', help='path to xml file') args = parser.parse_args() path = args.path doc = minidom.parse(path) gas = doc.getElementsByTagName('DiveMixture') for subNode in gas.item(0).childNodes: if (subNode.nodeName == "Oxygen"): O2=float(subNode.childNodes[0].nodeValue) if (subNode.nodeName == "Helium"): H2=float(subNode.childNodes[0].nodeValue) nodes = doc.getElementsByTagName('Dive.Sample') for node in nodes: if node.hasChildNodes() and len(node.childNodes) > 8: for subNode in node.childNodes: if (subNode.nodeName == "Depth" and subNode.hasChildNodes()): depth = (float(subNode.childNodes[0].nodeValue) / 10) + 1 if (subNode.nodeName == "Time" and subNode.hasChildNodes()): time = float(subNode.childNodes[0].nodeValue) / 60 print ("%.2f %.2f %.2f %.2f" % (time , depth, O2, H2))
Change the xml parser to output gas mixture content
Change the xml parser to output gas mixture content
Python
isc
AquaBSD/libbuhlmann,AquaBSD/libbuhlmann,AquaBSD/libbuhlmann
--- +++ @@ -1,6 +1,9 @@ #! /usr/bin/python import argparse from xml.dom import minidom + +O2=21 +H2=0 parser = argparse.ArgumentParser(description='Parse a dive in xml formt.') parser.add_argument('-f', '--file', required=True, @@ -9,6 +12,16 @@ args = parser.parse_args() path = args.path doc = minidom.parse(path) + +gas = doc.getElementsByTagName('DiveMixture') + + +for subNode in gas.item(0).childNodes: + if (subNode.nodeName == "Oxygen"): + O2=float(subNode.childNodes[0].nodeValue) + if (subNode.nodeName == "Helium"): + H2=float(subNode.childNodes[0].nodeValue) + nodes = doc.getElementsByTagName('Dive.Sample') for node in nodes: @@ -19,4 +32,4 @@ if (subNode.nodeName == "Time" and subNode.hasChildNodes()): time = float(subNode.childNodes[0].nodeValue) / 60 - print ("%.2f %.2f" % (time , depth)) + print ("%.2f %.2f %.2f %.2f" % (time , depth, O2, H2))
091b543fd8668d6f53bf126492aaaf47251d0672
src/ggrc_basic_permissions/roles/ProgramEditor.py
src/ggrc_basic_permissions/roles/ProgramEditor.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> scope = "Private Program" description = """ A user with authorization to edit mapping objects related to an access controlled program.<br/><br/>When a person has this role they can map and unmap objects to the Program and edit the Program info, but they are unable to delete the Program or assign other people roles for that program. """ permissions = { "read": [ "ObjectDocument", "ObjectObjective", "ObjectPerson", "Program", "Relationship", "UserRole", "Context", ], "create": [ "Audit", "ObjectDocument", "ObjectObjective", "ObjectPerson", "Relationship", ], "view_object_page": [ "__GGRC_ALL__" ], "update": [ "ObjectDocument", "ObjectObjective", "ObjectPerson", "Program", "Relationship" ], "delete": [ "Program", "ObjectDocument", "ObjectObjective", "ObjectPerson", "Relationship", ] }
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> scope = "Private Program" description = """ A user with authorization to edit mapping objects related to an access controlled program.<br/><br/>When a person has this role they can map and unmap objects to the Program and edit the Program info, but they are unable to delete the Program or assign other people roles for that program. """ permissions = { "read": [ "ObjectDocument", "ObjectObjective", "ObjectPerson", "Program", "Relationship", "UserRole", "Context", ], "create": [ "Audit", "Snapshot", "ObjectDocument", "ObjectObjective", "ObjectPerson", "Relationship", ], "view_object_page": [ "__GGRC_ALL__" ], "update": [ "Snapshot", "ObjectDocument", "ObjectObjective", "ObjectPerson", "Program", "Relationship" ], "delete": [ "Program", "ObjectDocument", "ObjectObjective", "ObjectPerson", "Relationship", ] }
Add support for program editor to create and update snapshots
Add support for program editor to create and update snapshots
Python
apache-2.0
selahssea/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core
--- +++ @@ -20,6 +20,7 @@ ], "create": [ "Audit", + "Snapshot", "ObjectDocument", "ObjectObjective", "ObjectPerson", @@ -29,6 +30,7 @@ "__GGRC_ALL__" ], "update": [ + "Snapshot", "ObjectDocument", "ObjectObjective", "ObjectPerson",
6876b6584cd90cca60fc21a53967dc1dfee6f2b4
testing/models/test_epic.py
testing/models/test_epic.py
import pytest from k2catalogue import models @pytest.fixture def epic(): return models.EPIC(epic_id=12345, ra=12.345, dec=67.894, mag=None, campaign_id=1) def test_repr(epic): assert repr(epic) == '<EPIC: 12345>'
import pytest try: from unittest import mock except ImportError: import mock from k2catalogue import models @pytest.fixture def epic(): return models.EPIC(epic_id=12345, ra=12.345, dec=67.894, mag=None, campaign_id=1) def test_repr(epic): assert repr(epic) == '<EPIC: 12345>' @mock.patch('k2catalogue.models.Simbad') def test_simbad_query(Simbad, epic): epic.simbad_query(radius=2.) Simbad.return_value.open.assert_called_once_with(radius=2.)
Add test for simbad query
Add test for simbad query
Python
mit
mindriot101/k2catalogue
--- +++ @@ -1,4 +1,8 @@ import pytest +try: + from unittest import mock +except ImportError: + import mock from k2catalogue import models @@ -12,3 +16,8 @@ def test_repr(epic): assert repr(epic) == '<EPIC: 12345>' + +@mock.patch('k2catalogue.models.Simbad') +def test_simbad_query(Simbad, epic): + epic.simbad_query(radius=2.) + Simbad.return_value.open.assert_called_once_with(radius=2.)
94eecbd714e82ce179ca9985f9dd89dc72995070
seleniumbase/fixtures/page_utils.py
seleniumbase/fixtures/page_utils.py
""" This module contains useful utility methods. """ def jq_format(code): """ Use before throwing raw code such as 'div[tab="advanced"]' into jQuery. Selectors with quotes inside of quotes would otherwise break jQuery. This is similar to "json.dumps(value)", but with one less layer of quotes. """ code = code.replace('\\', '\\\\').replace('\t', '\\t').replace('\n', '\\n') code = code.replace('\"', '\\\"').replace('\'', '\\\'') code = code.replace('\v', '\\v').replace('\a', '\\a').replace('\f', '\\f') code = code.replace('\b', '\\b').replace('\u', '\\u').replace('\r', '\\r') return code
""" This module contains useful utility methods. """ def jq_format(code): """ Use before throwing raw code such as 'div[tab="advanced"]' into jQuery. Selectors with quotes inside of quotes would otherwise break jQuery. This is similar to "json.dumps(value)", but with one less layer of quotes. """ code = code.replace('\\', '\\\\').replace('\t', '\\t').replace('\n', '\\n') code = code.replace('\"', '\\\"').replace('\'', '\\\'') code = code.replace('\v', '\\v').replace('\a', '\\a').replace('\f', '\\f') code = code.replace('\b', '\\b').replace('\u', '\\u').replace('\r', '\\r') return code def get_domain_url(url): url_header = url.split('://')[0] simple_url = url.split('://')[1] base_url = simple_url.split('/')[0] domain_url = url_header + '://' + base_url return domain_url
Add a method to extract the domain url from a full url
Add a method to extract the domain url from a full url
Python
mit
ktp420/SeleniumBase,mdmintz/SeleniumBase,possoumous/Watchers,seleniumbase/SeleniumBase,mdmintz/seleniumspot,possoumous/Watchers,mdmintz/SeleniumBase,possoumous/Watchers,ktp420/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,ktp420/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,possoumous/Watchers
--- +++ @@ -14,3 +14,11 @@ code = code.replace('\v', '\\v').replace('\a', '\\a').replace('\f', '\\f') code = code.replace('\b', '\\b').replace('\u', '\\u').replace('\r', '\\r') return code + + +def get_domain_url(url): + url_header = url.split('://')[0] + simple_url = url.split('://')[1] + base_url = simple_url.split('/')[0] + domain_url = url_header + '://' + base_url + return domain_url
3492ae03c9cfc8322ba60522779c7c0eeb642dd3
server/models/event_subscription.py
server/models/event_subscription.py
"""This module contains the SQLAlchemy EventSubscription class definition.""" from server.models.db import db class EventSubscription(db.Model): """SQLAlchemy EventSubscription class definition.""" __tablename__ = 'event_subscriptions' user_id = db.Column( 'user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True) event_id = db.Column( 'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True) event = db.relationship('Event', backref=db.backref('event_subscriptions')) user = db.relationship('User', backref=db.backref('event_subscriptions')) def __init__(self, event_id=None, user_id=None): """Constructor for EventSubscription class.""" self.event_id = event_id self.user_id = user_id
"""This module contains the SQLAlchemy EventSubscription class definition.""" from server.models.db import db class EventSubscription(db.Model): """SQLAlchemy EventSubscription class definition.""" __tablename__ = 'event_subscriptions' user_id = db.Column( 'user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True) event_id = db.Column( 'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True) def __init__(self, event_id=None, user_id=None): """Constructor for EventSubscription class.""" self.event_id = event_id self.user_id = user_id
Fix issue with deleting event subscriptions
Fix issue with deleting event subscriptions
Python
mit
bnotified/api,bnotified/api
--- +++ @@ -12,10 +12,6 @@ event_id = db.Column( 'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True) - event = db.relationship('Event', backref=db.backref('event_subscriptions')) - - user = db.relationship('User', backref=db.backref('event_subscriptions')) - def __init__(self, event_id=None, user_id=None): """Constructor for EventSubscription class.""" self.event_id = event_id
7ad80225cd593689b33c59db0b8eb3e9cfd6e763
tests/noreferences_tests.py
tests/noreferences_tests.py
"""Test noreferences bot module.""" # # (C) Pywikibot team, 2018-2020 # # Distributed under the terms of the MIT license. # import pywikibot from scripts.noreferences import NoReferencesBot from tests.aspects import TestCase, unittest class TestAddingReferences(TestCase): """Test adding references to section.""" family = 'wikipedia' code = 'cs' def test_add(self): """Test adding references section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot(None) bot.site = self.site page.text = '\n== Reference ==\n* [http://www.baz.org Baz]' new_text = bot.addReferences(page.text) expected = ('\n== Reference ==\n<references />' '\n\n* [http://www.baz.org Baz]') self.assertEqual(new_text, expected) def test_add_under_templates(self): """Test adding references section under templates in section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot(None) bot.site = self.site page.text = '\n== Reference ==\n{{Překlad|en|Baz|123456}}' new_text = bot.addReferences(page.text) expected = page.text + '\n<references />\n' self.assertEqual(new_text, expected) if __name__ == '__main__': # pragma: no cover unittest.main()
"""Test noreferences bot module.""" # # (C) Pywikibot team, 2018-2021 # # Distributed under the terms of the MIT license. # import pywikibot from scripts.noreferences import NoReferencesBot from tests.aspects import TestCase, unittest class TestAddingReferences(TestCase): """Test adding references to section.""" family = 'wikipedia' code = 'cs' def test_add(self): """Test adding references section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot() bot.site = self.site page.text = '\n== Reference ==\n* [http://www.baz.org Baz]' new_text = bot.addReferences(page.text) expected = ('\n== Reference ==\n<references />' '\n\n* [http://www.baz.org Baz]') self.assertEqual(new_text, expected) def test_add_under_templates(self): """Test adding references section under templates in section.""" page = pywikibot.Page(self.site, 'foo') bot = NoReferencesBot() bot.site = self.site page.text = '\n== Reference ==\n{{Překlad|en|Baz|123456}}' new_text = bot.addReferences(page.text) expected = page.text + '\n<references />\n' self.assertEqual(new_text, expected) if __name__ == '__main__': # pragma: no cover unittest.main()
Remove deprecated "gen" parameter of NoReferencesBot
[tests] Remove deprecated "gen" parameter of NoReferencesBot Change-Id: I8140117cfc2278cfec751164a6d1d8f12bcaef84
Python
mit
wikimedia/pywikibot-core,wikimedia/pywikibot-core
--- +++ @@ -1,6 +1,6 @@ """Test noreferences bot module.""" # -# (C) Pywikibot team, 2018-2020 +# (C) Pywikibot team, 2018-2021 # # Distributed under the terms of the MIT license. # @@ -20,7 +20,7 @@ def test_add(self): """Test adding references section.""" page = pywikibot.Page(self.site, 'foo') - bot = NoReferencesBot(None) + bot = NoReferencesBot() bot.site = self.site page.text = '\n== Reference ==\n* [http://www.baz.org Baz]' new_text = bot.addReferences(page.text) @@ -31,7 +31,7 @@ def test_add_under_templates(self): """Test adding references section under templates in section.""" page = pywikibot.Page(self.site, 'foo') - bot = NoReferencesBot(None) + bot = NoReferencesBot() bot.site = self.site page.text = '\n== Reference ==\n{{Překlad|en|Baz|123456}}' new_text = bot.addReferences(page.text)
f14b1aa56b838469f63cec22c87e2e8c0c3f17c6
csp.py
csp.py
csp = { 'default-src': '\'self\'', 'style-src': [ '\'self\'', '\'unsafe-inline\'' ], 'script-src': [ '\'self\'', 'cdn.httparchive.org', 'www.google-analytics.com', 'use.fontawesome.com', 'cdn.speedcurve.com', 'spdcrv.global.ssl.fastly.net', 'lux.speedcurve.com' ], 'font-src': [ '\'self\'' ], 'connect-src': [ '\'self\'', 'cdn.httparchive.org', 'discuss.httparchive.org', 'dev.to', 'cdn.rawgit.com', 'www.webpagetest.org', 'www.google-analytics.com', 'stats.g.doubleclick.net' ], 'img-src': [ '\'self\'', 'lux.speedcurve.com', 'almanac.httparchive.org', 'discuss.httparchive.org', 'avatars.discourse.org', 'www.google-analytics.com', 'www.google.com', 's.g.doubleclick.net', 'stats.g.doubleclick.net', 'sjc3.discourse-cdn.com', 'res.cloudinary.com' ] }
csp = { 'default-src': '\'self\'', 'style-src': [ '\'self\'', '\'unsafe-inline\'' ], 'script-src': [ '\'self\'', 'cdn.httparchive.org', 'www.google-analytics.com', 'use.fontawesome.com', 'cdn.speedcurve.com', 'spdcrv.global.ssl.fastly.net', 'lux.speedcurve.com' ], 'font-src': [ '\'self\'' ], 'connect-src': [ '\'self\'', 'cdn.httparchive.org', 'discuss.httparchive.org', 'dev.to', 'cdn.rawgit.com', 'www.webpagetest.org', 'www.google-analytics.com', 'stats.g.doubleclick.net' ], 'img-src': [ '\'self\'', 'lux.speedcurve.com', 'almanac.httparchive.org', 'discuss.httparchive.org', 'avatars.discourse.org', 'www.google-analytics.com', 'www.google.com', 's.g.doubleclick.net', 'stats.g.doubleclick.net', '*.discourse-cdn.com', 'res.cloudinary.com' ] }
Allow more discourse hostnames to fix CSP error
Allow more discourse hostnames to fix CSP error
Python
apache-2.0
HTTPArchive/beta.httparchive.org,HTTPArchive/beta.httparchive.org,HTTPArchive/beta.httparchive.org
--- +++ @@ -36,7 +36,7 @@ 'www.google.com', 's.g.doubleclick.net', 'stats.g.doubleclick.net', - 'sjc3.discourse-cdn.com', + '*.discourse-cdn.com', 'res.cloudinary.com' ] }
a1d8a81bbd25404b1109688bded9bea923ba6771
formly/tests/urls.py
formly/tests/urls.py
from django.conf.urls import include, url urlpatterns = [ url(r"^", include("formly.urls", namespace="formly")), ]
from django.conf.urls import include, url from django.views.generic import TemplateView urlpatterns = [ url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"), url(r"^", include("formly.urls", namespace="formly")), ]
Add "home" url for testing
Add "home" url for testing
Python
bsd-3-clause
eldarion/formly,eldarion/formly
--- +++ @@ -1,5 +1,7 @@ from django.conf.urls import include, url +from django.views.generic import TemplateView urlpatterns = [ + url(r"^home/", TemplateView.as_view(template_name="no-ie.html"), name="home"), url(r"^", include("formly.urls", namespace="formly")), ]
765864250faba841a2ee8f2fa669f57a25661737
testapp/testapp/urls.py
testapp/testapp/urls.py
"""testapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.views.static import serve from django_afip import views urlpatterns = [ url(r'^admin/', admin.site.urls), url( r'^invoices/pdf/(?P<pk>\d+)$', views.ReceiptPDFView.as_view(), name='receipt_pdf_view', ), url( r'^invoices/html/(?P<pk>\d+)$', views.ReceiptHTMLView.as_view(), name='receipt_html_view', ), url( r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}, ), ]
"""testapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.views.static import serve from django_afip import views urlpatterns = [ url(r'^admin/', admin.site.urls), url( r'^invoices/pdfdisplay/(?P<pk>\d+)$', views.ReceiptPDFDisplayView.as_view(), name='receipt_pdf_view', ), url( r'^invoices/pdf/(?P<pk>\d+)$', views.ReceiptPDFView.as_view(), name='receipt_pdf_view', ), url( r'^invoices/html/(?P<pk>\d+)$', views.ReceiptHTMLView.as_view(), name='receipt_html_view', ), url( r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}, ), ]
Add PDFDisplay view to the test app
Add PDFDisplay view to the test app
Python
isc
hobarrera/django-afip,hobarrera/django-afip
--- +++ @@ -23,6 +23,11 @@ urlpatterns = [ url(r'^admin/', admin.site.urls), url( + r'^invoices/pdfdisplay/(?P<pk>\d+)$', + views.ReceiptPDFDisplayView.as_view(), + name='receipt_pdf_view', + ), + url( r'^invoices/pdf/(?P<pk>\d+)$', views.ReceiptPDFView.as_view(), name='receipt_pdf_view',
e3d3893bf4cb8aa782efb05771339a0d59451fe9
xbrowse_server/base/management/commands/list_projects.py
xbrowse_server/base/management/commands/list_projects.py
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): """Command to generate a ped file for a given project""" def handle(self, *args, **options): projects = Project.objects.all() for project in projects: individuals = project.get_individuals() print("%3d families %3d individuals project id: %s" % ( len({i.get_family_id() for i in individuals} - {None,}), len(individuals), project.project_id))
from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project class Command(BaseCommand): """Command to print out basic stats on some or all projects. Optionally takes a list of project_ids. """ def handle(self, *args, **options): if args: projects = [Project.objects.get(project_id=arg) for arg in args] else: projects = Project.objects.all() for project in projects: individuals = project.get_individuals() print("%3d families: %s, %3d individuals, project id: %s. VCF files: %s \n %s" % ( len({i.get_family_id() for i in individuals} - {None,}), project.family_set.all(), len(individuals), project.project_id, project.get_all_vcf_files(), project.families_by_vcf().items() ))
Print additional stats for each projects
Print additional stats for each projects
Python
agpl-3.0
ssadedin/seqr,macarthur-lab/seqr,macarthur-lab/seqr,ssadedin/seqr,ssadedin/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse,macarthur-lab/xbrowse,ssadedin/seqr,ssadedin/seqr,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/seqr,macarthur-lab/xbrowse,macarthur-lab/xbrowse
--- +++ @@ -3,14 +3,22 @@ from xbrowse_server.base.models import Project class Command(BaseCommand): - """Command to generate a ped file for a given project""" + """Command to print out basic stats on some or all projects. Optionally takes a list of project_ids. """ def handle(self, *args, **options): - projects = Project.objects.all() + if args: + projects = [Project.objects.get(project_id=arg) for arg in args] + else: + projects = Project.objects.all() + for project in projects: individuals = project.get_individuals() - print("%3d families %3d individuals project id: %s" % ( + print("%3d families: %s, %3d individuals, project id: %s. VCF files: %s \n %s" % ( len({i.get_family_id() for i in individuals} - {None,}), + project.family_set.all(), len(individuals), - project.project_id)) + project.project_id, + project.get_all_vcf_files(), + project.families_by_vcf().items() + ))
870600482bd7d2b77542c169f78f125c17cec677
editorsnotes/api/serializers/activity.py
editorsnotes/api/serializers/activity.py
from rest_framework import serializers from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE, DELETION) VERSION_ACTIONS = { ADDITION: 'added', CHANGE: 'changed', DELETION: 'deleted' } # TODO: make these fields nested, maybe class ActivitySerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') project = serializers.ReadOnlyField(source='project.slug') type = serializers.ReadOnlyField(source='content_type.model') url = serializers.SerializerMethodField('get_object_url') title = serializers.ReadOnlyField(source='display_title') action = serializers.SerializerMethodField('get_action_repr') class Meta: model = LogActivity fields = ('user', 'project', 'time', 'type', 'url', 'title', 'action',) def get_object_url(self, obj): return None if obj.action == DELETION else obj.content_object.get_absolute_url() def get_action_repr(self, version_obj): return VERSION_ACTIONS[version_obj.action]
from rest_framework import serializers from editorsnotes.main.models.auth import (LogActivity, ADDITION, CHANGE, DELETION) VERSION_ACTIONS = { ADDITION: 'added', CHANGE: 'changed', DELETION: 'deleted' } # TODO: make these fields nested, maybe class ActivitySerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.username') project = serializers.ReadOnlyField(source='project.slug') type = serializers.ReadOnlyField(source='content_type.model') url = serializers.SerializerMethodField('get_object_url') title = serializers.ReadOnlyField(source='display_title') action = serializers.SerializerMethodField('get_action_repr') class Meta: model = LogActivity fields = ('user', 'project', 'time', 'type', 'url', 'title', 'action',) def get_object_url(self, obj): if obj.action == DELETION or obj.content_object is None: return None else: return obj.content_object.get_absolute_url() def get_action_repr(self, version_obj): return VERSION_ACTIONS[version_obj.action]
Fix bug in action serializer
Fix bug in action serializer Don't try to get URL of items that have been deleted
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
--- +++ @@ -21,6 +21,9 @@ model = LogActivity fields = ('user', 'project', 'time', 'type', 'url', 'title', 'action',) def get_object_url(self, obj): - return None if obj.action == DELETION else obj.content_object.get_absolute_url() + if obj.action == DELETION or obj.content_object is None: + return None + else: + return obj.content_object.get_absolute_url() def get_action_repr(self, version_obj): return VERSION_ACTIONS[version_obj.action]
d5820bef80ea4bdb871380dbfe41db12290fc5f8
functest/opnfv_tests/features/odl_sfc.py
functest/opnfv_tests/features/odl_sfc.py
#!/usr/bin/python # # Copyright (c) 2016 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # import functest.core.feature_base as base class OpenDaylightSFC(base.FeatureBase): def __init__(self): super(OpenDaylightSFC, self).__init__(project='sfc', case='functest-odl-sfc', repo='dir_repo_sfc') dir_sfc_functest = '{}/sfc/tests/functest'.format(self.repo) self.cmd = 'cd %s && python ./run_tests.py' % dir_sfc_functest
#!/usr/bin/python # # Copyright (c) 2016 All rights reserved # This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # import functest.core.feature_base as base from sfc.tests.functest import run_tests class OpenDaylightSFC(base.FeatureBase): def __init__(self): super(OpenDaylightSFC, self).__init__(project='sfc', case='functest-odl-sfc', repo='dir_repo_sfc') def execute(self): return run_tests.main()
Make SFC test a python call to main()
Make SFC test a python call to main() Instead of python -> bash -> python, call the SFC test using the execute() method that is inherited from FeatureBase and it's a bash call by default. With this change, we call the SFC test using main() of run_tests.py of SFC repo and will have real time output. Change-Id: I6d59821e603c88697a82b95c5626c5b703c11026 Signed-off-by: jose.lausuch <a4ed9890ad7f6494ac84a749f29a4dc3449a1186@ericsson.com> Signed-off-by: George Paraskevopoulos <97fa9f4b61869a8ee92863df90135c882f7b3aa0@intracom-telecom.com>
Python
apache-2.0
mywulin/functest,opnfv/functest,mywulin/functest,opnfv/functest
--- +++ @@ -8,6 +8,7 @@ # http://www.apache.org/licenses/LICENSE-2.0 # import functest.core.feature_base as base +from sfc.tests.functest import run_tests class OpenDaylightSFC(base.FeatureBase): @@ -16,5 +17,6 @@ super(OpenDaylightSFC, self).__init__(project='sfc', case='functest-odl-sfc', repo='dir_repo_sfc') - dir_sfc_functest = '{}/sfc/tests/functest'.format(self.repo) - self.cmd = 'cd %s && python ./run_tests.py' % dir_sfc_functest + + def execute(self): + return run_tests.main()
6fa0db63d12f11f0d11a77c2d0799cd506196b5b
chatterbot/utils/clean.py
chatterbot/utils/clean.py
import re def clean_whitespace(text): """ Remove any extra whitespace and line breaks as needed. """ # Replace linebreaks with spaces text = text.replace("\n", " ").replace("\r", " ").replace("\t", " ") # Remove any leeding or trailing whitespace text = text.strip() # Remove consecutive spaces text = re.sub(" +", " ", text) return text def clean(text): """ A function for cleaning a string of text. Returns valid ASCII characters. """ import unicodedata import sys text = clean_whitespace(text) # Remove links from message # text = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '', text) # Replace HTML escape characters if sys.version_info[0] < 3: from HTMLParser import HTMLParser parser = HTMLParser() text = parser.unescape(text) else: import html.parser parser = html.parser.HTMLParser() text = parser.unescape(text) # Normalize unicode characters # 'raw_input' is just 'input' in python3 if sys.version_info[0] < 3: text = unicode(text) text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("utf-8") return str(text)
import re def clean_whitespace(text): """ Remove any extra whitespace and line breaks as needed. """ # Replace linebreaks with spaces text = text.replace("\n", " ").replace("\r", " ").replace("\t", " ") # Remove any leeding or trailing whitespace text = text.strip() # Remove consecutive spaces text = re.sub(" +", " ", text) return text def clean(text): """ A function for cleaning a string of text. Returns valid ASCII characters. """ import unicodedata import sys text = clean_whitespace(text) # Remove links from message # text = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', '', text) # Replace HTML escape characters if sys.version_info[0] < 3: from HTMLParser import HTMLParser parser = HTMLParser() text = parser.unescape(text) else: import html text = html.unescape(text) # Normalize unicode characters # 'raw_input' is just 'input' in python3 if sys.version_info[0] < 3: text = unicode(text) text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode("utf-8") return str(text)
Update python3 html parser depricated method.
Update python3 html parser depricated method.
Python
bsd-3-clause
Reinaesaya/OUIRL-ChatBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,davizucon/ChatterBot,vkosuri/ChatterBot
--- +++ @@ -36,9 +36,8 @@ parser = HTMLParser() text = parser.unescape(text) else: - import html.parser - parser = html.parser.HTMLParser() - text = parser.unescape(text) + import html + text = html.unescape(text) # Normalize unicode characters # 'raw_input' is just 'input' in python3
36deb1b445ba631666a0e4870f4e46c566d3ea78
sms_939/controllers/sms_notification_controller.py
sms_939/controllers/sms_notification_controller.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import http from odoo.http import request class RestController(http.Controller): @http.route('/sms/mnc/', type='http', auth='public', methods=['GET'], csrf=False) def sms_notification(self, **parameters): sms = request.env['sms.notification'].sudo().create({ 'instance': parameters.get('instance'), 'sender': parameters.get('sender'), 'operator': parameters.get('operator'), 'service': parameters.get('service'), 'language': parameters.get('language'), 'date': parameters.get('receptionDate'), 'uuid': parameters.get('requestUid'), 'text': parameters.get('text'), }) return sms.run_service()
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2018 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # ############################################################################## from odoo import http from odoo.http import request class RestController(http.Controller): @http.route('/sms/mnc/', type='http', auth='public', methods=['POST'], csrf=False) def sms_notification(self, **parameters): sms = request.env['sms.notification'].sudo().create({ 'instance': parameters.get('instance'), 'sender': parameters.get('sender'), 'operator': parameters.get('operator'), 'service': parameters.get('service'), 'language': parameters.get('language'), 'date': parameters.get('receptionDate'), 'uuid': parameters.get('requestUid'), 'text': parameters.get('text'), }) return sms.run_service()
CHANGE mnc route to POST message
CHANGE mnc route to POST message
Python
agpl-3.0
eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland
--- +++ @@ -15,7 +15,7 @@ class RestController(http.Controller): - @http.route('/sms/mnc/', type='http', auth='public', methods=['GET'], + @http.route('/sms/mnc/', type='http', auth='public', methods=['POST'], csrf=False) def sms_notification(self, **parameters): sms = request.env['sms.notification'].sudo().create({
6e0e2a1e38506e85302197d4f700a924a609390c
pandas/compat/openpyxl_compat.py
pandas/compat/openpyxl_compat.py
""" Detect incompatible version of OpenPyXL GH7169 """ from distutils.version import LooseVersion start_ver = '1.6.1' stop_ver = '2.0.0' def is_compat(): """Detect whether the installed version of openpyxl is supported. Returns ------- compat : bool ``True`` if openpyxl is installed and is between versions 1.6.1 and 2.0.0, ``False`` otherwise. """ import openpyxl ver = LooseVersion(openpyxl.__version__) return LooseVersion(start_ver) < ver <= LooseVersion(stop_ver)
""" Detect incompatible version of OpenPyXL GH7169 """ from distutils.version import LooseVersion start_ver = '1.6.1' stop_ver = '2.0.0' def is_compat(): """Detect whether the installed version of openpyxl is supported. Returns ------- compat : bool ``True`` if openpyxl is installed and is between versions 1.6.1 and 2.0.0, ``False`` otherwise. """ import openpyxl ver = LooseVersion(openpyxl.__version__) return LooseVersion(start_ver) <= ver < LooseVersion(stop_ver)
Fix mismatched logic error in compatibility check
BUG: Fix mismatched logic error in compatibility check
Python
bsd-3-clause
pratapvardhan/pandas,nmartensen/pandas,cbertinato/pandas,jmmease/pandas,kdebrab/pandas,Winand/pandas,DGrady/pandas,MJuddBooth/pandas,jorisvandenbossche/pandas,jreback/pandas,jmmease/pandas,harisbal/pandas,DGrady/pandas,harisbal/pandas,gfyoung/pandas,jorisvandenbossche/pandas,jreback/pandas,jreback/pandas,cbertinato/pandas,pandas-dev/pandas,MJuddBooth/pandas,nmartensen/pandas,rs2/pandas,jreback/pandas,datapythonista/pandas,kdebrab/pandas,zfrenchee/pandas,kdebrab/pandas,linebp/pandas,jmmease/pandas,linebp/pandas,linebp/pandas,amolkahat/pandas,gfyoung/pandas,nmartensen/pandas,cython-testbed/pandas,DGrady/pandas,louispotok/pandas,MJuddBooth/pandas,linebp/pandas,gfyoung/pandas,nmartensen/pandas,zfrenchee/pandas,pratapvardhan/pandas,GuessWhoSamFoo/pandas,toobaz/pandas,toobaz/pandas,toobaz/pandas,GuessWhoSamFoo/pandas,linebp/pandas,harisbal/pandas,amolkahat/pandas,dsm054/pandas,kdebrab/pandas,winklerand/pandas,dsm054/pandas,jmmease/pandas,DGrady/pandas,cython-testbed/pandas,datapythonista/pandas,cython-testbed/pandas,gfyoung/pandas,nmartensen/pandas,datapythonista/pandas,pandas-dev/pandas,winklerand/pandas,Winand/pandas,cbertinato/pandas,Winand/pandas,nmartensen/pandas,MJuddBooth/pandas,amolkahat/pandas,GuessWhoSamFoo/pandas,louispotok/pandas,toobaz/pandas,TomAugspurger/pandas,Winand/pandas,zfrenchee/pandas,Winand/pandas,pandas-dev/pandas,rs2/pandas,kdebrab/pandas,jmmease/pandas,rs2/pandas,winklerand/pandas,pratapvardhan/pandas,dsm054/pandas,harisbal/pandas,louispotok/pandas,pandas-dev/pandas,winklerand/pandas,MJuddBooth/pandas,pratapvardhan/pandas,toobaz/pandas,TomAugspurger/pandas,jreback/pandas,DGrady/pandas,GuessWhoSamFoo/pandas,gfyoung/pandas,zfrenchee/pandas,cbertinato/pandas,amolkahat/pandas,jorisvandenbossche/pandas,louispotok/pandas,TomAugspurger/pandas,winklerand/pandas,linebp/pandas,harisbal/pandas,Winand/pandas,dsm054/pandas,jorisvandenbossche/pandas,datapythonista/pandas,jmmease/pandas,DGrady/pandas,pratapvardhan/pandas,TomAugspurger/pandas,rs2/pandas,GuessWhoSamFoo/pandas,dsm054/pandas,amolkahat/pandas,zfrenchee/pandas,winklerand/pandas,cython-testbed/pandas,cbertinato/pandas,louispotok/pandas,cython-testbed/pandas
--- +++ @@ -21,4 +21,4 @@ """ import openpyxl ver = LooseVersion(openpyxl.__version__) - return LooseVersion(start_ver) < ver <= LooseVersion(stop_ver) + return LooseVersion(start_ver) <= ver < LooseVersion(stop_ver)
a36e63037ce279d07a04074baf8c9f756dd8128a
wmtexe/cmi/make.py
wmtexe/cmi/make.py
import argparse import yaml from .bocca import make_project, ProjectExistsError def main(): parser = argparse.ArgumentParser() parser.add_argument('file', help='Project description file') args = parser.parse_args() try: with open(args.file, 'r') as fp: make_project(yaml.load(fp)) except ProjectExistsError as error: print 'The specified project (%s) already exists. Exiting.' % error if __name__ == '__main__': main()
import argparse import yaml from .bocca import make_project, ProjectExistsError def main(): parser = argparse.ArgumentParser() parser.add_argument('file', type=argparse.FileType('r'), help='Project description file') args = parser.parse_args() try: make_project(yaml.load(args.file)) except ProjectExistsError as error: print 'The specified project (%s) already exists. Exiting.' % error if __name__ == '__main__': main()
Read input file from stdin.
Read input file from stdin.
Python
mit
csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe,csdms/wmt-exe
--- +++ @@ -7,13 +7,13 @@ def main(): parser = argparse.ArgumentParser() - parser.add_argument('file', help='Project description file') + parser.add_argument('file', type=argparse.FileType('r'), + help='Project description file') args = parser.parse_args() try: - with open(args.file, 'r') as fp: - make_project(yaml.load(fp)) + make_project(yaml.load(args.file)) except ProjectExistsError as error: print 'The specified project (%s) already exists. Exiting.' % error
62c3fcd65b4c7d3cc4732885cf81640607a04480
marty/commands/remotes.py
marty/commands/remotes.py
import datetime import arrow from marty.commands import Command from marty.printer import printer class Remotes(Command): """ Show the list of configured remotes. """ help = 'Show the list of configured remotes' def run(self, args, config, storage, remotes): table_lines = [('<b>NAME</b>', '<b>TYPE</b>', '<b>LAST</b>', '<b>NEXT</b>')] for remote in sorted(remotes.list(), key=lambda x: x.name): latest_ref = '%s/latest' % remote.name latest_backup = storage.get_backup(latest_ref) latest_date_text = '-' next_date_text = '-' if latest_backup is None: if remote.scheduler is not None: next_date_text = '<color fg=yellow>now</color>' else: latest_date_text = '%s' % latest_backup.start_date.humanize() if remote.scheduler is not None and remote.scheduler['enabled']: next_date = latest_backup.start_date + datetime.timedelta(seconds=remote.scheduler['interval'] * 60) if next_date > arrow.now(): next_date_text = '<color fg=green>%s</color>' % next_date.humanize() else: next_date_text = '<color fg=red>%s</color>' % next_date.humanize() table_lines.append((remote.name, remote.type, latest_date_text, next_date_text)) printer.table(table_lines)
import datetime import arrow from marty.commands import Command from marty.printer import printer class Remotes(Command): """ Show the list of configured remotes. """ help = 'Show the list of configured remotes' def run(self, args, config, storage, remotes): table_lines = [('<b>NAME</b>', '<b>TYPE</b>', '<b>LAST</b>', '<b>NEXT</b>')] for remote in sorted(remotes.list(), key=lambda x: x.name): latest_ref = '%s/latest' % remote.name latest_backup = storage.get_backup(latest_ref) latest_date_text = '-' next_date_text = '-' if latest_backup is None: if remote.scheduler is not None: next_date_text = '<color fg=yellow>now</color>' else: latest_date_text = latest_backup.start_date.humanize() if remote.scheduler is not None and remote.scheduler['enabled']: next_date = latest_backup.start_date + datetime.timedelta(seconds=remote.scheduler['interval'] * 60) if next_date > arrow.now(): next_date_text = '<color fg=green>%s</color>' % next_date.humanize() else: next_date_text = '<color fg=red>%s</color>' % next_date.humanize() table_lines.append((remote.name, remote.type, latest_date_text, next_date_text)) printer.table(table_lines)
Clean useless format string in remote command
Clean useless format string in remote command
Python
mit
NaPs/Marty
--- +++ @@ -24,7 +24,7 @@ if remote.scheduler is not None: next_date_text = '<color fg=yellow>now</color>' else: - latest_date_text = '%s' % latest_backup.start_date.humanize() + latest_date_text = latest_backup.start_date.humanize() if remote.scheduler is not None and remote.scheduler['enabled']: next_date = latest_backup.start_date + datetime.timedelta(seconds=remote.scheduler['interval'] * 60) if next_date > arrow.now():
24a6519b7d6a9e961adff1b23a3d64231fc9d233
frappe/integrations/doctype/social_login_key/test_social_login_key.py
frappe/integrations/doctype/social_login_key/test_social_login_key.py
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe from frappe.integrations.doctype.social_login_key.social_login_key import BaseUrlNotSetError import unittest class TestSocialLoginKey(unittest.TestCase): def test_adding_frappe_social_login_provider(self): provider_name = "Frappe" social_login_key = make_social_login_key( social_login_provider=provider_name ) social_login_key.get_social_login_provider(provider_name, initialize=True) self.assertRaises(BaseUrlNotSetError, social_login_key.insert) def make_social_login_key(**kwargs): kwargs["doctype"] = "Social Login Key" if not "provider_name" in kwargs: kwargs["provider_name"] = "Test OAuth2 Provider" doc = frappe.get_doc(kwargs) return doc
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import frappe from frappe.integrations.doctype.social_login_key.social_login_key import BaseUrlNotSetError import unittest class TestSocialLoginKey(unittest.TestCase): def test_adding_frappe_social_login_provider(self): provider_name = "Frappe" social_login_key = make_social_login_key( social_login_provider=provider_name ) social_login_key.get_social_login_provider(provider_name, initialize=True) self.assertRaises(BaseUrlNotSetError, social_login_key.insert) def make_social_login_key(**kwargs): kwargs["doctype"] = "Social Login Key" if not "provider_name" in kwargs: kwargs["provider_name"] = "Test OAuth2 Provider" doc = frappe.get_doc(kwargs) return doc def create_or_update_social_login_key(): # used in other tests (connected app, oauth20) try: social_login_key = frappe.get_doc("Social Login Key", "frappe") except frappe.DoesNotExistError: social_login_key = frappe.new_doc("Social Login Key") social_login_key.get_social_login_provider("Frappe", initialize=True) social_login_key.base_url = frappe.utils.get_url() social_login_key.enable_social_login = 0 social_login_key.save() frappe.db.commit() return social_login_key
Add missing method required for test
test: Add missing method required for test - backported create_or_update_social_login_key from v13
Python
mit
vjFaLk/frappe,vjFaLk/frappe,vjFaLk/frappe,vjFaLk/frappe
--- +++ @@ -22,3 +22,17 @@ kwargs["provider_name"] = "Test OAuth2 Provider" doc = frappe.get_doc(kwargs) return doc + +def create_or_update_social_login_key(): + # used in other tests (connected app, oauth20) + try: + social_login_key = frappe.get_doc("Social Login Key", "frappe") + except frappe.DoesNotExistError: + social_login_key = frappe.new_doc("Social Login Key") + social_login_key.get_social_login_provider("Frappe", initialize=True) + social_login_key.base_url = frappe.utils.get_url() + social_login_key.enable_social_login = 0 + social_login_key.save() + frappe.db.commit() + + return social_login_key
2363cf9733006f08f2dc1061562bc29788206f21
fabfile.py
fabfile.py
from fabric.api import cd, env, run, task try: import fabfile_local _pyflakes = fabfile_local except ImportError: pass @task def update(): with cd("~/vagrant-installers"): run("git pull") @task def all(): "Run the task against all hosts." for _, value in env.roledefs.iteritems(): env.hosts.extend(value) @task def role(name): "Set the hosts to a specific role." env.hosts = env.roledefs[name]
from fabric.api import cd, env, run, task try: import fabfile_local _pyflakes = fabfile_local except ImportError: pass @task def update(): "Updates the installer generate code on the host." with cd("~/vagrant-installers"): run("git pull") @task def build(): "Builds the installer." with cd("~/vagrant-installers"): run("rake") @task def all(): "Run the task against all hosts." for _, value in env.roledefs.iteritems(): env.hosts.extend(value) @task def role(name): "Set the hosts to a specific role." env.hosts = env.roledefs[name]
Add fab task to build
Add fab task to build
Python
mit
redhat-developer-tooling/vagrant-installers,mitchellh/vagrant-installers,chrisroberts/vagrant-installers,redhat-developer-tooling/vagrant-installers,chrisroberts/vagrant-installers,chrisroberts/vagrant-installers,mitchellh/vagrant-installers,redhat-developer-tooling/vagrant-installers,chrisroberts/vagrant-installers,chrisroberts/vagrant-installers,mitchellh/vagrant-installers,mitchellh/vagrant-installers,chrisroberts/vagrant-installers,redhat-developer-tooling/vagrant-installers,mitchellh/vagrant-installers,mitchellh/vagrant-installers
--- +++ @@ -8,8 +8,15 @@ @task def update(): + "Updates the installer generate code on the host." with cd("~/vagrant-installers"): run("git pull") + +@task +def build(): + "Builds the installer." + with cd("~/vagrant-installers"): + run("rake") @task def all():
6c74b18372d3945f909ad63f6f58e11e7658282a
openacademy/model/openacademy_session.py
openacademy/model/openacademy_session.py
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor") course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") instructor_id = fields.Many2one('res.partner', string="Instructor", domain=['|', ("instructor", "=", True), ("category_id", "ilike", "Teacher"), ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")
Add domain or and ilike
[REF] openacademy: Add domain or and ilike
Python
apache-2.0
deivislaya/openacademy-project
--- +++ @@ -8,7 +8,11 @@ start_date = fields.Date() duration = fields.Float(digits=(6, 2), help="Duration in days") seats = fields.Integer(string="Number of seats") - instructor_id = fields.Many2one('res.partner', string="Instructor") + instructor_id = fields.Many2one('res.partner', string="Instructor", + domain=['|', + ("instructor", "=", True), + ("category_id", "ilike", "Teacher"), + ]) course_id = fields.Many2one('openacademy.course', ondelete='cascade', string="Course", required=True) attendee_ids = fields.Many2many('res.partner', string="Attendees")