commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
4c60e42af4b37c260e2a9f00eb82dbd44ee53799
__init__.py
__init__.py
__all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', 'tween', 'tweenfunc', 'util', 'world', 'Game', 'Constants', 'Point', 'Vector', 'GameLoop', 'World'] # convenience imports import entity, gameloop, util, world, mixin, music, point, sound, text, \ tiledimage, tilemap, tween, tweenfunc, emitter, effects from gameloop import Game, GameLoop from world import World from point import Point, Vector from entity import Image, Entity Constants = Game.Constants """A number of useful constants, such as keycodes, event types, and display flags."""
__all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', 'tween', 'tweenfunc', 'util', 'world', 'Game', 'Constants', 'Point', 'Vector', 'GameLoop', 'World', 'Image', 'Entity'] # convenience imports import entity, gameloop, util, world, mixin, music, point, sound, text, \ tiledimage, tilemap, tween, tweenfunc, emitter, effects from gameloop import Game, GameLoop from world import World from point import Point, Vector from entity import Image, Entity Constants = Game.Constants """A number of useful constants, such as keycodes, event types, and display flags."""
Put Image and Entity into __all__
Put Image and Entity into __all__
Python
lgpl-2.1
momikey/pyrge
__all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', 'tween', 'tweenfunc', 'util', 'world', - 'Game', 'Constants', 'Point', 'Vector', 'GameLoop', 'World'] + 'Game', 'Constants', 'Point', 'Vector', + 'GameLoop', 'World', 'Image', 'Entity'] # convenience imports import entity, gameloop, util, world, mixin, music, point, sound, text, \ tiledimage, tilemap, tween, tweenfunc, emitter, effects from gameloop import Game, GameLoop from world import World from point import Point, Vector from entity import Image, Entity Constants = Game.Constants """A number of useful constants, such as keycodes, event types, and display flags."""
Put Image and Entity into __all__
## Code Before: __all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', 'tween', 'tweenfunc', 'util', 'world', 'Game', 'Constants', 'Point', 'Vector', 'GameLoop', 'World'] # convenience imports import entity, gameloop, util, world, mixin, music, point, sound, text, \ tiledimage, tilemap, tween, tweenfunc, emitter, effects from gameloop import Game, GameLoop from world import World from point import Point, Vector from entity import Image, Entity Constants = Game.Constants """A number of useful constants, such as keycodes, event types, and display flags.""" ## Instruction: Put Image and Entity into __all__ ## Code After: __all__ = ['effects', 'emitter', 'entity', 'gameloop', 'mixin', 'music', 'point', 'quadtree', 'sound', 'spritesheet', 'text', 'tiledimage', 'tilemap', 'tween', 'tweenfunc', 'util', 'world', 'Game', 'Constants', 'Point', 'Vector', 'GameLoop', 'World', 'Image', 'Entity'] # convenience imports import entity, gameloop, util, world, mixin, music, point, sound, text, \ tiledimage, tilemap, tween, tweenfunc, emitter, effects from gameloop import Game, GameLoop from world import World from point import Point, Vector from entity import Image, Entity Constants = Game.Constants """A number of useful constants, such as keycodes, event types, and display flags."""
c01a858306d31a5b12e42f30ff01bdbdb2240092
froide/publicbody/tests.py
froide/publicbody/tests.py
from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2)
from django.test import TestCase from django.core.urlresolvers import reverse from publicbody.models import PublicBody class PublicBodyTest(TestCase): fixtures = ['auth.json', 'publicbodies.json', 'foirequest.json'] def test_web_page(self): response = self.client.get(reverse('publicbody-list')) self.assertEqual(response.status_code, 200) pb = PublicBody.objects.all()[0] response = self.client.get(reverse('publicbody-show', kwargs={"slug": pb.slug})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('publicbody-show_json', kwargs={"pk": pb.pk, "format": "json"})) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertIn('"name":', response.content) self.assertIn('"laws": [{', response.content) response = self.client.get(reverse('publicbody-show_json', kwargs={"slug": pb.slug, "format": "json"})) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') def test_csv(self): csv = PublicBody.export_csv() self.assertTrue(csv) def test_search(self): response = self.client.get(reverse('publicbody-search')+"?q=umwelt") self.assertIn("Umweltbundesamt", response.content) self.assertEqual(response['Content-Type'], 'application/json')
Test public body showing, json view and csv export
Test public body showing, json view and csv export
Python
mit
okfse/froide,ryankanno/froide,catcosmo/froide,ryankanno/froide,okfse/froide,LilithWittmann/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,catcosmo/froide,catcosmo/froide,stefanw/froide,ryankanno/froide,fin/froide,fin/froide,catcosmo/froide,okfse/froide,fin/froide,LilithWittmann/froide,stefanw/froide,catcosmo/froide,ryankanno/froide,LilithWittmann/froide,fin/froide,stefanw/froide,CodeforHawaii/froide,CodeforHawaii/froide,CodeforHawaii/froide,okfse/froide
+ from django.test import TestCase + from django.core.urlresolvers import reverse - from django.test import TestCase + from publicbody.models import PublicBody + class PublicBodyTest(TestCase): + fixtures = ['auth.json', 'publicbodies.json', 'foirequest.json'] - class SimpleTest(TestCase): - def test_basic_addition(self): - """ - Tests that 1 + 1 always equals 2. - """ - self.assertEqual(1 + 1, 2) + def test_web_page(self): + response = self.client.get(reverse('publicbody-list')) + self.assertEqual(response.status_code, 200) + pb = PublicBody.objects.all()[0] + response = self.client.get(reverse('publicbody-show', kwargs={"slug": pb.slug})) + self.assertEqual(response.status_code, 200) + response = self.client.get(reverse('publicbody-show_json', kwargs={"pk": pb.pk, "format": "json"})) + self.assertEqual(response.status_code, 200) + self.assertEqual(response['Content-Type'], 'application/json') + self.assertIn('"name":', response.content) + self.assertIn('"laws": [{', response.content) + response = self.client.get(reverse('publicbody-show_json', kwargs={"slug": pb.slug, "format": "json"})) + self.assertEqual(response.status_code, 200) + self.assertEqual(response['Content-Type'], 'application/json') + def test_csv(self): + csv = PublicBody.export_csv() + self.assertTrue(csv) + + def test_search(self): + response = self.client.get(reverse('publicbody-search')+"?q=umwelt") + self.assertIn("Umweltbundesamt", response.content) + self.assertEqual(response['Content-Type'], 'application/json') +
Test public body showing, json view and csv export
## Code Before: from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """ Tests that 1 + 1 always equals 2. """ self.assertEqual(1 + 1, 2) ## Instruction: Test public body showing, json view and csv export ## Code After: from django.test import TestCase from django.core.urlresolvers import reverse from publicbody.models import PublicBody class PublicBodyTest(TestCase): fixtures = ['auth.json', 'publicbodies.json', 'foirequest.json'] def test_web_page(self): response = self.client.get(reverse('publicbody-list')) self.assertEqual(response.status_code, 200) pb = PublicBody.objects.all()[0] response = self.client.get(reverse('publicbody-show', kwargs={"slug": pb.slug})) self.assertEqual(response.status_code, 200) response = self.client.get(reverse('publicbody-show_json', kwargs={"pk": pb.pk, "format": "json"})) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') self.assertIn('"name":', response.content) self.assertIn('"laws": [{', response.content) response = self.client.get(reverse('publicbody-show_json', kwargs={"slug": pb.slug, "format": "json"})) self.assertEqual(response.status_code, 200) self.assertEqual(response['Content-Type'], 'application/json') def test_csv(self): csv = PublicBody.export_csv() self.assertTrue(csv) def test_search(self): response = self.client.get(reverse('publicbody-search')+"?q=umwelt") self.assertIn("Umweltbundesamt", response.content) self.assertEqual(response['Content-Type'], 'application/json')
076f8cf27d3a1b52a1b597e224d23bd2ba18fcd7
kalamarsite.py
kalamarsite.py
import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'(.*)/pages/(.*)\.rst', ('project', 'page')), [('title', RestProperty(unicode, TITLE))], 'content') news = Rest( FileSystem( PROJECTS_PATH, r'(.*)/news/(.*)/(.*)\.rst', ('project', 'writer', 'datetime')), [('title', RestProperty(unicode, TITLE))], 'content') tutorial = Cache( Rest( FileSystem( PROJECTS_PATH, r'(.*)/tutorials/(.*)\.rst', ('project', 'tutorial')), [('title', RestProperty(unicode, TITLE)), ('abstract', RestProperty(unicode, '//topic/paragraph'))], 'content')) SITE = kalamar.site.Site() SITE.register('page', page) SITE.register('news', news) SITE.register('tutorial', tutorial)
import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/pages/(.*)\.rst', ('project', 'page')), [('title', RestProperty(unicode, TITLE))], 'content') news = Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/news/(.*)/(.*)\.rst', ('project', 'writer', 'datetime')), [('title', RestProperty(unicode, TITLE))], 'content') tutorial = Cache( Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/tutorials/(.*)\.rst', ('project', 'tutorial')), [('title', RestProperty(unicode, TITLE)), ('abstract', RestProperty(unicode, '//topic/paragraph'))], 'content')) SITE = kalamar.site.Site() SITE.register('page', page) SITE.register('news', news) SITE.register('tutorial', tutorial)
Use [a-z]* pattern to match project ids
Use [a-z]* pattern to match project ids
Python
bsd-3-clause
Kozea/sitenco
import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( - PROJECTS_PATH, r'(.*)/pages/(.*)\.rst', ('project', 'page')), + PROJECTS_PATH, r'([a-z]*)/pages/(.*)\.rst', ('project', 'page')), [('title', RestProperty(unicode, TITLE))], 'content') news = Rest( FileSystem( - PROJECTS_PATH, r'(.*)/news/(.*)/(.*)\.rst', + PROJECTS_PATH, r'([a-z]*)/news/(.*)/(.*)\.rst', ('project', 'writer', 'datetime')), [('title', RestProperty(unicode, TITLE))], 'content') tutorial = Cache( Rest( FileSystem( + PROJECTS_PATH, - PROJECTS_PATH, r'(.*)/tutorials/(.*)\.rst', ('project', 'tutorial')), + r'([a-z]*)/tutorials/(.*)\.rst', ('project', 'tutorial')), [('title', RestProperty(unicode, TITLE)), ('abstract', RestProperty(unicode, '//topic/paragraph'))], 'content')) SITE = kalamar.site.Site() SITE.register('page', page) SITE.register('news', news) SITE.register('tutorial', tutorial)
Use [a-z]* pattern to match project ids
## Code Before: import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'(.*)/pages/(.*)\.rst', ('project', 'page')), [('title', RestProperty(unicode, TITLE))], 'content') news = Rest( FileSystem( PROJECTS_PATH, r'(.*)/news/(.*)/(.*)\.rst', ('project', 'writer', 'datetime')), [('title', RestProperty(unicode, TITLE))], 'content') tutorial = Cache( Rest( FileSystem( PROJECTS_PATH, r'(.*)/tutorials/(.*)\.rst', ('project', 'tutorial')), [('title', RestProperty(unicode, TITLE)), ('abstract', RestProperty(unicode, '//topic/paragraph'))], 'content')) SITE = kalamar.site.Site() SITE.register('page', page) SITE.register('news', news) SITE.register('tutorial', tutorial) ## Instruction: Use [a-z]* pattern to match project ids ## Code After: import os import kalamar.site from kalamar.access_point.cache import Cache from kalamar.access_point.xml.rest import Rest, RestProperty, TITLE from kalamar.access_point.filesystem import FileSystem from sitenco import PROJECTS_PATH page = Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/pages/(.*)\.rst', ('project', 'page')), [('title', RestProperty(unicode, TITLE))], 'content') news = Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/news/(.*)/(.*)\.rst', ('project', 'writer', 'datetime')), [('title', RestProperty(unicode, TITLE))], 'content') tutorial = Cache( Rest( FileSystem( PROJECTS_PATH, r'([a-z]*)/tutorials/(.*)\.rst', ('project', 'tutorial')), [('title', RestProperty(unicode, TITLE)), ('abstract', RestProperty(unicode, '//topic/paragraph'))], 'content')) SITE = kalamar.site.Site() SITE.register('page', page) SITE.register('news', news) SITE.register('tutorial', tutorial)
696010e636f7e30ba331b103ba051422780edf4b
bluebottle/funding/utils.py
bluebottle/funding/utils.py
from babel.numbers import get_currency_name, get_currency_symbol from bluebottle.utils.exchange_rates import convert from django.db.models import Sum from djmoney.money import Money from bluebottle.funding.models import PaymentProvider def get_currency_settings(): result = [] for provider in PaymentProvider.objects.all(): for cur in provider.paymentcurrency_set.all(): result.append({ 'provider': provider.name, 'providerName': provider.title, 'code': cur.code, 'name': get_currency_name(cur.code), 'symbol': get_currency_symbol(cur.code).replace('US$', '$').replace('NGN', '₦'), 'defaultAmounts': [ cur.default1, cur.default2, cur.default3, cur.default4, ], 'minAmount': cur.min_amount, 'maxAmount': cur.max_amount }) return result def calculate_total(queryset, target='EUR'): totals = queryset.values( 'donor__amount_currency' ).annotate( total=Sum('donor__amount') ).order_by('-created') amounts = [Money(tot['total'], tot['donor__amount_currency']) for tot in totals] amounts = [convert(amount, target) for amount in amounts] return sum(amounts) or Money(0, target)
from babel.numbers import get_currency_name, get_currency_symbol from bluebottle.utils.exchange_rates import convert from django.db.models import Sum from djmoney.money import Money from bluebottle.funding.models import PaymentProvider def get_currency_settings(): result = [] for provider in PaymentProvider.objects.all(): for cur in provider.paymentcurrency_set.all(): result.append({ 'provider': provider.name, 'providerName': provider.title, 'code': cur.code, 'name': get_currency_name(cur.code), 'symbol': get_currency_symbol(cur.code).replace('US$', '$').replace('NGN', '₦'), 'defaultAmounts': [ cur.default1, cur.default2, cur.default3, cur.default4, ], 'minAmount': cur.min_amount, 'maxAmount': cur.max_amount }) return result def calculate_total(queryset, target='EUR'): totals = queryset.values( 'donor__payout_amount_currency' ).annotate( total=Sum('donor__payout_amount') ).order_by('-created') amounts = [Money(tot['total'], tot['donor__payout_amount_currency']) for tot in totals] amounts = [convert(amount, target) for amount in amounts] return sum(amounts) or Money(0, target)
USe payout amount to calculate total
USe payout amount to calculate total
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
from babel.numbers import get_currency_name, get_currency_symbol from bluebottle.utils.exchange_rates import convert from django.db.models import Sum from djmoney.money import Money from bluebottle.funding.models import PaymentProvider def get_currency_settings(): result = [] for provider in PaymentProvider.objects.all(): for cur in provider.paymentcurrency_set.all(): result.append({ 'provider': provider.name, 'providerName': provider.title, 'code': cur.code, 'name': get_currency_name(cur.code), 'symbol': get_currency_symbol(cur.code).replace('US$', '$').replace('NGN', '₦'), 'defaultAmounts': [ cur.default1, cur.default2, cur.default3, cur.default4, ], 'minAmount': cur.min_amount, 'maxAmount': cur.max_amount }) return result def calculate_total(queryset, target='EUR'): totals = queryset.values( - 'donor__amount_currency' + 'donor__payout_amount_currency' ).annotate( - total=Sum('donor__amount') + total=Sum('donor__payout_amount') ).order_by('-created') - amounts = [Money(tot['total'], tot['donor__amount_currency']) for tot in totals] + amounts = [Money(tot['total'], tot['donor__payout_amount_currency']) for tot in totals] amounts = [convert(amount, target) for amount in amounts] return sum(amounts) or Money(0, target)
USe payout amount to calculate total
## Code Before: from babel.numbers import get_currency_name, get_currency_symbol from bluebottle.utils.exchange_rates import convert from django.db.models import Sum from djmoney.money import Money from bluebottle.funding.models import PaymentProvider def get_currency_settings(): result = [] for provider in PaymentProvider.objects.all(): for cur in provider.paymentcurrency_set.all(): result.append({ 'provider': provider.name, 'providerName': provider.title, 'code': cur.code, 'name': get_currency_name(cur.code), 'symbol': get_currency_symbol(cur.code).replace('US$', '$').replace('NGN', '₦'), 'defaultAmounts': [ cur.default1, cur.default2, cur.default3, cur.default4, ], 'minAmount': cur.min_amount, 'maxAmount': cur.max_amount }) return result def calculate_total(queryset, target='EUR'): totals = queryset.values( 'donor__amount_currency' ).annotate( total=Sum('donor__amount') ).order_by('-created') amounts = [Money(tot['total'], tot['donor__amount_currency']) for tot in totals] amounts = [convert(amount, target) for amount in amounts] return sum(amounts) or Money(0, target) ## Instruction: USe payout amount to calculate total ## Code After: from babel.numbers import get_currency_name, get_currency_symbol from bluebottle.utils.exchange_rates import convert from django.db.models import Sum from djmoney.money import Money from bluebottle.funding.models import PaymentProvider def get_currency_settings(): result = [] for provider in PaymentProvider.objects.all(): for cur in provider.paymentcurrency_set.all(): result.append({ 'provider': provider.name, 'providerName': provider.title, 'code': cur.code, 'name': get_currency_name(cur.code), 'symbol': get_currency_symbol(cur.code).replace('US$', '$').replace('NGN', '₦'), 'defaultAmounts': [ cur.default1, cur.default2, cur.default3, cur.default4, ], 'minAmount': cur.min_amount, 'maxAmount': cur.max_amount }) return result def calculate_total(queryset, target='EUR'): totals = queryset.values( 'donor__payout_amount_currency' ).annotate( total=Sum('donor__payout_amount') ).order_by('-created') amounts = [Money(tot['total'], tot['donor__payout_amount_currency']) for tot in totals] amounts = [convert(amount, target) for amount in amounts] return sum(amounts) or Money(0, target)
38746e4f4891f7ad87ce678776be15556d1db449
gcl/to_json.py
gcl/to_json.py
import argparse import json import sys import gcl from gcl import query from gcl import util def main(argv=None, stdin=None): parser = argparse.ArgumentParser(description='Convert (parts of) a GCL model file to JSON.') parser.add_argument('file', metavar='FILE', type=str, nargs='?', help='File to parse') parser.add_argument('selectors', metavar='SELECTOR', type=str, nargs='*', help='Subnodes to convert. The first selector will be treated as the root of the printed output.') args = parser.parse_args(argv or sys.argv[1:]) try: if args.file and args.file != '-': model = gcl.load(args.file) else: model = gcl.loads((stdin or sys.stdin).read(), filename='<stdin>') sels = query.GPath(args.selectors) if not sels.everything(): model = sels.select(model).deep() plain = util.to_python(model) sys.stdout.write(json.dumps(plain)) except (gcl.ParseError, RuntimeError) as e: sys.stderr.write(str(e) + '\n') sys.exit(1)
import argparse import json import sys import gcl from gcl import query from gcl import util def select(dct, path): for part in path: if not hasattr(dct, 'keys'): raise RuntimeError('Value %r cannot be indexed with %r' % (dct, part)) if part not in dct: raise RuntimeError('Value %r has no key %r' % (dct, part)) dct = dct[part] return dct def main(argv=None, stdin=None): parser = argparse.ArgumentParser(description='Convert (parts of) a GCL model file to JSON.') parser.add_argument('file', metavar='FILE', type=str, nargs='?', help='File to parse') parser.add_argument('selectors', metavar='SELECTOR', type=str, nargs='*', help='Select nodes to include in the JSON.') parser.add_argument('--root', '-r', metavar='PATH', type=str, default='', help='Use the indicated root path as the root of the output JSON object (like a.b.c but without wildcards)') args = parser.parse_args(argv or sys.argv[1:]) try: if args.file and args.file != '-': model = gcl.load(args.file) else: model = gcl.loads((stdin or sys.stdin).read(), filename='<stdin>') sels = query.GPath(args.selectors) if not sels.everything(): model = sels.select(model).deep() plain = util.to_python(model) selectors = args.root.split('.') if args.root else [] selected = select(plain, selectors) sys.stdout.write(json.dumps(selected)) except (gcl.ParseError, RuntimeError) as e: sys.stderr.write(str(e) + '\n') sys.exit(1)
Add proper root selector to gcl2json
Add proper root selector to gcl2json
Python
mit
rix0rrr/gcl
import argparse import json import sys import gcl from gcl import query from gcl import util + def select(dct, path): + for part in path: + if not hasattr(dct, 'keys'): + raise RuntimeError('Value %r cannot be indexed with %r' % (dct, part)) + if part not in dct: + raise RuntimeError('Value %r has no key %r' % (dct, part)) + dct = dct[part] + return dct + + def main(argv=None, stdin=None): parser = argparse.ArgumentParser(description='Convert (parts of) a GCL model file to JSON.') parser.add_argument('file', metavar='FILE', type=str, nargs='?', help='File to parse') parser.add_argument('selectors', metavar='SELECTOR', type=str, nargs='*', - help='Subnodes to convert. The first selector will be treated as the root of the printed output.') + help='Select nodes to include in the JSON.') + parser.add_argument('--root', '-r', metavar='PATH', type=str, default='', + help='Use the indicated root path as the root of the output JSON object (like a.b.c but without wildcards)') args = parser.parse_args(argv or sys.argv[1:]) try: if args.file and args.file != '-': model = gcl.load(args.file) else: model = gcl.loads((stdin or sys.stdin).read(), filename='<stdin>') sels = query.GPath(args.selectors) if not sels.everything(): model = sels.select(model).deep() plain = util.to_python(model) + + selectors = args.root.split('.') if args.root else [] + selected = select(plain, selectors) + - sys.stdout.write(json.dumps(plain)) + sys.stdout.write(json.dumps(selected)) except (gcl.ParseError, RuntimeError) as e: sys.stderr.write(str(e) + '\n') sys.exit(1)
Add proper root selector to gcl2json
## Code Before: import argparse import json import sys import gcl from gcl import query from gcl import util def main(argv=None, stdin=None): parser = argparse.ArgumentParser(description='Convert (parts of) a GCL model file to JSON.') parser.add_argument('file', metavar='FILE', type=str, nargs='?', help='File to parse') parser.add_argument('selectors', metavar='SELECTOR', type=str, nargs='*', help='Subnodes to convert. The first selector will be treated as the root of the printed output.') args = parser.parse_args(argv or sys.argv[1:]) try: if args.file and args.file != '-': model = gcl.load(args.file) else: model = gcl.loads((stdin or sys.stdin).read(), filename='<stdin>') sels = query.GPath(args.selectors) if not sels.everything(): model = sels.select(model).deep() plain = util.to_python(model) sys.stdout.write(json.dumps(plain)) except (gcl.ParseError, RuntimeError) as e: sys.stderr.write(str(e) + '\n') sys.exit(1) ## Instruction: Add proper root selector to gcl2json ## Code After: import argparse import json import sys import gcl from gcl import query from gcl import util def select(dct, path): for part in path: if not hasattr(dct, 'keys'): raise RuntimeError('Value %r cannot be indexed with %r' % (dct, part)) if part not in dct: raise RuntimeError('Value %r has no key %r' % (dct, part)) dct = dct[part] return dct def main(argv=None, stdin=None): parser = argparse.ArgumentParser(description='Convert (parts of) a GCL model file to JSON.') parser.add_argument('file', metavar='FILE', type=str, nargs='?', help='File to parse') parser.add_argument('selectors', metavar='SELECTOR', type=str, nargs='*', help='Select nodes to include in the JSON.') parser.add_argument('--root', '-r', metavar='PATH', type=str, default='', help='Use the indicated root path as the root of the output JSON object (like a.b.c but without wildcards)') args = parser.parse_args(argv or sys.argv[1:]) try: if args.file and args.file != '-': model = gcl.load(args.file) else: model = gcl.loads((stdin or sys.stdin).read(), filename='<stdin>') sels = query.GPath(args.selectors) if not sels.everything(): model = sels.select(model).deep() plain = util.to_python(model) selectors = args.root.split('.') if args.root else [] selected = select(plain, selectors) sys.stdout.write(json.dumps(selected)) except (gcl.ParseError, RuntimeError) as e: sys.stderr.write(str(e) + '\n') sys.exit(1)
3c3e9b5f584c23c9359ca9dce71b89635fffd043
LiSE/LiSE/tests/test_load.py
LiSE/LiSE/tests/test_load.py
import os import shutil import pytest from LiSE.engine import Engine from LiSE.examples.kobold import inittest def test_keyframe_load_init(tempdir): """Can load a keyframe at start of branch, including locations""" eng = Engine(tempdir) inittest(eng) eng.branch = 'new' eng.snap_keyframe() eng.close() eng = Engine(tempdir) assert 'kobold' in eng.character['physical'].thing assert (0, 0) in eng.character['physical'].place assert (0, 1) in eng.character['physical'].portal[0, 0] eng.close() def test_multi_keyframe(tempdir): eng = Engine(tempdir) inittest(eng, kobold_pos=(9, 9)) eng.snap_keyframe() tick0 = eng.tick eng.turn = 1 eng.character['physical'].thing['kobold']['location'] = (3, 3) eng.snap_keyframe() tick1 = eng.tick eng.close() eng = Engine(tempdir) eng._load_at('trunk', 0, tick0+1) assert eng._things_cache.keyframe['physical']['trunk'][0][tick0]\ != eng._things_cache.keyframe['physical']['trunk'][1][tick1]
import os import shutil import pytest from LiSE.engine import Engine from LiSE.examples.kobold import inittest def test_keyframe_load_init(tempdir): """Can load a keyframe at start of branch, including locations""" eng = Engine(tempdir) inittest(eng) eng.branch = 'new' eng.snap_keyframe() eng.close() eng = Engine(tempdir) assert 'kobold' in eng.character['physical'].thing assert (0, 0) in eng.character['physical'].place assert (0, 1) in eng.character['physical'].portal[0, 0] eng.close() def test_multi_keyframe(tempdir): eng = Engine(tempdir) inittest(eng) eng.snap_keyframe() tick0 = eng.tick eng.turn = 1 del eng.character['physical'].place[3, 3] eng.snap_keyframe() tick1 = eng.tick eng.close() eng = Engine(tempdir) eng._load_at('trunk', 0, tick0+1) assert eng._nodes_cache.keyframe['physical', ]['trunk'][0][tick0]\ != eng._nodes_cache.keyframe['physical', ]['trunk'][1][tick1]
Make test_multi_keyframe demonstrate what it's supposed to
Make test_multi_keyframe demonstrate what it's supposed to I was testing a cache that wasn't behaving correctly for unrelated reasons.
Python
agpl-3.0
LogicalDash/LiSE,LogicalDash/LiSE
import os import shutil import pytest from LiSE.engine import Engine from LiSE.examples.kobold import inittest def test_keyframe_load_init(tempdir): """Can load a keyframe at start of branch, including locations""" eng = Engine(tempdir) inittest(eng) eng.branch = 'new' eng.snap_keyframe() eng.close() eng = Engine(tempdir) assert 'kobold' in eng.character['physical'].thing assert (0, 0) in eng.character['physical'].place assert (0, 1) in eng.character['physical'].portal[0, 0] eng.close() def test_multi_keyframe(tempdir): eng = Engine(tempdir) - inittest(eng, kobold_pos=(9, 9)) + inittest(eng) eng.snap_keyframe() tick0 = eng.tick eng.turn = 1 - eng.character['physical'].thing['kobold']['location'] = (3, 3) + del eng.character['physical'].place[3, 3] eng.snap_keyframe() tick1 = eng.tick eng.close() eng = Engine(tempdir) eng._load_at('trunk', 0, tick0+1) - assert eng._things_cache.keyframe['physical']['trunk'][0][tick0]\ + assert eng._nodes_cache.keyframe['physical', ]['trunk'][0][tick0]\ - != eng._things_cache.keyframe['physical']['trunk'][1][tick1] + != eng._nodes_cache.keyframe['physical', ]['trunk'][1][tick1]
Make test_multi_keyframe demonstrate what it's supposed to
## Code Before: import os import shutil import pytest from LiSE.engine import Engine from LiSE.examples.kobold import inittest def test_keyframe_load_init(tempdir): """Can load a keyframe at start of branch, including locations""" eng = Engine(tempdir) inittest(eng) eng.branch = 'new' eng.snap_keyframe() eng.close() eng = Engine(tempdir) assert 'kobold' in eng.character['physical'].thing assert (0, 0) in eng.character['physical'].place assert (0, 1) in eng.character['physical'].portal[0, 0] eng.close() def test_multi_keyframe(tempdir): eng = Engine(tempdir) inittest(eng, kobold_pos=(9, 9)) eng.snap_keyframe() tick0 = eng.tick eng.turn = 1 eng.character['physical'].thing['kobold']['location'] = (3, 3) eng.snap_keyframe() tick1 = eng.tick eng.close() eng = Engine(tempdir) eng._load_at('trunk', 0, tick0+1) assert eng._things_cache.keyframe['physical']['trunk'][0][tick0]\ != eng._things_cache.keyframe['physical']['trunk'][1][tick1] ## Instruction: Make test_multi_keyframe demonstrate what it's supposed to ## Code After: import os import shutil import pytest from LiSE.engine import Engine from LiSE.examples.kobold import inittest def test_keyframe_load_init(tempdir): """Can load a keyframe at start of branch, including locations""" eng = Engine(tempdir) inittest(eng) eng.branch = 'new' eng.snap_keyframe() eng.close() eng = Engine(tempdir) assert 'kobold' in eng.character['physical'].thing assert (0, 0) in eng.character['physical'].place assert (0, 1) in eng.character['physical'].portal[0, 0] eng.close() def test_multi_keyframe(tempdir): eng = Engine(tempdir) inittest(eng) eng.snap_keyframe() tick0 = eng.tick eng.turn = 1 del eng.character['physical'].place[3, 3] eng.snap_keyframe() tick1 = eng.tick eng.close() eng = Engine(tempdir) eng._load_at('trunk', 0, tick0+1) assert eng._nodes_cache.keyframe['physical', ]['trunk'][0][tick0]\ != eng._nodes_cache.keyframe['physical', ]['trunk'][1][tick1]
972cb7c234729d2ce8bbab0937f8efbfe18a2eeb
lab_members/models.py
lab_members/models.py
from django.db import models class Position(models.Model): class Meta: verbose_name = "Position" verbose_name_plural = "Positions" title = models.CharField(u'title', blank=False, default='', help_text=u'Please enter a title for this position', max_length=64, unique=True, ) def __str__(self): pass class Scientist(models.Model): class Meta: verbose_name = "Scientist" verbose_name_plural = "Scientists" full_name = models.CharField(u'full name', blank=False, default='', help_text=u'Please enter a full name for this scientist', max_length=64, unique=True, ) slug = models.SlugField(u'slug', blank=False, default='', help_text=u'Please enter a unique slug for this scientist', max_length=64, ) title = models.ForeignKey('lab_members.Position', blank=True, default=None, help_text=u'Please specify a title for this scientist', null=True, ) def __str__(self): pass
from django.db import models class Position(models.Model): class Meta: verbose_name = "Position" verbose_name_plural = "Positions" title = models.CharField(u'title', blank=False, default='', help_text=u'Please enter a title for this position', max_length=64, unique=True, ) def __str__(self): return self.title class Scientist(models.Model): class Meta: verbose_name = "Scientist" verbose_name_plural = "Scientists" full_name = models.CharField(u'full name', blank=False, default='', help_text=u'Please enter a full name for this scientist', max_length=64, unique=True, ) slug = models.SlugField(u'slug', blank=False, default='', help_text=u'Please enter a unique slug for this scientist', max_length=64, ) title = models.ForeignKey('lab_members.Position', blank=True, default=None, help_text=u'Please specify a title for this scientist', null=True, ) def __str__(self): return self.full_name
Fix error: __str__ returned non-string (type NoneType)
Fix error: __str__ returned non-string (type NoneType)
Python
bsd-3-clause
mfcovington/django-lab-members,mfcovington/django-lab-members,mfcovington/django-lab-members
from django.db import models class Position(models.Model): class Meta: verbose_name = "Position" verbose_name_plural = "Positions" title = models.CharField(u'title', blank=False, default='', help_text=u'Please enter a title for this position', max_length=64, unique=True, ) def __str__(self): - pass + return self.title class Scientist(models.Model): class Meta: verbose_name = "Scientist" verbose_name_plural = "Scientists" full_name = models.CharField(u'full name', blank=False, default='', help_text=u'Please enter a full name for this scientist', max_length=64, unique=True, ) slug = models.SlugField(u'slug', blank=False, default='', help_text=u'Please enter a unique slug for this scientist', max_length=64, ) title = models.ForeignKey('lab_members.Position', blank=True, default=None, help_text=u'Please specify a title for this scientist', null=True, ) def __str__(self): - pass + return self.full_name
Fix error: __str__ returned non-string (type NoneType)
## Code Before: from django.db import models class Position(models.Model): class Meta: verbose_name = "Position" verbose_name_plural = "Positions" title = models.CharField(u'title', blank=False, default='', help_text=u'Please enter a title for this position', max_length=64, unique=True, ) def __str__(self): pass class Scientist(models.Model): class Meta: verbose_name = "Scientist" verbose_name_plural = "Scientists" full_name = models.CharField(u'full name', blank=False, default='', help_text=u'Please enter a full name for this scientist', max_length=64, unique=True, ) slug = models.SlugField(u'slug', blank=False, default='', help_text=u'Please enter a unique slug for this scientist', max_length=64, ) title = models.ForeignKey('lab_members.Position', blank=True, default=None, help_text=u'Please specify a title for this scientist', null=True, ) def __str__(self): pass ## Instruction: Fix error: __str__ returned non-string (type NoneType) ## Code After: from django.db import models class Position(models.Model): class Meta: verbose_name = "Position" verbose_name_plural = "Positions" title = models.CharField(u'title', blank=False, default='', help_text=u'Please enter a title for this position', max_length=64, unique=True, ) def __str__(self): return self.title class Scientist(models.Model): class Meta: verbose_name = "Scientist" verbose_name_plural = "Scientists" full_name = models.CharField(u'full name', blank=False, default='', help_text=u'Please enter a full name for this scientist', max_length=64, unique=True, ) slug = models.SlugField(u'slug', blank=False, default='', help_text=u'Please enter a unique slug for this scientist', max_length=64, ) title = models.ForeignKey('lab_members.Position', blank=True, default=None, help_text=u'Please specify a title for this scientist', null=True, ) def __str__(self): return self.full_name
9ad049bdac489e5f500f8bf8ec0cd615ccacadbf
stack/logs.py
stack/logs.py
from troposphere import Join, iam, logs from .common import arn_prefix from .template import template container_log_group = logs.LogGroup( "ContainerLogs", template=template, RetentionInDays=365, DeletionPolicy="Retain", ) logging_policy = iam.Policy( PolicyName="LoggingPolicy", PolicyDocument=dict( Statement=[dict( Effect="Allow", Action=[ "logs:Create*", "logs:PutLogEvents", ], Resource=Join("", [ arn_prefix, ":logs:*:*:*", # allow logging to any log group ]), )], ), )
from troposphere import Join, iam, logs from .common import arn_prefix from .template import template container_log_group = logs.LogGroup( "ContainerLogs", template=template, RetentionInDays=365, DeletionPolicy="Retain", ) logging_policy = iam.Policy( PolicyName="LoggingPolicy", PolicyDocument=dict( Statement=[dict( Effect="Allow", Action=[ "logs:Create*", "logs:PutLogEvents", # Needed by aws-for-fluent-bit: "logs:DescribeLogGroups", "logs:DescribeLogStreams", ], Resource=Join("", [ arn_prefix, ":logs:*:*:*", # allow logging to any log group ]), )], ), )
Add logging permissions needed by aws-for-fluent-bit
Add logging permissions needed by aws-for-fluent-bit
Python
mit
tobiasmcnulty/aws-container-basics,caktus/aws-web-stacks
from troposphere import Join, iam, logs from .common import arn_prefix from .template import template container_log_group = logs.LogGroup( "ContainerLogs", template=template, RetentionInDays=365, DeletionPolicy="Retain", ) logging_policy = iam.Policy( PolicyName="LoggingPolicy", PolicyDocument=dict( Statement=[dict( Effect="Allow", Action=[ "logs:Create*", "logs:PutLogEvents", + # Needed by aws-for-fluent-bit: + "logs:DescribeLogGroups", + "logs:DescribeLogStreams", ], Resource=Join("", [ arn_prefix, ":logs:*:*:*", # allow logging to any log group ]), )], ), )
Add logging permissions needed by aws-for-fluent-bit
## Code Before: from troposphere import Join, iam, logs from .common import arn_prefix from .template import template container_log_group = logs.LogGroup( "ContainerLogs", template=template, RetentionInDays=365, DeletionPolicy="Retain", ) logging_policy = iam.Policy( PolicyName="LoggingPolicy", PolicyDocument=dict( Statement=[dict( Effect="Allow", Action=[ "logs:Create*", "logs:PutLogEvents", ], Resource=Join("", [ arn_prefix, ":logs:*:*:*", # allow logging to any log group ]), )], ), ) ## Instruction: Add logging permissions needed by aws-for-fluent-bit ## Code After: from troposphere import Join, iam, logs from .common import arn_prefix from .template import template container_log_group = logs.LogGroup( "ContainerLogs", template=template, RetentionInDays=365, DeletionPolicy="Retain", ) logging_policy = iam.Policy( PolicyName="LoggingPolicy", PolicyDocument=dict( Statement=[dict( Effect="Allow", Action=[ "logs:Create*", "logs:PutLogEvents", # Needed by aws-for-fluent-bit: "logs:DescribeLogGroups", "logs:DescribeLogStreams", ], Resource=Join("", [ arn_prefix, ":logs:*:*:*", # allow logging to any log group ]), )], ), )
e1ad3190e124163c0e7e0e7fc03cfea6f43f0cf8
stack/vpc.py
stack/vpc.py
from troposphere.ec2 import ( VPC, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", )
from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), )
Attach an `InternetGateway` to the `VPC`
Attach an `InternetGateway` to the `VPC`
Python
mit
tobiasmcnulty/aws-container-basics,caktus/aws-web-stacks
+ from troposphere import ( + Ref, + ) + from troposphere.ec2 import ( + InternetGateway, VPC, + VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) + + # Allow outgoing to outside VPC + internet_gateway = InternetGateway( + "InternetGateway", + template=template, + ) + + + # Attach Gateway to VPC + VPCGatewayAttachment( + "GatewayAttachement", + template=template, + VpcId=Ref(vpc), + InternetGatewayId=Ref(internet_gateway), + ) +
Attach an `InternetGateway` to the `VPC`
## Code Before: from troposphere.ec2 import ( VPC, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) ## Instruction: Attach an `InternetGateway` to the `VPC` ## Code After: from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( "Vpc", template=template, CidrBlock="10.0.0.0/16", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( "InternetGateway", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( "GatewayAttachement", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), )
92aeffe058bfd724309ddcdbdab9226057074afe
masters/master.chromium.lkgr/master_source_cfg.py
masters/master.chromium.lkgr/master_source_cfg.py
from buildbot.changes.pb import PBChangeSource def Update(config, active_master, c): # Polls config.Master.trunk_url for changes c['change_source'].append(PBChangeSource())
from master.url_poller import URLPoller LKGR_URL = 'https://chromium-status.appspot.com/lkgr' def Update(config, active_master, c): c['change_source'].append( URLPoller(changeurl=LKGR_URL, pollInterval=300, category='lkgr', include_revision=True))
Switch master.chromium.lkgr to poll the chromium-status app.
Switch master.chromium.lkgr to poll the chromium-status app. Using a PBChangeSource is silly, opaque, and potentially dangerous. We already have a URLPoller for exactly this use-case (already in use by chromium.endure) so let's use it here too. This also has the advantage of making sure the LKGR waterfall picks up *all* updates to LKGR, including manual ones. R=iannucci@chromium.org, phajdan.jr@chromium.org BUG=366954 Review URL: https://codereview.chromium.org/255753002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@266093 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
- from buildbot.changes.pb import PBChangeSource + from master.url_poller import URLPoller + + + LKGR_URL = 'https://chromium-status.appspot.com/lkgr' def Update(config, active_master, c): - # Polls config.Master.trunk_url for changes - c['change_source'].append(PBChangeSource()) + c['change_source'].append( + URLPoller(changeurl=LKGR_URL, pollInterval=300, + category='lkgr', include_revision=True))
Switch master.chromium.lkgr to poll the chromium-status app.
## Code Before: from buildbot.changes.pb import PBChangeSource def Update(config, active_master, c): # Polls config.Master.trunk_url for changes c['change_source'].append(PBChangeSource()) ## Instruction: Switch master.chromium.lkgr to poll the chromium-status app. ## Code After: from master.url_poller import URLPoller LKGR_URL = 'https://chromium-status.appspot.com/lkgr' def Update(config, active_master, c): c['change_source'].append( URLPoller(changeurl=LKGR_URL, pollInterval=300, category='lkgr', include_revision=True))
7fa20f228a673ee983af47910f10851c126a9308
src/foremast/plugin_manager.py
src/foremast/plugin_manager.py
from pluginbase import PluginBase class PluginManager: def __init__(self, paths, provider): self.paths = [paths] self.provider = provider plugin_base = PluginBase(package='foremast.plugins') self.plugin_source = plugin_base.make_plugin_source(searchpath=self.paths) def plugins(self): for plugin in self.plugin_source.list_plugins(): yield plugin def load(self): return self.plugin_source.load_plugin(self.provider)
"""Manager to handle plugins""" from pluginbase import PluginBase class PluginManager: """Class to manage and create Spinnaker applications Args: paths (str): Path of plugin directory. provider (str): The name of the cloud provider. """ def __init__(self, paths, provider): self.paths = [paths] self.provider = provider plugin_base = PluginBase(package='foremast.plugins') self.plugin_source = plugin_base.make_plugin_source(searchpath=self.paths) def plugins(self): """List of all plugins available.""" for plugin in self.plugin_source.list_plugins(): yield plugin def load(self): """Load the plugin object.""" return self.plugin_source.load_plugin(self.provider)
Add docstring to plugin manager
chore: Add docstring to plugin manager
Python
apache-2.0
gogoair/foremast,gogoair/foremast
+ """Manager to handle plugins""" from pluginbase import PluginBase class PluginManager: + """Class to manage and create Spinnaker applications + + Args: + paths (str): Path of plugin directory. + provider (str): The name of the cloud provider. + """ + def __init__(self, paths, provider): self.paths = [paths] self.provider = provider plugin_base = PluginBase(package='foremast.plugins') self.plugin_source = plugin_base.make_plugin_source(searchpath=self.paths) def plugins(self): + """List of all plugins available.""" for plugin in self.plugin_source.list_plugins(): yield plugin def load(self): + """Load the plugin object.""" return self.plugin_source.load_plugin(self.provider)
Add docstring to plugin manager
## Code Before: from pluginbase import PluginBase class PluginManager: def __init__(self, paths, provider): self.paths = [paths] self.provider = provider plugin_base = PluginBase(package='foremast.plugins') self.plugin_source = plugin_base.make_plugin_source(searchpath=self.paths) def plugins(self): for plugin in self.plugin_source.list_plugins(): yield plugin def load(self): return self.plugin_source.load_plugin(self.provider) ## Instruction: Add docstring to plugin manager ## Code After: """Manager to handle plugins""" from pluginbase import PluginBase class PluginManager: """Class to manage and create Spinnaker applications Args: paths (str): Path of plugin directory. provider (str): The name of the cloud provider. """ def __init__(self, paths, provider): self.paths = [paths] self.provider = provider plugin_base = PluginBase(package='foremast.plugins') self.plugin_source = plugin_base.make_plugin_source(searchpath=self.paths) def plugins(self): """List of all plugins available.""" for plugin in self.plugin_source.list_plugins(): yield plugin def load(self): """Load the plugin object.""" return self.plugin_source.load_plugin(self.provider)
a2ced7a752c033cef1a1da1fb246b99f0895f86a
src/objectdictionary.py
src/objectdictionary.py
import collections class ObjectDictionary(collections.Mapping): def __init__(self): self.names = {} self.ids = {} @classmethod def initialize(edsPath): pass def __setitem__(self,key,value): pass def __getitem__(self,key): pass def __iter__(): pass def __len__(): pass if __name__ == '__main__': cow = ObjectDictionary()
import collections class ObjectDictionary(collections.Mapping): def __init__(self): self.names = {} self.ids = {} @classmethod def initialize(edsPath): pass def __setitem__(self,key,value): if type(key) is str: self.names[key] = value else: self.ids[key] = value def __getitem__(self,key): if type(key) is str: return self.names[key] else: return self.ids[key] def __iter__(self): for objitem in self.ids: yield objitem def __len__(self): return len(self.ids) if __name__ == '__main__': test = ObjectDictionary()
Add Mapping methods to ObjectDictionary
Add Mapping methods to ObjectDictionary
Python
mit
aceofwings/Evt-Gateway,aceofwings/Evt-Gateway
import collections class ObjectDictionary(collections.Mapping): def __init__(self): self.names = {} self.ids = {} @classmethod def initialize(edsPath): pass def __setitem__(self,key,value): - pass + if type(key) is str: + self.names[key] = value + else: + self.ids[key] = value def __getitem__(self,key): - pass + if type(key) is str: + return self.names[key] + else: + return self.ids[key] - def __iter__(): - pass + def __iter__(self): + for objitem in self.ids: + yield objitem + + - def __len__(): + def __len__(self): - pass + return len(self.ids) if __name__ == '__main__': - cow = ObjectDictionary() + test = ObjectDictionary()
Add Mapping methods to ObjectDictionary
## Code Before: import collections class ObjectDictionary(collections.Mapping): def __init__(self): self.names = {} self.ids = {} @classmethod def initialize(edsPath): pass def __setitem__(self,key,value): pass def __getitem__(self,key): pass def __iter__(): pass def __len__(): pass if __name__ == '__main__': cow = ObjectDictionary() ## Instruction: Add Mapping methods to ObjectDictionary ## Code After: import collections class ObjectDictionary(collections.Mapping): def __init__(self): self.names = {} self.ids = {} @classmethod def initialize(edsPath): pass def __setitem__(self,key,value): if type(key) is str: self.names[key] = value else: self.ids[key] = value def __getitem__(self,key): if type(key) is str: return self.names[key] else: return self.ids[key] def __iter__(self): for objitem in self.ids: yield objitem def __len__(self): return len(self.ids) if __name__ == '__main__': test = ObjectDictionary()
f0861ff6c817f1f683e69cf362336545ff3d9148
ledger/admin.py
ledger/admin.py
from django.contrib import admin from ledger.models import Account, Entry class EntryAdmin(admin.ModelAdmin): list_display = ['date', 'amount', 'details', 'debit_account', 'credit_account'] list_filter = ['date'] admin.site.register(Entry, EntryAdmin) admin.site.register(Account)
from django.contrib import admin from ledger.models import Account, Entry class EntryAdmin(admin.ModelAdmin): list_display = ['date', 'amount', 'details', 'debit_account', 'credit_account'] list_filter = ['date', 'debit_account', 'credit_account'] search_fields = ['details', 'debit_account__name', 'credit_account__name'] ordering = ['-date'] admin.site.register(Entry, EntryAdmin) admin.site.register(Account)
Add a little more functionality to EntryAdmin
Add a little more functionality to EntryAdmin
Python
mpl-2.0
jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django
from django.contrib import admin from ledger.models import Account, Entry class EntryAdmin(admin.ModelAdmin): list_display = ['date', 'amount', 'details', 'debit_account', 'credit_account'] - list_filter = ['date'] + list_filter = ['date', 'debit_account', 'credit_account'] + search_fields = ['details', 'debit_account__name', 'credit_account__name'] + ordering = ['-date'] admin.site.register(Entry, EntryAdmin) admin.site.register(Account)
Add a little more functionality to EntryAdmin
## Code Before: from django.contrib import admin from ledger.models import Account, Entry class EntryAdmin(admin.ModelAdmin): list_display = ['date', 'amount', 'details', 'debit_account', 'credit_account'] list_filter = ['date'] admin.site.register(Entry, EntryAdmin) admin.site.register(Account) ## Instruction: Add a little more functionality to EntryAdmin ## Code After: from django.contrib import admin from ledger.models import Account, Entry class EntryAdmin(admin.ModelAdmin): list_display = ['date', 'amount', 'details', 'debit_account', 'credit_account'] list_filter = ['date', 'debit_account', 'credit_account'] search_fields = ['details', 'debit_account__name', 'credit_account__name'] ordering = ['-date'] admin.site.register(Entry, EntryAdmin) admin.site.register(Account)
1e7361f46f551a2e897040ae47b43cdd5263d328
dataactcore/models/field.py
dataactcore/models/field.py
class FieldType: """ Acts as an enum for field types """ INTEGER = "INTEGER" TEXT = "TEXT" class FieldConstraint: """ Acts a an enum for field constraints """ NONE = "" PRIMARY_KEY = "PRIMARY KEY" NOT_NULL = "NOT NULL"
class FieldType: """ Acts as an enum for field types """ INTEGER = "INTEGER" TEXT = "TEXT"
Remove FieldConstraint class (not used)
Remove FieldConstraint class (not used)
Python
cc0-1.0
fedspendingtransparency/data-act-broker-backend,fedspendingtransparency/data-act-broker-backend
class FieldType: """ Acts as an enum for field types """ INTEGER = "INTEGER" TEXT = "TEXT" - class FieldConstraint: - """ Acts a an enum for field constraints """ - NONE = "" - PRIMARY_KEY = "PRIMARY KEY" - NOT_NULL = "NOT NULL"
Remove FieldConstraint class (not used)
## Code Before: class FieldType: """ Acts as an enum for field types """ INTEGER = "INTEGER" TEXT = "TEXT" class FieldConstraint: """ Acts a an enum for field constraints """ NONE = "" PRIMARY_KEY = "PRIMARY KEY" NOT_NULL = "NOT NULL" ## Instruction: Remove FieldConstraint class (not used) ## Code After: class FieldType: """ Acts as an enum for field types """ INTEGER = "INTEGER" TEXT = "TEXT"
07ee6957d20a1c02b22ed5d91d20211506e7ca54
partner_feeds/templatetags/partner_feed_tags.py
partner_feeds/templatetags/partner_feed_tags.py
from django import template from partner_feeds.models import Partner register = template.Library() @register.assignment_tag def get_partners(*args): partners = [] for name in args: try: partner = Partner.objects.get(name=name) except Partner.DoesNotExist: continue partner.posts = partner.post_set.all().order_by('-date') partners.append(partner) return partners
from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners
Update `get_partners` assignment tag to reduce the number of queries
Update `get_partners` assignment tag to reduce the number of queries Maintains the same interface so no other changes should be required
Python
bsd-2-clause
theatlantic/django-partner-feeds
from django import template - from partner_feeds.models import Partner + from partner_feeds.models import Partner, Post register = template.Library() + @register.assignment_tag - def get_partners(*args): + def get_partners(*partner_names): - partners = [] - for name in args: - try: - partner = Partner.objects.get(name=name) - except Partner.DoesNotExist: - continue - partner.posts = partner.post_set.all().order_by('-date') - partners.append(partner) + """ + Given a list of partner names, return those partners with posts attached to + them in the order that they were passed to this function + + """ + partners = list(Partner.objects.filter(name__in=partner_names)) + for partner in partners: + partner.posts = Post.objects.filter(partner=partner) + partners.sort(key=lambda p: partner_names.index(p.name)) return partners +
Update `get_partners` assignment tag to reduce the number of queries
## Code Before: from django import template from partner_feeds.models import Partner register = template.Library() @register.assignment_tag def get_partners(*args): partners = [] for name in args: try: partner = Partner.objects.get(name=name) except Partner.DoesNotExist: continue partner.posts = partner.post_set.all().order_by('-date') partners.append(partner) return partners ## Instruction: Update `get_partners` assignment tag to reduce the number of queries ## Code After: from django import template from partner_feeds.models import Partner, Post register = template.Library() @register.assignment_tag def get_partners(*partner_names): """ Given a list of partner names, return those partners with posts attached to them in the order that they were passed to this function """ partners = list(Partner.objects.filter(name__in=partner_names)) for partner in partners: partner.posts = Post.objects.filter(partner=partner) partners.sort(key=lambda p: partner_names.index(p.name)) return partners
7dbc1359ea4fb1b725fd53869a218856e4dec701
lswapi/httpie/__init__.py
lswapi/httpie/__init__.py
from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(self.client_id, self.client_secret, __auth_token_url__) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(__auth_token_url__, self.client_id, self.client_secret) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
Fix for function signature change in 0.4.0 in fetch_access_token
Fix for function signature change in 0.4.0 in fetch_access_token
Python
apache-2.0
nrocco/lswapi
from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r - token = fetch_access_token(self.client_id, self.client_secret, __auth_token_url__) + token = fetch_access_token(__auth_token_url__, self.client_id, self.client_secret) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
Fix for function signature change in 0.4.0 in fetch_access_token
## Code Before: from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(self.client_id, self.client_secret, __auth_token_url__) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password) ## Instruction: Fix for function signature change in 0.4.0 in fetch_access_token ## Code After: from json import loads, dumps from time import time from os import path from lswapi import __auth_token_url__, __token_store__, fetch_access_token from requests import post from httpie.plugins import AuthPlugin class LswApiAuth(object): def __init__(self, client_id, client_secret): self.client_id = client_id self.client_secret = client_secret def __call__(self, r): if path.exists(__token_store__): with open(__token_store__, 'r') as file: token = loads(file.read()) if 'expires_at' in token and token['expires_at'] > time(): r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r token = fetch_access_token(__auth_token_url__, self.client_id, self.client_secret) with open(__token_store__, 'w') as file: file.write(dumps(token)) r.headers['Authorization'] = '{token_type} {access_token}'.format(**token) return r class ApiAuthPlugin(AuthPlugin): name = 'LswApi Oauth' auth_type = 'lswapi' description = 'LeaseWeb Api Oauth Authentication' def get_auth(self, username, password): return LswApiAuth(username, password)
c0ec6a6a799ab86562b07326eeaf21da4fd23dff
rejected/log.py
rejected/log.py
import logging class CorrelationFilter(logging.Formatter): """Filter records that have a correlation_id""" def __init__(self, exists=None): super(CorrelationFilter, self).__init__() self.exists = exists def filter(self, record): if self.exists: return hasattr(record, 'correlation_id') return not hasattr(record, 'correlation_id') class CorrelationAdapter(logging.LoggerAdapter): """A LoggerAdapter that appends the a correlation ID to the message record properties. """ def __init__(self, logger, consumer): self.logger = logger self.consumer = consumer def process(self, msg, kwargs): """Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict) """ kwargs['extra'] = {'correlation_id': self.consumer.correlation_id} return msg, kwargs
import logging class CorrelationFilter(logging.Formatter): """Filter records that have a correlation_id""" def __init__(self, exists=None): super(CorrelationFilter, self).__init__() self.exists = exists def filter(self, record): if self.exists: return hasattr(record, 'correlation_id') return not hasattr(record, 'correlation_id') class CorrelationAdapter(logging.LoggerAdapter): """A LoggerAdapter that appends the a correlation ID to the message record properties. """ def __init__(self, logger, consumer): self.logger = logger self.consumer = consumer def process(self, msg, kwargs): """Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict) """ kwargs['extra'] = {'correlation_id': self.consumer.correlation_id, 'consumer': self.consumer.name} return msg, kwargs
Add the consumer name to the extra values
Add the consumer name to the extra values
Python
bsd-3-clause
gmr/rejected,gmr/rejected
import logging class CorrelationFilter(logging.Formatter): """Filter records that have a correlation_id""" def __init__(self, exists=None): super(CorrelationFilter, self).__init__() self.exists = exists def filter(self, record): if self.exists: return hasattr(record, 'correlation_id') return not hasattr(record, 'correlation_id') class CorrelationAdapter(logging.LoggerAdapter): """A LoggerAdapter that appends the a correlation ID to the message record properties. """ def __init__(self, logger, consumer): self.logger = logger self.consumer = consumer def process(self, msg, kwargs): """Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict) """ - kwargs['extra'] = {'correlation_id': self.consumer.correlation_id} + kwargs['extra'] = {'correlation_id': self.consumer.correlation_id, + 'consumer': self.consumer.name} return msg, kwargs
Add the consumer name to the extra values
## Code Before: import logging class CorrelationFilter(logging.Formatter): """Filter records that have a correlation_id""" def __init__(self, exists=None): super(CorrelationFilter, self).__init__() self.exists = exists def filter(self, record): if self.exists: return hasattr(record, 'correlation_id') return not hasattr(record, 'correlation_id') class CorrelationAdapter(logging.LoggerAdapter): """A LoggerAdapter that appends the a correlation ID to the message record properties. """ def __init__(self, logger, consumer): self.logger = logger self.consumer = consumer def process(self, msg, kwargs): """Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict) """ kwargs['extra'] = {'correlation_id': self.consumer.correlation_id} return msg, kwargs ## Instruction: Add the consumer name to the extra values ## Code After: import logging class CorrelationFilter(logging.Formatter): """Filter records that have a correlation_id""" def __init__(self, exists=None): super(CorrelationFilter, self).__init__() self.exists = exists def filter(self, record): if self.exists: return hasattr(record, 'correlation_id') return not hasattr(record, 'correlation_id') class CorrelationAdapter(logging.LoggerAdapter): """A LoggerAdapter that appends the a correlation ID to the message record properties. """ def __init__(self, logger, consumer): self.logger = logger self.consumer = consumer def process(self, msg, kwargs): """Process the logging message and keyword arguments passed in to a logging call to insert contextual information. :param str msg: The message to process :param dict kwargs: The kwargs to append :rtype: (str, dict) """ kwargs['extra'] = {'correlation_id': self.consumer.correlation_id, 'consumer': self.consumer.name} return msg, kwargs
63db2005911abae96eb170af0dd93093cbfeae38
nimp/utilities/ue4.py
nimp/utilities/ue4.py
import socket import random import string import time import contextlib import shutil import os from nimp.utilities.build import * from nimp.utilities.deployment import * #--------------------------------------------------------------------------- def ue4_build(env): vs_version = '12' vcxproj = 'Engine/Intermediate/ProjectFiles/' + env.game + '.vcxproj' if _ue4_generate_project() != 0: log_error("[nimp] Error generating UE4 project files") return False if env.ue4_build_platform == 'PS4': ps4_vcxproj = 'Engine/Intermediate/ProjectFiles/PS4MapFileUtil.vcxproj' if not _ue4_build_project(env.solution, ps4_vcxproj, 'Win64', env.configuration, vs_version, 'Build'): log_error("[nimp] Could not build PS4MapFileUtil.exe") return False return _ue4_build_project(env.solution, vcxproj, env.ue4_build_platform, env.configuration, vs_version, 'Build') #--------------------------------------------------------------------------- def _ue4_generate_project(): return call_process('.', ['./GenerateProjectFiles.bat']) #--------------------------------------------------------------------------- def _ue4_build_project(sln_file, project, build_platform, configuration, vs_version, target = 'Rebuild'): return vsbuild(sln_file, build_platform, configuration, project, vs_version, target)
import socket import random import string import time import contextlib import shutil import os from nimp.utilities.build import * from nimp.utilities.deployment import * #--------------------------------------------------------------------------- def ue4_build(env): vs_version = '12' if _ue4_generate_project() != 0: log_error("[nimp] Error generating UE4 project files") return False if env.ue4_build_platform == 'PS4': if not _ue4_build_project(env.solution, 'PS4MapFileUtil', 'Win64', env.configuration, vs_version, 'Build'): log_error("[nimp] Could not build PS4MapFileUtil.exe") return False return _ue4_build_project(env.solution, env.game, env.ue4_build_platform, env.configuration, vs_version, 'Build') #--------------------------------------------------------------------------- def _ue4_generate_project(): return call_process('.', ['./GenerateProjectFiles.bat']) #--------------------------------------------------------------------------- def _ue4_build_project(sln_file, project, build_platform, configuration, vs_version, target = 'Rebuild'): return vsbuild(sln_file, build_platform, configuration, project, vs_version, target)
Build UE4 projects by name rather than by full path.
Build UE4 projects by name rather than by full path.
Python
mit
dontnod/nimp
import socket import random import string import time import contextlib import shutil import os from nimp.utilities.build import * from nimp.utilities.deployment import * #--------------------------------------------------------------------------- def ue4_build(env): vs_version = '12' - vcxproj = 'Engine/Intermediate/ProjectFiles/' + env.game + '.vcxproj' if _ue4_generate_project() != 0: log_error("[nimp] Error generating UE4 project files") return False if env.ue4_build_platform == 'PS4': - ps4_vcxproj = 'Engine/Intermediate/ProjectFiles/PS4MapFileUtil.vcxproj' - if not _ue4_build_project(env.solution, ps4_vcxproj, 'Win64', + if not _ue4_build_project(env.solution, 'PS4MapFileUtil', 'Win64', env.configuration, vs_version, 'Build'): log_error("[nimp] Could not build PS4MapFileUtil.exe") return False - return _ue4_build_project(env.solution, vcxproj, env.ue4_build_platform, + return _ue4_build_project(env.solution, env.game, env.ue4_build_platform, env.configuration, vs_version, 'Build') #--------------------------------------------------------------------------- def _ue4_generate_project(): return call_process('.', ['./GenerateProjectFiles.bat']) #--------------------------------------------------------------------------- def _ue4_build_project(sln_file, project, build_platform, configuration, vs_version, target = 'Rebuild'): return vsbuild(sln_file, build_platform, configuration, project, vs_version, target)
Build UE4 projects by name rather than by full path.
## Code Before: import socket import random import string import time import contextlib import shutil import os from nimp.utilities.build import * from nimp.utilities.deployment import * #--------------------------------------------------------------------------- def ue4_build(env): vs_version = '12' vcxproj = 'Engine/Intermediate/ProjectFiles/' + env.game + '.vcxproj' if _ue4_generate_project() != 0: log_error("[nimp] Error generating UE4 project files") return False if env.ue4_build_platform == 'PS4': ps4_vcxproj = 'Engine/Intermediate/ProjectFiles/PS4MapFileUtil.vcxproj' if not _ue4_build_project(env.solution, ps4_vcxproj, 'Win64', env.configuration, vs_version, 'Build'): log_error("[nimp] Could not build PS4MapFileUtil.exe") return False return _ue4_build_project(env.solution, vcxproj, env.ue4_build_platform, env.configuration, vs_version, 'Build') #--------------------------------------------------------------------------- def _ue4_generate_project(): return call_process('.', ['./GenerateProjectFiles.bat']) #--------------------------------------------------------------------------- def _ue4_build_project(sln_file, project, build_platform, configuration, vs_version, target = 'Rebuild'): return vsbuild(sln_file, build_platform, configuration, project, vs_version, target) ## Instruction: Build UE4 projects by name rather than by full path. ## Code After: import socket import random import string import time import contextlib import shutil import os from nimp.utilities.build import * from nimp.utilities.deployment import * #--------------------------------------------------------------------------- def ue4_build(env): vs_version = '12' if _ue4_generate_project() != 0: log_error("[nimp] Error generating UE4 project files") return False if env.ue4_build_platform == 'PS4': if not _ue4_build_project(env.solution, 'PS4MapFileUtil', 'Win64', env.configuration, vs_version, 'Build'): log_error("[nimp] Could not build PS4MapFileUtil.exe") return False return _ue4_build_project(env.solution, env.game, env.ue4_build_platform, env.configuration, vs_version, 'Build') #--------------------------------------------------------------------------- def _ue4_generate_project(): return call_process('.', ['./GenerateProjectFiles.bat']) #--------------------------------------------------------------------------- def _ue4_build_project(sln_file, project, build_platform, configuration, vs_version, target = 'Rebuild'): return vsbuild(sln_file, build_platform, configuration, project, vs_version, target)
11cb3adf0beb19abebbf8345b9244dbcc0f51ca7
autopoke.py
autopoke.py
from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_id('email').send_keys(input('Email: ')) driver.find_element_by_id('pass').send_keys(getpass()) driver.find_element_by_id('loginbutton').click() driver.get('https://facebook.com/pokes/') assert "Forgot password?" not in driver.page_source c = 0 c2 = 0 while True: try: for i in driver.find_elements_by_link_text("Poke Back"): i.click() c += 1 print("Clicked so far: " + str(c)) except StaleElementReferenceException: driver.get('https://facebook.com/pokes/') sleep(0.5)
from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_id('email').send_keys(input('Email: ')) driver.find_element_by_id('pass').send_keys(getpass()) driver.find_element_by_id('loginbutton').click() driver.get('https://facebook.com/pokes/') assert "Forgot password?" not in driver.page_source c = 0 while True: try: for i in driver.find_elements_by_link_text("Poke Back"): i.click() c += 1 print("Clicked so far: " + str(c)) except StaleElementReferenceException: print("Found exception, reloading page") driver.get('https://facebook.com/pokes/') sleep(0.5)
Add notice on page reload
Add notice on page reload
Python
mit
matthewbentley/autopoke
from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_id('email').send_keys(input('Email: ')) driver.find_element_by_id('pass').send_keys(getpass()) driver.find_element_by_id('loginbutton').click() driver.get('https://facebook.com/pokes/') assert "Forgot password?" not in driver.page_source c = 0 - c2 = 0 while True: try: for i in driver.find_elements_by_link_text("Poke Back"): i.click() c += 1 print("Clicked so far: " + str(c)) except StaleElementReferenceException: + print("Found exception, reloading page") driver.get('https://facebook.com/pokes/') sleep(0.5)
Add notice on page reload
## Code Before: from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_id('email').send_keys(input('Email: ')) driver.find_element_by_id('pass').send_keys(getpass()) driver.find_element_by_id('loginbutton').click() driver.get('https://facebook.com/pokes/') assert "Forgot password?" not in driver.page_source c = 0 c2 = 0 while True: try: for i in driver.find_elements_by_link_text("Poke Back"): i.click() c += 1 print("Clicked so far: " + str(c)) except StaleElementReferenceException: driver.get('https://facebook.com/pokes/') sleep(0.5) ## Instruction: Add notice on page reload ## Code After: from selenium import webdriver from selenium.common.exceptions import StaleElementReferenceException from time import sleep from getpass import getpass if __name__ == '__main__': driver = webdriver.phantomjs.webdriver.WebDriver() driver.get('https://facebook.com') driver.find_element_by_id('email').send_keys(input('Email: ')) driver.find_element_by_id('pass').send_keys(getpass()) driver.find_element_by_id('loginbutton').click() driver.get('https://facebook.com/pokes/') assert "Forgot password?" not in driver.page_source c = 0 while True: try: for i in driver.find_elements_by_link_text("Poke Back"): i.click() c += 1 print("Clicked so far: " + str(c)) except StaleElementReferenceException: print("Found exception, reloading page") driver.get('https://facebook.com/pokes/') sleep(0.5)
ccfc5e8681eef5e382b6c31abce540cbe179f7b2
tests/factories/user.py
tests/factories/user.py
import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner') class UserWithMembershipFactory(UserFactory): membership = factory.RelatedFactory('tests.factories.property.MembershipFactory', 'user')
import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at for key, value in kwargs.items(): setattr(rhe, key, value) class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner') class UserWithMembershipFactory(UserFactory): membership = factory.RelatedFactory('tests.factories.property.MembershipFactory', 'user')
Allow adjusting of RoomHistoryEntry attributes in UserFactory
Allow adjusting of RoomHistoryEntry attributes in UserFactory
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at + for key, value in kwargs.items(): + setattr(rhe, key, value) + class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner') class UserWithMembershipFactory(UserFactory): membership = factory.RelatedFactory('tests.factories.property.MembershipFactory', 'user')
Allow adjusting of RoomHistoryEntry attributes in UserFactory
## Code Before: import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner') class UserWithMembershipFactory(UserFactory): membership = factory.RelatedFactory('tests.factories.property.MembershipFactory', 'user') ## Instruction: Allow adjusting of RoomHistoryEntry attributes in UserFactory ## Code After: import factory from factory.faker import Faker from pycroft.model.user import User, RoomHistoryEntry from .base import BaseFactory from .facilities import RoomFactory from .finance import AccountFactory class UserFactory(BaseFactory): class Meta: model = User login = Faker('user_name') name = Faker('name') registered_at = Faker('date_time') password = Faker('password') email = Faker('email') account = factory.SubFactory(AccountFactory, type="USER_ASSET") room = factory.SubFactory(RoomFactory) address = factory.SelfAttribute('room.address') @factory.post_generation def room_history_entries(self, create, extracted, **kwargs): if self.room is not None: # Set room history entry begin to registration date rhe = RoomHistoryEntry.q.filter_by(user=self, room=self.room).one() rhe.begins_at = self.registered_at for key, value in kwargs.items(): setattr(rhe, key, value) class UserWithHostFactory(UserFactory): host = factory.RelatedFactory('tests.factories.host.HostFactory', 'owner') class UserWithMembershipFactory(UserFactory): membership = factory.RelatedFactory('tests.factories.property.MembershipFactory', 'user')
e86f62edb2edf9dd5d20eb2bf89b09c76807de50
tests/cupy_tests/core_tests/test_array_function.py
tests/cupy_tests/core_tests/test_array_function.py
import unittest import numpy import six import cupy from cupy import testing @testing.gpu class TestArrayFunction(unittest.TestCase): @testing.with_requires('numpy>=1.17.0') def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray(a) # The numpy call for both CPU and GPU arrays is intentional to test the # __array_function__ protocol qr_cpu = numpy.linalg.qr(a_cpu) qr_gpu = numpy.linalg.qr(a_gpu) if isinstance(qr_cpu, tuple): for b_cpu, b_gpu in six.moves.zip(qr_cpu, qr_gpu): self.assertEqual(b_cpu.dtype, b_gpu.dtype) cupy.testing.assert_allclose(b_cpu, b_gpu, atol=1e-4) else: self.assertEqual(qr_cpu.dtype, qr_gpu.dtype) cupy.testing.assert_allclose(qr_cpu, qr_gpu, atol=1e-4)
import unittest import numpy import six import cupy from cupy import testing @testing.gpu class TestArrayFunction(unittest.TestCase): @testing.with_requires('numpy>=1.17.0') def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray(a) # The numpy call for both CPU and GPU arrays is intentional to test the # __array_function__ protocol qr_cpu = numpy.linalg.qr(a_cpu) qr_gpu = numpy.linalg.qr(a_gpu) if isinstance(qr_cpu, tuple): for b_cpu, b_gpu in six.moves.zip(qr_cpu, qr_gpu): self.assertEqual(b_cpu.dtype, b_gpu.dtype) cupy.testing.assert_allclose(b_cpu, b_gpu, atol=1e-4) else: self.assertEqual(qr_cpu.dtype, qr_gpu.dtype) cupy.testing.assert_allclose(qr_cpu, qr_gpu, atol=1e-4) @testing.numpy_cupy_equal() def test_array_function_can_cast(self, xp): return numpy.can_cast(xp.arange(2), 'f4') @testing.numpy_cupy_equal() def test_array_function_common_type(self, xp): return numpy.common_type(xp.arange(2, dtype='f8'), xp.arange(2, dtype='f4')) @testing.numpy_cupy_equal() def test_array_function_result_type(self, xp): return numpy.result_type(3, xp.arange(2, dtype='f8'))
Add tests for NumPy _implementation usage
Add tests for NumPy _implementation usage
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
import unittest import numpy import six import cupy from cupy import testing @testing.gpu class TestArrayFunction(unittest.TestCase): @testing.with_requires('numpy>=1.17.0') def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray(a) # The numpy call for both CPU and GPU arrays is intentional to test the # __array_function__ protocol qr_cpu = numpy.linalg.qr(a_cpu) qr_gpu = numpy.linalg.qr(a_gpu) if isinstance(qr_cpu, tuple): for b_cpu, b_gpu in six.moves.zip(qr_cpu, qr_gpu): self.assertEqual(b_cpu.dtype, b_gpu.dtype) cupy.testing.assert_allclose(b_cpu, b_gpu, atol=1e-4) else: self.assertEqual(qr_cpu.dtype, qr_gpu.dtype) cupy.testing.assert_allclose(qr_cpu, qr_gpu, atol=1e-4) + @testing.numpy_cupy_equal() + def test_array_function_can_cast(self, xp): + return numpy.can_cast(xp.arange(2), 'f4') + + @testing.numpy_cupy_equal() + def test_array_function_common_type(self, xp): + return numpy.common_type(xp.arange(2, dtype='f8'), xp.arange(2, dtype='f4')) + + @testing.numpy_cupy_equal() + def test_array_function_result_type(self, xp): + return numpy.result_type(3, xp.arange(2, dtype='f8')) +
Add tests for NumPy _implementation usage
## Code Before: import unittest import numpy import six import cupy from cupy import testing @testing.gpu class TestArrayFunction(unittest.TestCase): @testing.with_requires('numpy>=1.17.0') def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray(a) # The numpy call for both CPU and GPU arrays is intentional to test the # __array_function__ protocol qr_cpu = numpy.linalg.qr(a_cpu) qr_gpu = numpy.linalg.qr(a_gpu) if isinstance(qr_cpu, tuple): for b_cpu, b_gpu in six.moves.zip(qr_cpu, qr_gpu): self.assertEqual(b_cpu.dtype, b_gpu.dtype) cupy.testing.assert_allclose(b_cpu, b_gpu, atol=1e-4) else: self.assertEqual(qr_cpu.dtype, qr_gpu.dtype) cupy.testing.assert_allclose(qr_cpu, qr_gpu, atol=1e-4) ## Instruction: Add tests for NumPy _implementation usage ## Code After: import unittest import numpy import six import cupy from cupy import testing @testing.gpu class TestArrayFunction(unittest.TestCase): @testing.with_requires('numpy>=1.17.0') def test_array_function(self): a = numpy.random.randn(100, 100) a_cpu = numpy.asarray(a) a_gpu = cupy.asarray(a) # The numpy call for both CPU and GPU arrays is intentional to test the # __array_function__ protocol qr_cpu = numpy.linalg.qr(a_cpu) qr_gpu = numpy.linalg.qr(a_gpu) if isinstance(qr_cpu, tuple): for b_cpu, b_gpu in six.moves.zip(qr_cpu, qr_gpu): self.assertEqual(b_cpu.dtype, b_gpu.dtype) cupy.testing.assert_allclose(b_cpu, b_gpu, atol=1e-4) else: self.assertEqual(qr_cpu.dtype, qr_gpu.dtype) cupy.testing.assert_allclose(qr_cpu, qr_gpu, atol=1e-4) @testing.numpy_cupy_equal() def test_array_function_can_cast(self, xp): return numpy.can_cast(xp.arange(2), 'f4') @testing.numpy_cupy_equal() def test_array_function_common_type(self, xp): return numpy.common_type(xp.arange(2, dtype='f8'), xp.arange(2, dtype='f4')) @testing.numpy_cupy_equal() def test_array_function_result_type(self, xp): return numpy.result_type(3, xp.arange(2, dtype='f8'))
a9a2c13cf947de9bc8ed50a38da5f7191b86ae23
accounts/tests/test_views.py
accounts/tests/test_views.py
from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. """ response = self.client.get('/') self.assertTemplateUsed(response, 'accounts/welcome.html') class SendLoginEmailTest(TestCase): """Tests for the view which sends the login email. """ def setUp(self): self.url = reverse('send_login_email') self.test_email = 'newvisitor@example.com' def test_uses_emailsent_template(self): """The send_login_email url responds with login_email_sent template. """ response = self.client.post(self.url, data={'email': self.test_email}) self.assertTemplateUsed(response, 'accounts/login_email_sent.html') def test_get_request_yields_405(self): """Accessing the view via get request is not allowed. """ response = self.client.get(self.url) self.assertEqual(response.status_code, 405)
from django.test import TestCase from django.core import mail from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. """ response = self.client.get('/') self.assertTemplateUsed(response, 'accounts/welcome.html') class SendLoginEmailTest(TestCase): """Tests for the view which sends the login email. """ def setUp(self): self.url = reverse('send_login_email') self.test_email = 'newvisitor@example.com' def test_uses_emailsent_template(self): """The send_login_email url responds with login_email_sent template. """ response = self.client.post(self.url, data={'email': self.test_email}) self.assertTemplateUsed(response, 'accounts/login_email_sent.html') def test_get_request_yields_405(self): """Accessing the view via get request is not allowed. """ response = self.client.get(self.url) self.assertEqual(response.status_code, 405) def test_view_sends_token_email(self): """The view should send an email to the email address from post. """ self.client.post(self.url, data={'email': self.test_email}) self.assertEqual(len(mail.outbox), 1)
Add trivial test for the view to send an email
Add trivial test for the view to send an email
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
from django.test import TestCase + from django.core import mail from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. """ response = self.client.get('/') self.assertTemplateUsed(response, 'accounts/welcome.html') class SendLoginEmailTest(TestCase): """Tests for the view which sends the login email. """ def setUp(self): self.url = reverse('send_login_email') self.test_email = 'newvisitor@example.com' def test_uses_emailsent_template(self): """The send_login_email url responds with login_email_sent template. """ response = self.client.post(self.url, data={'email': self.test_email}) self.assertTemplateUsed(response, 'accounts/login_email_sent.html') def test_get_request_yields_405(self): """Accessing the view via get request is not allowed. """ response = self.client.get(self.url) self.assertEqual(response.status_code, 405) + def test_view_sends_token_email(self): + """The view should send an email to the email address from post. + """ + self.client.post(self.url, data={'email': self.test_email}) + self.assertEqual(len(mail.outbox), 1) +
Add trivial test for the view to send an email
## Code Before: from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. """ response = self.client.get('/') self.assertTemplateUsed(response, 'accounts/welcome.html') class SendLoginEmailTest(TestCase): """Tests for the view which sends the login email. """ def setUp(self): self.url = reverse('send_login_email') self.test_email = 'newvisitor@example.com' def test_uses_emailsent_template(self): """The send_login_email url responds with login_email_sent template. """ response = self.client.post(self.url, data={'email': self.test_email}) self.assertTemplateUsed(response, 'accounts/login_email_sent.html') def test_get_request_yields_405(self): """Accessing the view via get request is not allowed. """ response = self.client.get(self.url) self.assertEqual(response.status_code, 405) ## Instruction: Add trivial test for the view to send an email ## Code After: from django.test import TestCase from django.core import mail from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. """ response = self.client.get('/') self.assertTemplateUsed(response, 'accounts/welcome.html') class SendLoginEmailTest(TestCase): """Tests for the view which sends the login email. """ def setUp(self): self.url = reverse('send_login_email') self.test_email = 'newvisitor@example.com' def test_uses_emailsent_template(self): """The send_login_email url responds with login_email_sent template. """ response = self.client.post(self.url, data={'email': self.test_email}) self.assertTemplateUsed(response, 'accounts/login_email_sent.html') def test_get_request_yields_405(self): """Accessing the view via get request is not allowed. """ response = self.client.get(self.url) self.assertEqual(response.status_code, 405) def test_view_sends_token_email(self): """The view should send an email to the email address from post. """ self.client.post(self.url, data={'email': self.test_email}) self.assertEqual(len(mail.outbox), 1)
018f8e7c7c69eefeb121c8552eb319b4b550f251
backslash/error_container.py
backslash/error_container.py
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'exception': exception, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
from sentinels import NOTHING class ErrorContainer(object): def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'message': message, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
Unify errors and failures in API
Unify errors and failures in API
Python
bsd-3-clause
vmalloc/backslash-python,slash-testing/backslash-python
from sentinels import NOTHING class ErrorContainer(object): - def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): + def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, - 'exception': exception, + 'message': message, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
Unify errors and failures in API
## Code Before: from sentinels import NOTHING class ErrorContainer(object): def add_error(self, exception, exception_type, traceback, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'exception': exception, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id' ## Instruction: Unify errors and failures in API ## Code After: from sentinels import NOTHING class ErrorContainer(object): def add_error(self, message, exception_type=NOTHING, traceback=NOTHING, timestamp=NOTHING): return self.client.api.call_function('add_error', {self._get_id_key(): self.id, 'message': message, 'exception_type': exception_type, 'traceback': traceback, 'timestamp': timestamp }) def _get_id_key(self): if type(self).__name__ == 'Test': return 'test_id' return 'session_id'
75a27c416effd2958182b1401e49d6613a28857d
sana_builder/webapp/models.py
sana_builder/webapp/models.py
from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) uuid = models.IntegerField(null=True) version = models.CharField(max_length=50, null=True) owner = models.ForeignKey(User, unique=True) class Page(models.Model): procedure = models.ForeignKey(Procedure)
from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) uuid = models.IntegerField(null=True, unique=True) version = models.CharField(max_length=50, null=True) owner = models.ForeignKey(User, unique=True) class Page(models.Model): procedure = models.ForeignKey(Procedure)
Make uuid on procedures unique
Make uuid on procedures unique
Python
bsd-3-clause
SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder,SanaMobile/sana.protocol_builder
from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) - uuid = models.IntegerField(null=True) + uuid = models.IntegerField(null=True, unique=True) version = models.CharField(max_length=50, null=True) owner = models.ForeignKey(User, unique=True) class Page(models.Model): procedure = models.ForeignKey(Procedure)
Make uuid on procedures unique
## Code Before: from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) uuid = models.IntegerField(null=True) version = models.CharField(max_length=50, null=True) owner = models.ForeignKey(User, unique=True) class Page(models.Model): procedure = models.ForeignKey(Procedure) ## Instruction: Make uuid on procedures unique ## Code After: from django.db import models from django.contrib.auth.models import User class Procedure(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) uuid = models.IntegerField(null=True, unique=True) version = models.CharField(max_length=50, null=True) owner = models.ForeignKey(User, unique=True) class Page(models.Model): procedure = models.ForeignKey(Procedure)
ad1203b9b93d1be499698807e2307413c20bb573
cisco_olt_http/tests/test_operations.py
cisco_olt_http/tests/test_operations.py
from cisco_olt_http import operations
from cisco_olt_http import operations from cisco_olt_http.client import Client def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data
Add simple test for operation get_data
Add simple test for operation get_data
Python
mit
beezz/cisco-olt-http-client,Vnet-as/cisco-olt-http-client
from cisco_olt_http import operations + from cisco_olt_http.client import Client + + def test_get_data(): + client = Client('http://base-url') + show_equipment_op = operations.ShowEquipmentOp(client) + op_data = show_equipment_op.get_data() + assert op_data +
Add simple test for operation get_data
## Code Before: from cisco_olt_http import operations ## Instruction: Add simple test for operation get_data ## Code After: from cisco_olt_http import operations from cisco_olt_http.client import Client def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data
f3eeb19249fae51a5537735cd5966596194cdc36
pages/widgets_registry.py
pages/widgets_registry.py
__all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise AlreadyRegistered( _('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
__all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise WidgetAlreadyRegistered(_('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
Fix widget registry exception handling code
Fix widget registry exception handling code
Python
bsd-3-clause
batiste/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,oliciv/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,oliciv/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,remik/django-page-cms
__all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: - raise AlreadyRegistered( - _('The widget %s has already been registered.') % widget.__name__) + raise WidgetAlreadyRegistered(_('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
Fix widget registry exception handling code
## Code Before: __all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise AlreadyRegistered( _('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name) ## Instruction: Fix widget registry exception handling code ## Code After: __all__ = ('register_widget',) from django.utils.translation import ugettext as _ class WidgetAlreadyRegistered(Exception): """ An attempt was made to register a widget for Django page CMS more than once. """ pass class WidgetNotFound(Exception): """ The requested widget was not found """ pass registry = [] def register_widget(widget): if widget in registry: raise WidgetAlreadyRegistered(_('The widget %s has already been registered.') % widget.__name__) registry.append(widget) def get_widget(name): for widget in registry: if widget.__name__ == name: return widget raise WidgetNotFound( _('The widget %s has not been registered.') % name)
3ac86b4c058f920c9ec774c192d84050d61c8cc3
tests/__init__.py
tests/__init__.py
import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: os.remove(os.path.join("tests/resources", path)) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else: os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
Fix bug; os.remove cannot remove directories
Fix bug; os.remove cannot remove directories
Python
mit
koji-kojiro/hylang-hycc
import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: - os.remove(os.path.join("tests/resources", path)) + path = os.path.join("tests/resources", path) + if os.path.isdir(path): + os.rmdir(path) + else: + os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
Fix bug; os.remove cannot remove directories
## Code Before: import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: os.remove(os.path.join("tests/resources", path)) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean() ## Instruction: Fix bug; os.remove cannot remove directories ## Code After: import os from hycc.util import hycc_main def clean(): for path in os.listdir("tests/resources"): if path not in ["hello.hy", "__init__.py"]: path = os.path.join("tests/resources", path) if os.path.isdir(path): os.rmdir(path) else: os.remove(path) def test_build_executable(): hycc_main("tests/resources/hello.hy".split()) assert os.path.exists("tests/resources/hello") clean() def test_shared_library(): hycc_main("tests/resources/hello.hy --shared".split()) from tests.resources.hello import hello assert hello() == "hello" clean()
f4cfad2edaa896b471f4f44b2a3fda2bd6b1bb49
tests/conftest.py
tests/conftest.py
import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) @app.route('/ping') def ping(): return jsonify(ping='pong') return app
import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app
Add index route to test application
Add index route to test application This endpoint uses to start :class:`LiveServer` instance with minimum waiting timeout.
Python
mit
amateja/pytest-flask
import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) + @app.route('/') + def index(): + return app.response_class('OK') + @app.route('/ping') def ping(): return jsonify(ping='pong') return app
Add index route to test application
## Code Before: import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) @app.route('/ping') def ping(): return jsonify(ping='pong') return app ## Instruction: Add index route to test application ## Code After: import pytest from flask import Flask, jsonify @pytest.fixture def app(): app = Flask(__name__) @app.route('/') def index(): return app.response_class('OK') @app.route('/ping') def ping(): return jsonify(ping='pong') return app
dff2120a65daacfb1add8da604483f354abcefa2
src/pygrapes/serializer/__init__.py
src/pygrapes/serializer/__init__.py
from abstract import Abstract from json import Json from msgpack import MsgPack __all__ = ['Abstract', 'Json', 'MsgPack']
from pygrapes.serializer.abstract import Abstract from pygrapes.serializer.json import Json from pygrapes.serializer.msgpack import MsgPack __all__ = ['Abstract', 'Json', 'MsgPack']
Load resources by absolute path not relative
Load resources by absolute path not relative
Python
bsd-3-clause
michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes
- from abstract import Abstract - from json import Json - from msgpack import MsgPack + from pygrapes.serializer.abstract import Abstract + from pygrapes.serializer.json import Json + from pygrapes.serializer.msgpack import MsgPack __all__ = ['Abstract', 'Json', 'MsgPack']
Load resources by absolute path not relative
## Code Before: from abstract import Abstract from json import Json from msgpack import MsgPack __all__ = ['Abstract', 'Json', 'MsgPack'] ## Instruction: Load resources by absolute path not relative ## Code After: from pygrapes.serializer.abstract import Abstract from pygrapes.serializer.json import Json from pygrapes.serializer.msgpack import MsgPack __all__ = ['Abstract', 'Json', 'MsgPack']
ff37a13d1adec1fe685bd48964ab50ef000f53f5
loom/config.py
loom/config.py
from fabric.api import env, run, sudo, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_puppet_version = '3.1.1' # Default librarian version # If loom_librarian_version is None, loom installs the latest version env.loom_librarian_version = '0.9.9' def host_roles(host_string): """ Returns the role of a given host string. """ roles = set() for role, hosts in env.roledefs.items(): if host_string in hosts: roles.add(role) return list(roles) def current_roles(): return host_roles(env.host_string) def has_puppet_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): result = sudo('which puppet') return result.succeeded def has_librarian_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): librarian = sudo('which librarian-puppet') return librarian.succeeded
from fabric.api import env, run, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_puppet_version = '3.1.1' # Default librarian version # If loom_librarian_version is None, loom installs the latest version env.loom_librarian_version = '0.9.9' def host_roles(host_string): """ Returns the role of a given host string. """ roles = set() for role, hosts in env.roledefs.items(): if host_string in hosts: roles.add(role) return list(roles) def current_roles(): return host_roles(env.host_string) def has_puppet_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): result = run('which puppet') return result.succeeded def has_librarian_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): librarian = run('which librarian-puppet') return librarian.succeeded
Revert "sudo is required to run which <gem-exec> on arch."
Revert "sudo is required to run which <gem-exec> on arch." This reverts commit 15162c58c27bc84f1c7fc0326f782bd693ca4d7e.
Python
bsd-3-clause
nithinphilips/loom,nithinphilips/loom
- from fabric.api import env, run, sudo, settings, hide + from fabric.api import env, run, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_puppet_version = '3.1.1' # Default librarian version # If loom_librarian_version is None, loom installs the latest version env.loom_librarian_version = '0.9.9' def host_roles(host_string): """ Returns the role of a given host string. """ roles = set() for role, hosts in env.roledefs.items(): if host_string in hosts: roles.add(role) return list(roles) def current_roles(): return host_roles(env.host_string) def has_puppet_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): - result = sudo('which puppet') + result = run('which puppet') return result.succeeded def has_librarian_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): - librarian = sudo('which librarian-puppet') + librarian = run('which librarian-puppet') return librarian.succeeded
Revert "sudo is required to run which <gem-exec> on arch."
## Code Before: from fabric.api import env, run, sudo, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_puppet_version = '3.1.1' # Default librarian version # If loom_librarian_version is None, loom installs the latest version env.loom_librarian_version = '0.9.9' def host_roles(host_string): """ Returns the role of a given host string. """ roles = set() for role, hosts in env.roledefs.items(): if host_string in hosts: roles.add(role) return list(roles) def current_roles(): return host_roles(env.host_string) def has_puppet_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): result = sudo('which puppet') return result.succeeded def has_librarian_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): librarian = sudo('which librarian-puppet') return librarian.succeeded ## Instruction: Revert "sudo is required to run which <gem-exec> on arch." ## Code After: from fabric.api import env, run, settings, hide # Default system user env.user = 'ubuntu' # Default puppet environment env.environment = 'prod' # Default puppet module directory env.puppet_module_dir = 'modules/' # Default puppet version # If loom_puppet_version is None, loom installs the latest version env.loom_puppet_version = '3.1.1' # Default librarian version # If loom_librarian_version is None, loom installs the latest version env.loom_librarian_version = '0.9.9' def host_roles(host_string): """ Returns the role of a given host string. """ roles = set() for role, hosts in env.roledefs.items(): if host_string in hosts: roles.add(role) return list(roles) def current_roles(): return host_roles(env.host_string) def has_puppet_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): result = run('which puppet') return result.succeeded def has_librarian_installed(): with settings(hide('warnings', 'running', 'stdout', 'stderr'), warn_only=True): librarian = run('which librarian-puppet') return librarian.succeeded
4b88dff3df0c82392314efe9c48379e1ad2b1500
vinotes/apps/api/serializers.py
vinotes/apps/api/serializers.py
from django.contrib.auth.models import User from rest_framework import serializers from .models import Note, Trait, Wine, Winery class WinerySerializer(serializers.ModelSerializer): wines = serializers.PrimaryKeyRelatedField(many=True, queryset=Wine.objects.all()) class Meta: model = Winery fields = ('id', 'name', 'wines') class WineSerializer(serializers.ModelSerializer): class Meta: model = Wine fields = ('id', 'winery', 'name', 'vintage') class TraitSerializer(serializers.ModelSerializer): class Meta: model = Trait fields = ('id', 'name') class NoteSerializer(serializers.ModelSerializer): taster = serializers.ReadOnlyField(source='taster.username') class Meta: model = Note fields = ('id', 'taster', 'tasted', 'wine', 'color_traits', 'nose_traits', 'taste_traits', 'finish_traits', 'rating') class UserSerializer(serializers.ModelSerializer): notes = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) class Meta: model = User fields = ('id', 'username', 'email', 'notes')
from django.contrib.auth.models import User from rest_framework import serializers from .models import Note, Trait, Wine, Winery class WinerySerializer(serializers.ModelSerializer): wines = serializers.PrimaryKeyRelatedField(many=True, queryset=Wine.objects.all()) class Meta: model = Winery fields = ('id', 'name', 'wines') class WineSerializer(serializers.ModelSerializer): class Meta: model = Wine fields = ('id', 'winery', 'name', 'vintage') class TraitSerializer(serializers.ModelSerializer): color_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) nose_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) taste_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) finish_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) class Meta: model = Trait fields = ('id', 'name', 'color_traits', 'nose_traits', 'taste_traits', 'finish_traits') class NoteSerializer(serializers.ModelSerializer): taster = serializers.ReadOnlyField(source='taster.username') class Meta: model = Note fields = ('id', 'taster', 'tasted', 'wine', 'color_traits', 'nose_traits', 'taste_traits', 'finish_traits', 'rating') class UserSerializer(serializers.ModelSerializer): notes = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) class Meta: model = User fields = ('id', 'username', 'email', 'notes')
Add trait's wines to serializer.
Add trait's wines to serializer.
Python
unlicense
rcutmore/vinotes-api,rcutmore/vinotes-api
from django.contrib.auth.models import User from rest_framework import serializers from .models import Note, Trait, Wine, Winery class WinerySerializer(serializers.ModelSerializer): wines = serializers.PrimaryKeyRelatedField(many=True, queryset=Wine.objects.all()) class Meta: model = Winery fields = ('id', 'name', 'wines') class WineSerializer(serializers.ModelSerializer): class Meta: model = Wine fields = ('id', 'winery', 'name', 'vintage') class TraitSerializer(serializers.ModelSerializer): + color_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) + nose_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) + taste_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) + finish_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) + + class Meta: model = Trait - fields = ('id', 'name') + fields = ('id', 'name', 'color_traits', + 'nose_traits', 'taste_traits', 'finish_traits') class NoteSerializer(serializers.ModelSerializer): taster = serializers.ReadOnlyField(source='taster.username') class Meta: model = Note fields = ('id', 'taster', 'tasted', 'wine', 'color_traits', 'nose_traits', 'taste_traits', 'finish_traits', 'rating') class UserSerializer(serializers.ModelSerializer): notes = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) class Meta: model = User fields = ('id', 'username', 'email', 'notes')
Add trait's wines to serializer.
## Code Before: from django.contrib.auth.models import User from rest_framework import serializers from .models import Note, Trait, Wine, Winery class WinerySerializer(serializers.ModelSerializer): wines = serializers.PrimaryKeyRelatedField(many=True, queryset=Wine.objects.all()) class Meta: model = Winery fields = ('id', 'name', 'wines') class WineSerializer(serializers.ModelSerializer): class Meta: model = Wine fields = ('id', 'winery', 'name', 'vintage') class TraitSerializer(serializers.ModelSerializer): class Meta: model = Trait fields = ('id', 'name') class NoteSerializer(serializers.ModelSerializer): taster = serializers.ReadOnlyField(source='taster.username') class Meta: model = Note fields = ('id', 'taster', 'tasted', 'wine', 'color_traits', 'nose_traits', 'taste_traits', 'finish_traits', 'rating') class UserSerializer(serializers.ModelSerializer): notes = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) class Meta: model = User fields = ('id', 'username', 'email', 'notes') ## Instruction: Add trait's wines to serializer. ## Code After: from django.contrib.auth.models import User from rest_framework import serializers from .models import Note, Trait, Wine, Winery class WinerySerializer(serializers.ModelSerializer): wines = serializers.PrimaryKeyRelatedField(many=True, queryset=Wine.objects.all()) class Meta: model = Winery fields = ('id', 'name', 'wines') class WineSerializer(serializers.ModelSerializer): class Meta: model = Wine fields = ('id', 'winery', 'name', 'vintage') class TraitSerializer(serializers.ModelSerializer): color_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) nose_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) taste_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) finish_traits = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) class Meta: model = Trait fields = ('id', 'name', 'color_traits', 'nose_traits', 'taste_traits', 'finish_traits') class NoteSerializer(serializers.ModelSerializer): taster = serializers.ReadOnlyField(source='taster.username') class Meta: model = Note fields = ('id', 'taster', 'tasted', 'wine', 'color_traits', 'nose_traits', 'taste_traits', 'finish_traits', 'rating') class UserSerializer(serializers.ModelSerializer): notes = serializers.PrimaryKeyRelatedField(many=True, queryset=Note.objects.all()) class Meta: model = User fields = ('id', 'username', 'email', 'notes')
a34c594a13a79a864d1b747d84a0074e7711dd42
testanalyzer/pythonanalyzer.py
testanalyzer/pythonanalyzer.py
import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("class [a-zA-Z0-9_]+\(?[a-zA-Z0-9_, ]*\)?:", content)) def get_function_count(self, content): return len( re.findall("def [a-zA-Z0-9_]+\([a-zA-Z0-9_, ]*\):", content))
import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content)) def get_function_count(self, content): return len( re.findall("def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:", content))
Update regex to allow spaces
Update regex to allow spaces
Python
mpl-2.0
CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer
import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( - re.findall("class [a-zA-Z0-9_]+\(?[a-zA-Z0-9_, ]*\)?:", content)) + re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content)) def get_function_count(self, content): return len( - re.findall("def [a-zA-Z0-9_]+\([a-zA-Z0-9_, ]*\):", content)) + re.findall("def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:", content))
Update regex to allow spaces
## Code Before: import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("class [a-zA-Z0-9_]+\(?[a-zA-Z0-9_, ]*\)?:", content)) def get_function_count(self, content): return len( re.findall("def [a-zA-Z0-9_]+\([a-zA-Z0-9_, ]*\):", content)) ## Instruction: Update regex to allow spaces ## Code After: import re from fileanalyzer import FileAnalyzer class PythonAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:", content)) def get_function_count(self, content): return len( re.findall("def +[a-zA-Z0-9_]+ *\([a-zA-Z0-9_, ]*\) *:", content))
3d8f642460cf5c26dd8f58a5a36786b3ef4069e8
ogusa/tests/test_txfunc.py
ogusa/tests/test_txfunc.py
import pickle from ogusa import txfunc def test_cps_data(): with open("../../regression/cps_test_replace_outliers.pkl", 'rb') as p: param_arr = pickle.load(p) sse_big_mat = pickle.load(p) txfunc.replace_outliers(param_arr, sse_big_mat)
from ogusa import txfunc import numpy as np import pickle import os CUR_PATH = os.path.abspath(os.path.dirname(__file__)) def test_replace_outliers(): """ 4 cases: s is an outlier and is 0 s is an outlier and is in the interior (s > 0 and s < S) s is not an outlier but the first s - 1 ages were (s = 1 in our case) s is an outlier and is the max age """ S = 20 BW = 2 numparams = 5 param_arr = np.random.rand(S * BW * numparams).reshape(S, BW, numparams) sse_big_mat = ~ np.ones((S, BW), dtype=bool) sse_big_mat[0, 0] = True sse_big_mat[1, 0] = True sse_big_mat[S-11, 0] = True sse_big_mat[S-10, 0] = True sse_big_mat[S - 2, 0] = True sse_big_mat[S - 1, 0] = True txfunc.replace_outliers(param_arr, sse_big_mat)
Use simulated data for test
Use simulated data for test
Python
mit
OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic,OpenSourcePolicyCenter/dynamic
- import pickle from ogusa import txfunc - def test_cps_data(): - with open("../../regression/cps_test_replace_outliers.pkl", 'rb') as p: - param_arr = pickle.load(p) - sse_big_mat = pickle.load(p) + import numpy as np + import pickle + import os + + CUR_PATH = os.path.abspath(os.path.dirname(__file__)) + + def test_replace_outliers(): + """ + 4 cases: + s is an outlier and is 0 + s is an outlier and is in the interior (s > 0 and s < S) + s is not an outlier but the first s - 1 ages were (s = 1 in our case) + s is an outlier and is the max age + """ + S = 20 + BW = 2 + numparams = 5 + param_arr = np.random.rand(S * BW * numparams).reshape(S, BW, numparams) + sse_big_mat = ~ np.ones((S, BW), dtype=bool) + sse_big_mat[0, 0] = True + sse_big_mat[1, 0] = True + sse_big_mat[S-11, 0] = True + sse_big_mat[S-10, 0] = True + sse_big_mat[S - 2, 0] = True + sse_big_mat[S - 1, 0] = True txfunc.replace_outliers(param_arr, sse_big_mat)
Use simulated data for test
## Code Before: import pickle from ogusa import txfunc def test_cps_data(): with open("../../regression/cps_test_replace_outliers.pkl", 'rb') as p: param_arr = pickle.load(p) sse_big_mat = pickle.load(p) txfunc.replace_outliers(param_arr, sse_big_mat) ## Instruction: Use simulated data for test ## Code After: from ogusa import txfunc import numpy as np import pickle import os CUR_PATH = os.path.abspath(os.path.dirname(__file__)) def test_replace_outliers(): """ 4 cases: s is an outlier and is 0 s is an outlier and is in the interior (s > 0 and s < S) s is not an outlier but the first s - 1 ages were (s = 1 in our case) s is an outlier and is the max age """ S = 20 BW = 2 numparams = 5 param_arr = np.random.rand(S * BW * numparams).reshape(S, BW, numparams) sse_big_mat = ~ np.ones((S, BW), dtype=bool) sse_big_mat[0, 0] = True sse_big_mat[1, 0] = True sse_big_mat[S-11, 0] = True sse_big_mat[S-10, 0] = True sse_big_mat[S - 2, 0] = True sse_big_mat[S - 1, 0] = True txfunc.replace_outliers(param_arr, sse_big_mat)
d92c2dba7e549cee8059ecf4f1017956a630cd7a
web3/utils/validation.py
web3/utils/validation.py
from eth_utils import ( is_address, is_checksum_address, is_checksum_formatted_address, is_dict, is_list_like, ) def validate_abi(abi): """ Helper function for validating an ABI """ if not is_list_like(abi): raise ValueError("'abi' is not a list") for e in abi: if not is_dict(e): raise ValueError("The elements of 'abi' are not all dictionaries") def validate_address(value): """ Helper function for validating an address """ if not is_address(value): raise ValueError("'{0}' is not an address".format(value)) validate_address_checksum(value) def validate_address_checksum(value): """ Helper function for validating an address EIP55 checksum """ if is_checksum_formatted_address(value): if not is_checksum_address(value): raise ValueError("'{0}' has an invalid EIP55 checksum".format(value))
from eth_utils import ( is_address, is_checksum_address, is_checksum_formatted_address, is_dict, is_list_like, ) def validate_abi(abi): """ Helper function for validating an ABI """ if not is_list_like(abi): raise ValueError("'abi' is not a list") for e in abi: if not is_dict(e): raise ValueError("The elements of 'abi' are not all dictionaries") def validate_address(value): """ Helper function for validating an address """ validate_address_checksum(value) if not is_address(value): raise ValueError("'{0}' is not an address".format(value)) def validate_address_checksum(value): """ Helper function for validating an address EIP55 checksum """ if is_checksum_formatted_address(value): if not is_checksum_address(value): raise ValueError("'{0}' has an invalid EIP55 checksum".format(value))
Raise error specific to address checksum failure
Raise error specific to address checksum failure Because is_address() also checks for a valid checksum, the old code showed a generic "not an address" error if the checksum failed.
Python
mit
pipermerriam/web3.py
from eth_utils import ( is_address, is_checksum_address, is_checksum_formatted_address, is_dict, is_list_like, ) def validate_abi(abi): """ Helper function for validating an ABI """ if not is_list_like(abi): raise ValueError("'abi' is not a list") for e in abi: if not is_dict(e): raise ValueError("The elements of 'abi' are not all dictionaries") def validate_address(value): """ Helper function for validating an address """ + validate_address_checksum(value) if not is_address(value): raise ValueError("'{0}' is not an address".format(value)) - validate_address_checksum(value) def validate_address_checksum(value): """ Helper function for validating an address EIP55 checksum """ if is_checksum_formatted_address(value): if not is_checksum_address(value): raise ValueError("'{0}' has an invalid EIP55 checksum".format(value))
Raise error specific to address checksum failure
## Code Before: from eth_utils import ( is_address, is_checksum_address, is_checksum_formatted_address, is_dict, is_list_like, ) def validate_abi(abi): """ Helper function for validating an ABI """ if not is_list_like(abi): raise ValueError("'abi' is not a list") for e in abi: if not is_dict(e): raise ValueError("The elements of 'abi' are not all dictionaries") def validate_address(value): """ Helper function for validating an address """ if not is_address(value): raise ValueError("'{0}' is not an address".format(value)) validate_address_checksum(value) def validate_address_checksum(value): """ Helper function for validating an address EIP55 checksum """ if is_checksum_formatted_address(value): if not is_checksum_address(value): raise ValueError("'{0}' has an invalid EIP55 checksum".format(value)) ## Instruction: Raise error specific to address checksum failure ## Code After: from eth_utils import ( is_address, is_checksum_address, is_checksum_formatted_address, is_dict, is_list_like, ) def validate_abi(abi): """ Helper function for validating an ABI """ if not is_list_like(abi): raise ValueError("'abi' is not a list") for e in abi: if not is_dict(e): raise ValueError("The elements of 'abi' are not all dictionaries") def validate_address(value): """ Helper function for validating an address """ validate_address_checksum(value) if not is_address(value): raise ValueError("'{0}' is not an address".format(value)) def validate_address_checksum(value): """ Helper function for validating an address EIP55 checksum """ if is_checksum_formatted_address(value): if not is_checksum_address(value): raise ValueError("'{0}' has an invalid EIP55 checksum".format(value))
6a827bee5263c9bb5d34d6ac971581c62e827e7d
pinax/comments/models.py
pinax/comments/models.py
from datetime import datetime from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.CharField(max_length=255, blank=True) website = models.CharField(max_length=255, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.IntegerField() content_object = GenericForeignKey() comment = models.TextField() submit_date = models.DateTimeField(default=datetime.now) ip_address = models.GenericIPAddressField(null=True) public = models.BooleanField(default=True) @property def data(self): return { "pk": self.pk, "comment": self.comment, "author": self.author.username if self.author else "", "name": self.name, "email": self.email, "website": self.website, "submit_date": str(self.submit_date) } def __str__(self): return "pk=%d" % self.pk # pragma: no cover
from datetime import datetime from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.CharField(max_length=255, blank=True) website = models.CharField(max_length=255, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.IntegerField() content_object = GenericForeignKey() comment = models.TextField() submit_date = models.DateTimeField(default=datetime.now) ip_address = models.GenericIPAddressField(null=True) public = models.BooleanField(default=True) @property def data(self): return { "pk": self.pk, "comment": self.comment, "author": self.author.username if self.author else "", "name": self.name, "email": self.email, "website": self.website, "submit_date": str(self.submit_date) } def __str__(self): return "pk=%d" % self.pk # pragma: no cover
Change syntax to drop support
Change syntax to drop support
Python
mit
pinax/pinax-comments,pinax/pinax-comments,eldarion/dialogos
from datetime import datetime from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models - from django.utils.encoding import python_2_unicode_compatible - @python_2_unicode_compatible class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.CharField(max_length=255, blank=True) website = models.CharField(max_length=255, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.IntegerField() content_object = GenericForeignKey() comment = models.TextField() submit_date = models.DateTimeField(default=datetime.now) ip_address = models.GenericIPAddressField(null=True) public = models.BooleanField(default=True) @property def data(self): return { "pk": self.pk, "comment": self.comment, "author": self.author.username if self.author else "", "name": self.name, "email": self.email, "website": self.website, "submit_date": str(self.submit_date) } def __str__(self): return "pk=%d" % self.pk # pragma: no cover
Change syntax to drop support
## Code Before: from datetime import datetime from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.CharField(max_length=255, blank=True) website = models.CharField(max_length=255, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.IntegerField() content_object = GenericForeignKey() comment = models.TextField() submit_date = models.DateTimeField(default=datetime.now) ip_address = models.GenericIPAddressField(null=True) public = models.BooleanField(default=True) @property def data(self): return { "pk": self.pk, "comment": self.comment, "author": self.author.username if self.author else "", "name": self.name, "email": self.email, "website": self.website, "submit_date": str(self.submit_date) } def __str__(self): return "pk=%d" % self.pk # pragma: no cover ## Instruction: Change syntax to drop support ## Code After: from datetime import datetime from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Comment(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.CharField(max_length=255, blank=True) website = models.CharField(max_length=255, blank=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.IntegerField() content_object = GenericForeignKey() comment = models.TextField() submit_date = models.DateTimeField(default=datetime.now) ip_address = models.GenericIPAddressField(null=True) public = models.BooleanField(default=True) @property def data(self): return { "pk": self.pk, "comment": self.comment, "author": self.author.username if self.author else "", "name": self.name, "email": self.email, "website": self.website, "submit_date": str(self.submit_date) } def __str__(self): return "pk=%d" % self.pk # pragma: no cover
af51ef98d8575e7832d79c1068c092d388866dcb
donut/donut_SMTP_handler.py
donut/donut_SMTP_handler.py
from logging.handlers import SMTPHandler DEV_TEAM_EMAILS_QUERY = '''SELECT DISTINCT email FROM members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups WHERE group_name = "Devteam" ''' class DonutSMTPHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, db_instance, credentials=None, secure=None, timeout=5.0): super().__init__(mailhost, fromaddr, toaddrs, subject, credentials, secure, timeout) self.db_instance = db_instance def emit(self, record): ''' Overrides SMTPHandler's emit such that we dynamically get current donut dev team members ''' self.toaddrs = self.getAdmins() super().emit(record) def getAdmins(self): ''' Returns current members in Devteam ''' with self.db_instance.cursor() as cursor: cursor.execute(DEV_TEAM_EMAILS_QUERY, []) res = cursor.fetchall() return [result['email'] for result in res]
from logging.handlers import SMTPHandler DEV_TEAM_EMAILS_QUERY = '''SELECT DISTINCT email FROM members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups WHERE group_name = "Devteam" ''' DEFAULT_DEV_TEAM_EMAILS = ['devteam@donut.caltech.edu'] class DonutSMTPHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, db_instance, credentials=None, secure=None, timeout=5.0): super().__init__(mailhost, fromaddr, toaddrs, subject, credentials, secure, timeout) self.db_instance = db_instance def emit(self, record): ''' Overrides SMTPHandler's emit such that we dynamically get current donut dev team members ''' self.toaddrs = self.getAdmins() super().emit(record) def getAdmins(self): ''' Returns current members in Devteam ''' try: with self.db_instance.cursor() as cursor: cursor.execute(DEV_TEAM_EMAILS_QUERY) res = cursor.fetchall() return [result['email'] for result in res] except Exception: # If the database is inaccessible, fallback to a hard-coded email list return DEFAULT_DEV_TEAM_EMAILS
Allow error email to still be sent if DB is down
Allow error email to still be sent if DB is down We were seeing errors in the logs where the database was inaccessible, but the errors were not being emailed out because the handler makes a DB query.
Python
mit
ASCIT/donut,ASCIT/donut,ASCIT/donut
from logging.handlers import SMTPHandler DEV_TEAM_EMAILS_QUERY = '''SELECT DISTINCT email FROM - members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups + members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups - WHERE group_name = "Devteam" + WHERE group_name = "Devteam" ''' + DEFAULT_DEV_TEAM_EMAILS = ['devteam@donut.caltech.edu'] class DonutSMTPHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, db_instance, credentials=None, secure=None, timeout=5.0): super().__init__(mailhost, fromaddr, toaddrs, subject, credentials, secure, timeout) self.db_instance = db_instance def emit(self, record): ''' Overrides SMTPHandler's emit such that we dynamically get current donut dev team members ''' self.toaddrs = self.getAdmins() super().emit(record) def getAdmins(self): ''' Returns current members in Devteam ''' + try: - with self.db_instance.cursor() as cursor: + with self.db_instance.cursor() as cursor: - cursor.execute(DEV_TEAM_EMAILS_QUERY, []) + cursor.execute(DEV_TEAM_EMAILS_QUERY) - res = cursor.fetchall() + res = cursor.fetchall() - return [result['email'] for result in res] + return [result['email'] for result in res] + except Exception: + # If the database is inaccessible, fallback to a hard-coded email list + return DEFAULT_DEV_TEAM_EMAILS
Allow error email to still be sent if DB is down
## Code Before: from logging.handlers import SMTPHandler DEV_TEAM_EMAILS_QUERY = '''SELECT DISTINCT email FROM members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups WHERE group_name = "Devteam" ''' class DonutSMTPHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, db_instance, credentials=None, secure=None, timeout=5.0): super().__init__(mailhost, fromaddr, toaddrs, subject, credentials, secure, timeout) self.db_instance = db_instance def emit(self, record): ''' Overrides SMTPHandler's emit such that we dynamically get current donut dev team members ''' self.toaddrs = self.getAdmins() super().emit(record) def getAdmins(self): ''' Returns current members in Devteam ''' with self.db_instance.cursor() as cursor: cursor.execute(DEV_TEAM_EMAILS_QUERY, []) res = cursor.fetchall() return [result['email'] for result in res] ## Instruction: Allow error email to still be sent if DB is down ## Code After: from logging.handlers import SMTPHandler DEV_TEAM_EMAILS_QUERY = '''SELECT DISTINCT email FROM members NATURAL JOIN current_position_holders NATURAL JOIN positions NATURAL JOIN groups WHERE group_name = "Devteam" ''' DEFAULT_DEV_TEAM_EMAILS = ['devteam@donut.caltech.edu'] class DonutSMTPHandler(SMTPHandler): def __init__(self, mailhost, fromaddr, toaddrs, subject, db_instance, credentials=None, secure=None, timeout=5.0): super().__init__(mailhost, fromaddr, toaddrs, subject, credentials, secure, timeout) self.db_instance = db_instance def emit(self, record): ''' Overrides SMTPHandler's emit such that we dynamically get current donut dev team members ''' self.toaddrs = self.getAdmins() super().emit(record) def getAdmins(self): ''' Returns current members in Devteam ''' try: with self.db_instance.cursor() as cursor: cursor.execute(DEV_TEAM_EMAILS_QUERY) res = cursor.fetchall() return [result['email'] for result in res] except Exception: # If the database is inaccessible, fallback to a hard-coded email list return DEFAULT_DEV_TEAM_EMAILS
185f429f2a4309addf446fb382434e1a0ecafb9a
crm_employees/models/crm_employees_range.py
crm_employees/models/crm_employees_range.py
from openerp import models, fields class CrmEmployeesRange(models.Model): _name = 'crm.employees_range' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Employees range" name = fields.Char(required=True) parent_id = fields.Many2one(comodel_name='crm.employees_range') children = fields.One2many(comodel_name='crm.employees_range', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
from openerp import models, fields class CrmEmployeesRange(models.Model): _name = 'crm.employees_range' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Employees range" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one(comodel_name='crm.employees_range') children = fields.One2many(comodel_name='crm.employees_range', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
Set some fields as tranlate
Set some fields as tranlate
Python
agpl-3.0
Therp/partner-contact,open-synergy/partner-contact,diagramsoftware/partner-contact,Endika/partner-contact,acsone/partner-contact
from openerp import models, fields class CrmEmployeesRange(models.Model): _name = 'crm.employees_range' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Employees range" - name = fields.Char(required=True) + name = fields.Char(required=True, translate=True) parent_id = fields.Many2one(comodel_name='crm.employees_range') children = fields.One2many(comodel_name='crm.employees_range', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
Set some fields as tranlate
## Code Before: from openerp import models, fields class CrmEmployeesRange(models.Model): _name = 'crm.employees_range' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Employees range" name = fields.Char(required=True) parent_id = fields.Many2one(comodel_name='crm.employees_range') children = fields.One2many(comodel_name='crm.employees_range', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True) ## Instruction: Set some fields as tranlate ## Code After: from openerp import models, fields class CrmEmployeesRange(models.Model): _name = 'crm.employees_range' _order = "parent_left" _parent_order = "name" _parent_store = True _description = "Employees range" name = fields.Char(required=True, translate=True) parent_id = fields.Many2one(comodel_name='crm.employees_range') children = fields.One2many(comodel_name='crm.employees_range', inverse_name='parent_id') parent_left = fields.Integer('Parent Left', select=True) parent_right = fields.Integer('Parent Right', select=True)
78b62cd865b5c31a17c982b78dc91127ebf54525
erpnext/patches/may_2012/same_purchase_rate_patch.py
erpnext/patches/may_2012/same_purchase_rate_patch.py
def execute(): import webnotes gd = webnotes.model.code.get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
def execute(): import webnotes from webnotes.model.code import get_obj gd = get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
Maintain same rate throughout pur cycle: in global defaults, by default set true
Maintain same rate throughout pur cycle: in global defaults, by default set true
Python
agpl-3.0
rohitwaghchaure/digitales_erpnext,gangadhar-kadam/smrterp,pombredanne/erpnext,saurabh6790/test-med-app,gangadharkadam/johnerp,indictranstech/erpnext,hernad/erpnext,gangadhar-kadam/helpdesk-erpnext,gangadhar-kadam/mic-erpnext,mbauskar/Das_Erpnext,hernad/erpnext,Tejal011089/huntercamp_erpnext,saurabh6790/ON-RISAPP,mbauskar/phrerp,gangadhar-kadam/laganerp,gangadhar-kadam/hrerp,pombredanne/erpnext,pawaranand/phrerp,gangadharkadam/contributionerp,mbauskar/phrerp,dieface/erpnext,indictranstech/Das_Erpnext,suyashphadtare/sajil-erp,njmube/erpnext,indictranstech/fbd_erpnext,indictranstech/phrerp,gangadhar-kadam/powapp,njmube/erpnext,saurabh6790/aimobilize-app-backup,gangadhar-kadam/latestchurcherp,Drooids/erpnext,indictranstech/biggift-erpnext,geekroot/erpnext,suyashphadtare/sajil-erp,suyashphadtare/sajil-final-erp,indictranstech/Das_Erpnext,indictranstech/biggift-erpnext,indictranstech/phrerp,gangadhar-kadam/verve_erp,mbauskar/internal-hr,gangadhar-kadam/church-erpnext,gmarke/erpnext,Tejal011089/Medsyn2_app,indictranstech/buyback-erp,gangadhar-kadam/smrterp,Tejal011089/digitales_erpnext,Tejal011089/trufil-erpnext,indictranstech/vestasi-erpnext,gmarke/erpnext,netfirms/erpnext,hatwar/buyback-erpnext,dieface/erpnext,shitolepriya/test-erp,gangadharkadam/contributionerp,mbauskar/sapphire-erpnext,SPKian/Testing2,suyashphadtare/test,sheafferusa/erpnext,fuhongliang/erpnext,gangadharkadam/verveerp,indictranstech/tele-erpnext,saurabh6790/omnisys-app,Tejal011089/paypal_erpnext,mbauskar/omnitech-erpnext,shitolepriya/test-erp,gangadhar-kadam/verve-erp,mbauskar/phrerp,gangadhar-kadam/adb-erp,saurabh6790/omnit-app,MartinEnder/erpnext-de,SPKian/Testing,rohitwaghchaure/GenieManager-erpnext,indictranstech/Das_Erpnext,geekroot/erpnext,gangadharkadam/tailorerp,suyashphadtare/vestasi-erp-jan-end,hanselke/erpnext-1,mahabuber/erpnext,gangadhar-kadam/helpdesk-erpnext,hatwar/Das_erpnext,aruizramon/alec_erpnext,saurabh6790/medsyn-app1,saurabh6790/test_final_med_app,gangadharkadam/v4_erp,indictranstech/trufil-erpnext,anandpdoshi/erpnext,SPKian/Testing2,rohitwaghchaure/New_Theme_Erp,indictranstech/buyback-erp,gsnbng/erpnext,saurabh6790/medsyn-app,saurabh6790/omn-app,sagar30051991/ozsmart-erp,gangadhar-kadam/latestchurcherp,sagar30051991/ozsmart-erp,gangadhar-kadam/mtn-erpnext,Tejal011089/paypal_erpnext,gangadharkadam/office_erp,saurabh6790/med_new_app,netfirms/erpnext,BhupeshGupta/erpnext,Suninus/erpnext,gsnbng/erpnext,gangadhar-kadam/latestchurcherp,Tejal011089/osmosis_erpnext,shitolepriya/test-erp,rohitwaghchaure/digitales_erpnext,gangadhar-kadam/verve_live_erp,ThiagoGarciaAlves/erpnext,ThiagoGarciaAlves/erpnext,gangadharkadam/v5_erp,ShashaQin/erpnext,SPKian/Testing,indictranstech/focal-erpnext,indictranstech/osmosis-erpnext,indictranstech/focal-erpnext,Suninus/erpnext,gangadharkadam/saloon_erp_install,Tejal011089/med2-app,mbauskar/omnitech-demo-erpnext,rohitwaghchaure/New_Theme_Erp,suyashphadtare/gd-erp,meisterkleister/erpnext,saurabh6790/test-med-app,mbauskar/alec_frappe5_erpnext,MartinEnder/erpnext-de,suyashphadtare/vestasi-erp-jan-end,gangadharkadam/v6_erp,gangadhar-kadam/powapp,gangadharkadam/sher,saurabh6790/alert-med-app,mbauskar/Das_Erpnext,BhupeshGupta/erpnext,indictranstech/reciphergroup-erpnext,Tejal011089/osmosis_erpnext,anandpdoshi/erpnext,gangadhar-kadam/verve_test_erp,gangadharkadam/v5_erp,shft117/SteckerApp,rohitwaghchaure/erpnext_smart,gangadhar-kadam/prjapp,geekroot/erpnext,saurabh6790/ON-RISAPP,indictranstech/buyback-erp,gangadharkadam/sterp,tmimori/erpnext,fuhongliang/erpnext,mbauskar/Das_Erpnext,Tejal011089/huntercamp_erpnext,gangadharkadam/saloon_erp,ThiagoGarciaAlves/erpnext,indictranstech/trufil-erpnext,saurabh6790/medapp,suyashphadtare/vestasi-erp-jan-end,saurabh6790/test-erp,indictranstech/fbd_erpnext,gangadharkadam/saloon_erp_install,gangadhar-kadam/laganerp,Tejal011089/digitales_erpnext,fuhongliang/erpnext,SPKian/Testing2,saurabh6790/aimobilize,meisterkleister/erpnext,indictranstech/focal-erpnext,gangadharkadam/saloon_erp,SPKian/Testing,rohitwaghchaure/erpnext-receipher,gangadharkadam/smrterp,gangadharkadam/v5_erp,gangadhar-kadam/sms-erpnext,gangadharkadam/office_erp,hernad/erpnext,mbauskar/sapphire-erpnext,gangadharkadam/saloon_erp_install,saurabh6790/OFF-RISAPP,suyashphadtare/vestasi-update-erp,ShashaQin/erpnext,gangadhar-kadam/laganerp,Tejal011089/osmosis_erpnext,treejames/erpnext,gangadhar-kadam/sms-erpnext,BhupeshGupta/erpnext,mbauskar/omnitech-demo-erpnext,tmimori/erpnext,saurabh6790/medsynaptic1-app,gangadharkadam/vlinkerp,sagar30051991/ozsmart-erp,Tejal011089/trufil-erpnext,rohitwaghchaure/erpnext-receipher,gangadharkadam/sterp,indictranstech/fbd_erpnext,saurabh6790/trufil_app,rohitwaghchaure/GenieManager-erpnext,sheafferusa/erpnext,saurabh6790/med_new_app,indictranstech/phrerp,suyashphadtare/gd-erp,njmube/erpnext,mbauskar/internal-hr,gangadhar-kadam/sapphire_app,Tejal011089/trufil-erpnext,gangadharkadam/vlinkerp,gangadharkadam/tailorerp,indictranstech/tele-erpnext,susuchina/ERPNEXT,Tejal011089/digitales_erpnext,suyashphadtare/sajil-final-erp,gangadharkadam/saloon_erp,MartinEnder/erpnext-de,gangadharkadam/vlinkerp,saurabh6790/med_app_rels,SPKian/Testing,rohitwaghchaure/erpnext_smart,saurabh6790/medsynaptic1-app,gangadhar-kadam/verve_test_erp,rohitwaghchaure/GenieManager-erpnext,gangadharkadam/contributionerp,4commerce-technologies-AG/erpnext,saurabh6790/omnitech-apps,indictranstech/tele-erpnext,hatwar/buyback-erpnext,saurabh6790/medsynaptic-app,susuchina/ERPNEXT,gangadharkadam/v6_erp,indictranstech/osmosis-erpnext,saurabh6790/omnitech-apps,rohitwaghchaure/erpnext_smart,rohitwaghchaure/New_Theme_Erp,saurabh6790/trufil_app,indictranstech/vestasi-erpnext,mbauskar/sapphire-erpnext,hatwar/focal-erpnext,pombredanne/erpnext,gangadharkadam/smrterp,saurabh6790/pow-app,mbauskar/omnitech-erpnext,treejames/erpnext,gangadharkadam/office_erp,dieface/erpnext,indictranstech/trufil-erpnext,hatwar/buyback-erpnext,indictranstech/vestasi-erpnext,saurabh6790/medsyn-app1,gangadharkadam/v4_erp,mbauskar/alec_frappe5_erpnext,netfirms/erpnext,suyashphadtare/vestasi-erp-final,gangadhar-kadam/verve_erp,suyashphadtare/vestasi-update-erp,suyashphadtare/vestasi-erp-final,mahabuber/erpnext,gangadharkadam/letzerp,susuchina/ERPNEXT,suyashphadtare/sajil-final-erp,indictranstech/osmosis-erpnext,treejames/erpnext,hatwar/Das_erpnext,gangadhar-kadam/verve_erp,mahabuber/erpnext,saurabh6790/pow-app,shft117/SteckerApp,indictranstech/phrerp,gangadhar-kadam/verve_erp,mbauskar/sapphire-erpnext,saurabh6790/omnisys-app,suyashphadtare/vestasi-update-erp,gangadhar-kadam/helpdesk-erpnext,Yellowen/Owrang,saurabh6790/aimobilize,gangadhar-kadam/powapp,hatwar/focal-erpnext,saurabh6790/omnit-app,fuhongliang/erpnext,ThiagoGarciaAlves/erpnext,saurabh6790/test-erp,Tejal011089/trufil-erpnext,hernad/erpnext,suyashphadtare/vestasi-erp-1,sheafferusa/erpnext,indictranstech/internal-erpnext,mbauskar/Das_Erpnext,mbauskar/helpdesk-erpnext,gangadhar-kadam/hrerp,Tejal011089/fbd_erpnext,hanselke/erpnext-1,gangadhar-kadam/helpdesk-erpnext,saurabh6790/tru_app_back,indictranstech/tele-erpnext,gsnbng/erpnext,rohitwaghchaure/erpnext-receipher,sheafferusa/erpnext,gangadharkadam/verveerp,suyashphadtare/gd-erp,gangadhar-kadam/nassimapp,gangadhar-kadam/nassimapp,shft117/SteckerApp,gangadhar-kadam/verve_test_erp,rohitwaghchaure/erpnext-receipher,gmarke/erpnext,saurabh6790/OFF-RISAPP,4commerce-technologies-AG/erpnext,indictranstech/erpnext,meisterkleister/erpnext,Tejal011089/med2-app,Tejal011089/Medsyn2_app,suyashphadtare/vestasi-erp-final,mbauskar/omnitech-erpnext,ShashaQin/erpnext,gangadharkadam/v4_erp,mbauskar/phrerp,sagar30051991/ozsmart-erp,indictranstech/erpnext,indictranstech/internal-erpnext,suyashphadtare/vestasi-erp-jan-end,hatwar/focal-erpnext,indictranstech/internal-erpnext,SPKian/Testing2,Drooids/erpnext,hatwar/Das_erpnext,gangadhar-kadam/prjapp,gangadharkadam/sher,Tejal011089/paypal_erpnext,gangadharkadam/vlinkerp,suyashphadtare/vestasi-erp-1,gangadhar-kadam/church-erpnext,indictranstech/erpnext,geekroot/erpnext,Tejal011089/osmosis_erpnext,gangadhar-kadam/verve_live_erp,gangadharkadam/v5_erp,hatwar/buyback-erpnext,suyashphadtare/test,mbauskar/alec_frappe5_erpnext,saurabh6790/alert-med-app,Suninus/erpnext,saurabh6790/med_app_rels,gangadhar-kadam/latestchurcherp,Tejal011089/digitales_erpnext,rohitwaghchaure/digitales_erpnext,gangadhar-kadam/mic-erpnext,indictranstech/reciphergroup-erpnext,indictranstech/trufil-erpnext,gangadhar-kadam/sapphire_app,aruizramon/alec_erpnext,gangadharkadam/saloon_erp_install,saurabh6790/omn-app,indictranstech/Das_Erpnext,anandpdoshi/erpnext,rohitwaghchaure/New_Theme_Erp,meisterkleister/erpnext,mbauskar/omnitech-erpnext,mbauskar/omnitech-demo-erpnext,Aptitudetech/ERPNext,mbauskar/helpdesk-erpnext,gangadhar-kadam/verve_live_erp,suyashphadtare/sajil-erp,shitolepriya/test-erp,mbauskar/helpdesk-erpnext,Tejal011089/fbd_erpnext,hanselke/erpnext-1,saurabh6790/test-erp,gangadharkadam/letzerp,Tejal011089/fbd_erpnext,gangadharkadam/v6_erp,saurabh6790/medsyn-app,gangadhar-kadam/verve-erp,gangadharkadam/verveerp,gangadharkadam/contributionerp,gangadhar-kadam/verve-erp,treejames/erpnext,gsnbng/erpnext,pombredanne/erpnext,gangadharkadam/saloon_erp,indictranstech/fbd_erpnext,indictranstech/biggift-erpnext,gangadhar-kadam/verve_test_erp,aruizramon/alec_erpnext,suyashphadtare/test,mbauskar/helpdesk-erpnext,4commerce-technologies-AG/erpnext,Drooids/erpnext,saurabh6790/test_final_med_app,shft117/SteckerApp,netfirms/erpnext,gangadharkadam/letzerp,mbauskar/internal-hr,saurabh6790/omni-apps,tmimori/erpnext,pawaranand/phrerp,hanselke/erpnext-1,indictranstech/osmosis-erpnext,njmube/erpnext,gmarke/erpnext,Tejal011089/fbd_erpnext,saurabh6790/test-erp,BhupeshGupta/erpnext,gangadhar-kadam/sapphire_app,Yellowen/Owrang,susuchina/ERPNEXT,indictranstech/internal-erpnext,hatwar/focal-erpnext,gangadharkadam/johnerp,indictranstech/biggift-erpnext,gangadharkadam/v6_erp,saurabh6790/aimobilize-app-backup,gangadharkadam/letzerp,Tejal011089/huntercamp_erpnext,saurabh6790/tru_app_back,saurabh6790/omni-apps,Drooids/erpnext,indictranstech/vestasi-erpnext,suyashphadtare/gd-erp,pawaranand/phrerp,Tejal011089/huntercamp_erpnext,dieface/erpnext,Suninus/erpnext,Tejal011089/paypal_erpnext,tmimori/erpnext,saurabh6790/medapp,indictranstech/buyback-erp,ShashaQin/erpnext,pawaranand/phrerp,indictranstech/focal-erpnext,indictranstech/reciphergroup-erpnext,indictranstech/reciphergroup-erpnext,hatwar/Das_erpnext,mbauskar/omnitech-demo-erpnext,gangadharkadam/v4_erp,MartinEnder/erpnext-de,anandpdoshi/erpnext,suyashphadtare/vestasi-erp-1,rohitwaghchaure/GenieManager-erpnext,mahabuber/erpnext,gangadhar-kadam/adb-erp,gangadhar-kadam/mtn-erpnext,gangadhar-kadam/verve_live_erp,aruizramon/alec_erpnext,gangadharkadam/verveerp,mbauskar/alec_frappe5_erpnext,rohitwaghchaure/digitales_erpnext,saurabh6790/medsynaptic-app
def execute(): import webnotes + from webnotes.model.code import get_obj - gd = webnotes.model.code.get_obj('Global Defaults') + gd = get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
Maintain same rate throughout pur cycle: in global defaults, by default set true
## Code Before: def execute(): import webnotes gd = webnotes.model.code.get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update() ## Instruction: Maintain same rate throughout pur cycle: in global defaults, by default set true ## Code After: def execute(): import webnotes from webnotes.model.code import get_obj gd = get_obj('Global Defaults') gd.doc.maintain_same_rate = 1 gd.doc.save() gd.on_update()
840af484f3b0f615167adf9600263e0d8c2e3875
wrappers/python/setup.py
wrappers/python/setup.py
from distutils.core import setup import os PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0' setup( name='python3-indy', version=PKG_VERSION, packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=['pytest<3.7', 'pytest-asyncio', 'base58'], tests_require=['pytest<3.7', 'pytest-asyncio', 'base58'] )
from distutils.core import setup import os PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0' setup( name='python3-indy', version=PKG_VERSION, packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=['base58'], tests_require=['pytest<3.7', 'pytest-asyncio', 'base58'] )
Remove install dependency of pytest from python wrapper
Remove install dependency of pytest from python wrapper Signed-off-by: Daniel Bluhm <6df8625bb799b640110458f819853f591a9910cb@sovrin.org>
Python
apache-2.0
Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk
from distutils.core import setup import os PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0' setup( name='python3-indy', version=PKG_VERSION, packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', - install_requires=['pytest<3.7', 'pytest-asyncio', 'base58'], + install_requires=['base58'], tests_require=['pytest<3.7', 'pytest-asyncio', 'base58'] )
Remove install dependency of pytest from python wrapper
## Code Before: from distutils.core import setup import os PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0' setup( name='python3-indy', version=PKG_VERSION, packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=['pytest<3.7', 'pytest-asyncio', 'base58'], tests_require=['pytest<3.7', 'pytest-asyncio', 'base58'] ) ## Instruction: Remove install dependency of pytest from python wrapper ## Code After: from distutils.core import setup import os PKG_VERSION = os.environ.get('PACKAGE_VERSION') or '1.9.0' setup( name='python3-indy', version=PKG_VERSION, packages=['indy'], url='https://github.com/hyperledger/indy-sdk', license='MIT/Apache-2.0', author='Vyacheslav Gudkov', author_email='vyacheslav.gudkov@dsr-company.com', description='This is the official SDK for Hyperledger Indy (https://www.hyperledger.org/projects), which provides a distributed-ledger-based foundation for self-sovereign identity (https://sovrin.org). The major artifact of the SDK is a c-callable library.', install_requires=['base58'], tests_require=['pytest<3.7', 'pytest-asyncio', 'base58'] )
061e0e0702025d99956b7dc606ea0bb4fa5c84ea
flocker/restapi/_logging.py
flocker/restapi/_logging.py
__all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response.")
__all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") # It would be nice if RESPONSE_CODE was in REQUEST instead of # JSON_REQUEST; see FLOC-1586. REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response bodies.")
Address review comment: Better documentation.
Address review comment: Better documentation.
Python
apache-2.0
Azulinho/flocker,moypray/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,w4ngyi/flocker,adamtheturtle/flocker,runcom/flocker,mbrukman/flocker,LaynePeng/flocker,achanda/flocker,jml/flocker,hackday-profilers/flocker,AndyHuu/flocker,jml/flocker,lukemarsden/flocker,LaynePeng/flocker,achanda/flocker,1d4Nf6/flocker,Azulinho/flocker,hackday-profilers/flocker,moypray/flocker,w4ngyi/flocker,1d4Nf6/flocker,hackday-profilers/flocker,lukemarsden/flocker,AndyHuu/flocker,Azulinho/flocker,1d4Nf6/flocker,mbrukman/flocker,agonzalezro/flocker,LaynePeng/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,w4ngyi/flocker,moypray/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,agonzalezro/flocker,adamtheturtle/flocker,achanda/flocker,runcom/flocker,jml/flocker,agonzalezro/flocker,AndyHuu/flocker,runcom/flocker
__all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") + # It would be nice if RESPONSE_CODE was in REQUEST instead of + # JSON_REQUEST; see FLOC-1586. REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], - u"A request containing JSON request and response.") + u"A request containing JSON request and response bodies.")
Address review comment: Better documentation.
## Code Before: __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response.") ## Instruction: Address review comment: Better documentation. ## Code After: __all__ = [ "JSON_REQUEST", "REQUEST", ] from eliot import Field, ActionType LOG_SYSTEM = u"api" METHOD = Field(u"method", lambda method: method, u"The HTTP method of the request.") REQUEST_PATH = Field( u"request_path", lambda path: path, u"The absolute path of the resource to which the request was issued.") JSON = Field.forTypes( u"json", [unicode, bytes, dict, list, None, bool, float], u"JSON, either request or response depending on context.") RESPONSE_CODE = Field.forTypes( u"code", [int], u"The response code for the request.") # It would be nice if RESPONSE_CODE was in REQUEST instead of # JSON_REQUEST; see FLOC-1586. REQUEST = ActionType( LOG_SYSTEM + u":request", [REQUEST_PATH, METHOD], [], u"A request was received on the public HTTP interface.") JSON_REQUEST = ActionType( LOG_SYSTEM + u":json_request", [JSON], [RESPONSE_CODE, JSON], u"A request containing JSON request and response bodies.")
d2536523770a59ed60bf27e8c0e456a33ca1a804
billabong/tests/test_main.py
billabong/tests/test_main.py
"""Test CLI interface.""" import os from .fixtures import record assert record def run(cmd): """Helper to test running a CLI command.""" os.system('python -m billabong ' + cmd) def test_cli(record): """Test main supported CLI commands.""" ID = record['id'] run('ls') run('blobs') run('info ' + ID) run('search txt') run('check') run('push') run('pull') run('echo ' + ID) run('status') run('version')
"""Test CLI interface.""" import os from .fixtures import record assert record def run(cmd): """Helper to test running a CLI command.""" os.system('python -m billabong ' + cmd) def test_cli(record): """Test main supported CLI commands.""" ID = record['id'] run('ls') run('records') run('blobs') run('info ' + ID) run('info ' + ID + ' --no-color') run('search txt') run('check') run('push') run('pull') run('echo ' + ID) run('status') run('version') run('add hello.txt')
Add test for cli 'add' command
Add test for cli 'add' command
Python
agpl-3.0
hoh/Billabong,hoh/Billabong
"""Test CLI interface.""" import os from .fixtures import record assert record def run(cmd): """Helper to test running a CLI command.""" os.system('python -m billabong ' + cmd) def test_cli(record): """Test main supported CLI commands.""" ID = record['id'] run('ls') + run('records') run('blobs') run('info ' + ID) + run('info ' + ID + ' --no-color') run('search txt') run('check') run('push') run('pull') run('echo ' + ID) run('status') run('version') + run('add hello.txt') +
Add test for cli 'add' command
## Code Before: """Test CLI interface.""" import os from .fixtures import record assert record def run(cmd): """Helper to test running a CLI command.""" os.system('python -m billabong ' + cmd) def test_cli(record): """Test main supported CLI commands.""" ID = record['id'] run('ls') run('blobs') run('info ' + ID) run('search txt') run('check') run('push') run('pull') run('echo ' + ID) run('status') run('version') ## Instruction: Add test for cli 'add' command ## Code After: """Test CLI interface.""" import os from .fixtures import record assert record def run(cmd): """Helper to test running a CLI command.""" os.system('python -m billabong ' + cmd) def test_cli(record): """Test main supported CLI commands.""" ID = record['id'] run('ls') run('records') run('blobs') run('info ' + ID) run('info ' + ID + ' --no-color') run('search txt') run('check') run('push') run('pull') run('echo ' + ID) run('status') run('version') run('add hello.txt')
32ca774aca8fd60a26f6144a98f25fa8b65ad22b
yak/rest_social_auth/serializers.py
yak/rest_social_auth/serializers.py
from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_user.serializers import SignUpSerializer User = get_user_model() class SocialSignUpSerializer(SignUpSerializer): password = serializers.CharField(required=False, write_only=True) class Meta: model = User fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') write_only_fields = ('access_token', 'access_token_secret') read_only_fields = ('fullname', 'username', 'email', 'client_id', 'client_secret')
from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_user.serializers import LoginSerializer User = get_user_model() class SocialSignUpSerializer(LoginSerializer): fullname = serializers.CharField(read_only=True) username = serializers.CharField(read_only=True) email = serializers.EmailField(read_only=True) password = serializers.CharField(required=False, write_only=True) class Meta: model = User fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') write_only_fields = ('access_token', 'access_token_secret')
Update social sign up serializer to avoid new validation on regular sign up
Update social sign up serializer to avoid new validation on regular sign up
Python
mit
ParableSciences/YAK-server,sventech/YAK-server,yeti/YAK-server,sventech/YAK-server,ParableSciences/YAK-server,yeti/YAK-server
from django.contrib.auth import get_user_model from rest_framework import serializers - from yak.rest_user.serializers import SignUpSerializer + from yak.rest_user.serializers import LoginSerializer User = get_user_model() - class SocialSignUpSerializer(SignUpSerializer): + class SocialSignUpSerializer(LoginSerializer): + fullname = serializers.CharField(read_only=True) + username = serializers.CharField(read_only=True) + email = serializers.EmailField(read_only=True) password = serializers.CharField(required=False, write_only=True) class Meta: model = User fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') write_only_fields = ('access_token', 'access_token_secret') - read_only_fields = ('fullname', 'username', 'email', 'client_id', 'client_secret')
Update social sign up serializer to avoid new validation on regular sign up
## Code Before: from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_user.serializers import SignUpSerializer User = get_user_model() class SocialSignUpSerializer(SignUpSerializer): password = serializers.CharField(required=False, write_only=True) class Meta: model = User fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') write_only_fields = ('access_token', 'access_token_secret') read_only_fields = ('fullname', 'username', 'email', 'client_id', 'client_secret') ## Instruction: Update social sign up serializer to avoid new validation on regular sign up ## Code After: from django.contrib.auth import get_user_model from rest_framework import serializers from yak.rest_user.serializers import LoginSerializer User = get_user_model() class SocialSignUpSerializer(LoginSerializer): fullname = serializers.CharField(read_only=True) username = serializers.CharField(read_only=True) email = serializers.EmailField(read_only=True) password = serializers.CharField(required=False, write_only=True) class Meta: model = User fields = ('fullname', 'username', 'email', 'password', 'client_id', 'client_secret') write_only_fields = ('access_token', 'access_token_secret')
a42b6d1faa38f92b21d74c1cf258f4b0e9800401
search/urls.py
search/urls.py
from django.conf.urls import patterns, url from django.views.generic import TemplateView from core.auth import perm import search.views urlpatterns = patterns('', url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'), url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'), url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'), url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'), url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'), url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'), )
from django.conf.urls import patterns, url from django.views.generic import TemplateView from core.auth import perm import search.views urlpatterns = patterns('', url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'), url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'), url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'), url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'), url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'), url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'), )
Allow any logged-in user to perform image searches.
Allow any logged-in user to perform image searches.
Python
mit
occrp/id-backend
from django.conf.urls import patterns, url from django.views.generic import TemplateView from core.auth import perm import search.views urlpatterns = patterns('', url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'), url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'), - url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'), + url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'), - url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'), + url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'), url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'), url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'), )
Allow any logged-in user to perform image searches.
## Code Before: from django.conf.urls import patterns, url from django.views.generic import TemplateView from core.auth import perm import search.views urlpatterns = patterns('', url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'), url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'), url(r'^image/$', perm('user', search.views.ImageSearchTemplate), name='search_images'), url(r'^image/query/$', perm('user', search.views.SearchImageQuery), name='search_images_query'), url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'), url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'), ) ## Instruction: Allow any logged-in user to perform image searches. ## Code After: from django.conf.urls import patterns, url from django.views.generic import TemplateView from core.auth import perm import search.views urlpatterns = patterns('', url(r'^document/$', perm('any', search.views.DocumentSearchTemplate), name='search'), url(r'^document/query/$',perm('any', search.views.DocumentSearchQuery), name='search_documents_query'), url(r'^image/$', perm('loggedin', search.views.ImageSearchTemplate), name='search_images'), url(r'^image/query/$', perm('loggedin', search.views.SearchImageQuery), name='search_images_query'), url(r'^social/$', perm('user', TemplateView, template_name='search/search_social.jinja'), name='search_social'), url(r'^social/query/$', perm('user', search.views.SearchSocialQuery), name='search_social_query'), )
afc0ace0767e29f8c2b71ed5ba7f8139e24fc020
categories/serializers.py
categories/serializers.py
from .models import Category, Keyword, Subcategory from rest_framework import serializers class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required') class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name')
from .models import Category, Keyword, Subcategory from rest_framework import serializers class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories')
Add reverse relationship serializer to Category
Add reverse relationship serializer to Category
Python
apache-2.0
belatrix/BackendAllStars
from .models import Category, Keyword, Subcategory from rest_framework import serializers - - - class CategorySerializer(serializers.ModelSerializer): - class Meta: - model = Category - fields = ('pk', 'name', 'weight', 'comment_required') class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') + + + class CategorySerializer(serializers.ModelSerializer): + subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') + + class Meta: + model = Category + fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories')
Add reverse relationship serializer to Category
## Code Before: from .models import Category, Keyword, Subcategory from rest_framework import serializers class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required') class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') ## Instruction: Add reverse relationship serializer to Category ## Code After: from .models import Category, Keyword, Subcategory from rest_framework import serializers class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class KeywordListSerializer(serializers.ModelSerializer): class Meta: model = Keyword fields = ('pk', 'name') class SubcategoryDetailSerializer(serializers.ModelSerializer): class Meta: model = Subcategory depth = 1 fields = ('pk', 'name', 'category') class SubcategoryListSerializer(serializers.ModelSerializer): class Meta: model = Subcategory fields = ('pk', 'name') class CategorySerializer(serializers.ModelSerializer): subcategories = SubcategoryListSerializer(many=True, source='subcategory_set') class Meta: model = Category fields = ('pk', 'name', 'weight', 'comment_required', 'subcategories')
8e9889bb9c2d916f61e5e08416a171777f1c6a2e
samples/gpio_write.py
samples/gpio_write.py
import asyncio import apigpio LED_GPIO = 21 @asyncio.coroutine def start_blink(pi, address): yield from pi.connect(address) # running this in this order blocks :( # only in run, when debuging it does not block... # blocks on set_mode for the second gpio yield from pi.set_mode(LED_GPIO, apigpio.OUTPUT) while True: yield from pi.write(LED_GPIO, 0) yield from asyncio.sleep(1) yield from pi.write(LED_GPIO, 1) yield from asyncio.sleep(1) if __name__ == '__main__': loop = asyncio.get_event_loop() pi = apigpio.Pi(loop) address = ('192.168.1.3', 8888) loop.run_until_complete(start_blink(pi, address))
import asyncio import apigpio LED_GPIO = 21 @asyncio.coroutine def start_blink(pi, address): yield from pi.connect(address) yield from pi.set_mode(LED_GPIO, apigpio.OUTPUT) while True: yield from pi.write(LED_GPIO, 0) yield from asyncio.sleep(1) yield from pi.write(LED_GPIO, 1) yield from asyncio.sleep(1) if __name__ == '__main__': loop = asyncio.get_event_loop() pi = apigpio.Pi(loop) address = ('192.168.1.3', 8888) loop.run_until_complete(start_blink(pi, address))
Remove wrong comments on samples.
Remove wrong comments on samples.
Python
mit
PierreRust/apigpio
import asyncio import apigpio LED_GPIO = 21 @asyncio.coroutine def start_blink(pi, address): yield from pi.connect(address) - # running this in this order blocks :( - # only in run, when debuging it does not block... - # blocks on set_mode for the second gpio yield from pi.set_mode(LED_GPIO, apigpio.OUTPUT) while True: yield from pi.write(LED_GPIO, 0) yield from asyncio.sleep(1) yield from pi.write(LED_GPIO, 1) yield from asyncio.sleep(1) if __name__ == '__main__': loop = asyncio.get_event_loop() pi = apigpio.Pi(loop) address = ('192.168.1.3', 8888) loop.run_until_complete(start_blink(pi, address))
Remove wrong comments on samples.
## Code Before: import asyncio import apigpio LED_GPIO = 21 @asyncio.coroutine def start_blink(pi, address): yield from pi.connect(address) # running this in this order blocks :( # only in run, when debuging it does not block... # blocks on set_mode for the second gpio yield from pi.set_mode(LED_GPIO, apigpio.OUTPUT) while True: yield from pi.write(LED_GPIO, 0) yield from asyncio.sleep(1) yield from pi.write(LED_GPIO, 1) yield from asyncio.sleep(1) if __name__ == '__main__': loop = asyncio.get_event_loop() pi = apigpio.Pi(loop) address = ('192.168.1.3', 8888) loop.run_until_complete(start_blink(pi, address)) ## Instruction: Remove wrong comments on samples. ## Code After: import asyncio import apigpio LED_GPIO = 21 @asyncio.coroutine def start_blink(pi, address): yield from pi.connect(address) yield from pi.set_mode(LED_GPIO, apigpio.OUTPUT) while True: yield from pi.write(LED_GPIO, 0) yield from asyncio.sleep(1) yield from pi.write(LED_GPIO, 1) yield from asyncio.sleep(1) if __name__ == '__main__': loop = asyncio.get_event_loop() pi = apigpio.Pi(loop) address = ('192.168.1.3', 8888) loop.run_until_complete(start_blink(pi, address))
ffde5305a2182e566384887d51e4fde90adc9908
runtests.py
runtests.py
import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures))
import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": tests = "tests" if len(sys.argv) == 1 else sys.argv[1] os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests([tests]) sys.exit(bool(failures))
Make it possible to run individual tests.
Tests: Make it possible to run individual tests.
Python
agpl-3.0
etesync/journal-manager
import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": + tests = "tests" if len(sys.argv) == 1 else sys.argv[1] os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() - failures = test_runner.run_tests(["tests"]) + failures = test_runner.run_tests([tests]) sys.exit(bool(failures))
Make it possible to run individual tests.
## Code Before: import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures)) ## Instruction: Make it possible to run individual tests. ## Code After: import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": tests = "tests" if len(sys.argv) == 1 else sys.argv[1] os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests([tests]) sys.exit(bool(failures))
16b2de5a1c4965b1e3a2cb96c6ea3bd847e85c95
hxl/commands/hxlvalidate.py
hxl/commands/hxlvalidate.py
import sys import argparse from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input, output=sys.stdout, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) schema.validate(parser) # end
import sys from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input=sys.stdin, output=sys.stderr, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) return schema.validate(parser) # end
Return result of validation from the command script.
Return result of validation from the command script.
Python
unlicense
HXLStandard/libhxl-python,HXLStandard/libhxl-python
import sys - import argparse from hxl.parser import HXLReader from hxl.schema import loadHXLSchema - def hxlvalidate(input, output=sys.stdout, schema_input=None): + def hxlvalidate(input=sys.stdin, output=sys.stderr, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) - schema.validate(parser) + return schema.validate(parser) # end
Return result of validation from the command script.
## Code Before: import sys import argparse from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input, output=sys.stdout, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) schema.validate(parser) # end ## Instruction: Return result of validation from the command script. ## Code After: import sys from hxl.parser import HXLReader from hxl.schema import loadHXLSchema def hxlvalidate(input=sys.stdin, output=sys.stderr, schema_input=None): parser = HXLReader(input) schema = loadHXLSchema(schema_input) return schema.validate(parser) # end
08542b47b127d6bcf128bdedb5f25956f909784e
website_snippet_anchor/__openerp__.py
website_snippet_anchor/__openerp__.py
{ "name": "Set Snippet's Anchor", "summary": "Allow to reach a concrete section in the page", "version": "8.0.1.0.0", "category": "Website", "website": "http://www.antiun.com", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "website", ], "data": [ "views/assets.xml", "views/snippets.xml", ], }
{ "name": "Set Snippet's Anchor", "summary": "Allow to reach a concrete section in the page", "version": "8.0.1.0.0", "category": "Website", "website": "http://www.antiun.com", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": [ "website", ], "data": [ "views/assets.xml", "views/snippets.xml", ], }
Remove unused keys from manifest.
Remove unused keys from manifest.
Python
agpl-3.0
pedrobaeza/website,brain-tec/website,LasLabs/website,gfcapalbo/website,gfcapalbo/website,acsone/website,LasLabs/website,LasLabs/website,open-synergy/website,pedrobaeza/website,brain-tec/website,pedrobaeza/website,nuobit/website,nuobit/website,nuobit/website,gfcapalbo/website,Endika/website,pedrobaeza/website,Yajo/website,gfcapalbo/website,Endika/website,open-synergy/website,Antiun/website,kaerdsar/website,open-synergy/website,open-synergy/website,brain-tec/website,Yajo/website,acsone/website,nuobit/website,acsone/website,kaerdsar/website,Endika/website,acsone/website,LasLabs/website,Antiun/website,Endika/website,Yajo/website,Antiun/website,kaerdsar/website,brain-tec/website,Yajo/website,Antiun/website
{ "name": "Set Snippet's Anchor", "summary": "Allow to reach a concrete section in the page", "version": "8.0.1.0.0", "category": "Website", "website": "http://www.antiun.com", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, - "external_dependencies": { - "python": [], - "bin": [], - }, "depends": [ "website", ], "data": [ "views/assets.xml", "views/snippets.xml", ], }
Remove unused keys from manifest.
## Code Before: { "name": "Set Snippet's Anchor", "summary": "Allow to reach a concrete section in the page", "version": "8.0.1.0.0", "category": "Website", "website": "http://www.antiun.com", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "website", ], "data": [ "views/assets.xml", "views/snippets.xml", ], } ## Instruction: Remove unused keys from manifest. ## Code After: { "name": "Set Snippet's Anchor", "summary": "Allow to reach a concrete section in the page", "version": "8.0.1.0.0", "category": "Website", "website": "http://www.antiun.com", "author": "Antiun Ingeniería S.L., Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "depends": [ "website", ], "data": [ "views/assets.xml", "views/snippets.xml", ], }
2020838fb456e6118f78ca7288cc14f3046b73eb
oxauth/auth.py
oxauth/auth.py
import json import base64 import urllib from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 class OXSessionDecryptor(object): def __init__(self, secret_key_base, salt="encrypted cookie", keylen=64, iterations=1000): self.secret = PBKDF2(secret_key_base, salt.encode(), keylen, iterations) def get_cookie_data(self, cookie): cookie = base64.b64decode(urllib.parse.unquote(cookie).split('--')[0]) encrypted_data, iv = map(base64.b64decode, cookie.split('--'.encode())) cipher = AES.new(self.secret[:32], AES.MODE_CBC, iv) return json.loads(unpad(cipher.decrypt(encrypted_data)))
import json import base64 import urllib from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 unpad = lambda s: s[:-ord(s[len(s) - 1:])] class OXSessionDecryptor(object): def __init__(self, secret_key_base, salt="encrypted cookie", keylen=64, iterations=1000): self.secret = PBKDF2(secret_key_base, salt.encode(), keylen, iterations) def get_cookie_data(self, cookie): cookie = base64.b64decode(urllib.parse.unquote(cookie).split('--')[0]) encrypted_data, iv = map(base64.b64decode, cookie.split('--'.encode())) cipher = AES.new(self.secret[:32], AES.MODE_CBC, iv) return json.loads(unpad(cipher.decrypt(encrypted_data)))
Add unpad function for unpacking cookie
Add unpad function for unpacking cookie
Python
agpl-3.0
openstax/openstax-cms,Connexions/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms
import json import base64 import urllib from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 + unpad = lambda s: s[:-ord(s[len(s) - 1:])] class OXSessionDecryptor(object): def __init__(self, secret_key_base, salt="encrypted cookie", keylen=64, iterations=1000): self.secret = PBKDF2(secret_key_base, salt.encode(), keylen, iterations) def get_cookie_data(self, cookie): cookie = base64.b64decode(urllib.parse.unquote(cookie).split('--')[0]) encrypted_data, iv = map(base64.b64decode, cookie.split('--'.encode())) cipher = AES.new(self.secret[:32], AES.MODE_CBC, iv) return json.loads(unpad(cipher.decrypt(encrypted_data)))
Add unpad function for unpacking cookie
## Code Before: import json import base64 import urllib from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 class OXSessionDecryptor(object): def __init__(self, secret_key_base, salt="encrypted cookie", keylen=64, iterations=1000): self.secret = PBKDF2(secret_key_base, salt.encode(), keylen, iterations) def get_cookie_data(self, cookie): cookie = base64.b64decode(urllib.parse.unquote(cookie).split('--')[0]) encrypted_data, iv = map(base64.b64decode, cookie.split('--'.encode())) cipher = AES.new(self.secret[:32], AES.MODE_CBC, iv) return json.loads(unpad(cipher.decrypt(encrypted_data))) ## Instruction: Add unpad function for unpacking cookie ## Code After: import json import base64 import urllib from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 unpad = lambda s: s[:-ord(s[len(s) - 1:])] class OXSessionDecryptor(object): def __init__(self, secret_key_base, salt="encrypted cookie", keylen=64, iterations=1000): self.secret = PBKDF2(secret_key_base, salt.encode(), keylen, iterations) def get_cookie_data(self, cookie): cookie = base64.b64decode(urllib.parse.unquote(cookie).split('--')[0]) encrypted_data, iv = map(base64.b64decode, cookie.split('--'.encode())) cipher = AES.new(self.secret[:32], AES.MODE_CBC, iv) return json.loads(unpad(cipher.decrypt(encrypted_data)))
bf39b4dbe258e62b6172b177fc9e6cf8a0c44f9a
expr/common.py
expr/common.py
from __future__ import print_function ADD_OP = '+' MULTIPLY_OP = '*' OPERATORS = [ADD_OP, MULTIPLY_OP] def pprint_expr_trees(trees): from parser import ExprParser print('[') for t in trees: print(' ', ExprParser(t)) print(']')
from __future__ import print_function ADD_OP = '+' MULTIPLY_OP = '*' OPERATORS = [ADD_OP, MULTIPLY_OP] def pprint_expr_trees(trees): print('[') for t in trees: print(' ', t) print(']')
Update pprint_expr_trees to adopt Expr
Update pprint_expr_trees to adopt Expr
Python
mit
admk/soap
from __future__ import print_function ADD_OP = '+' MULTIPLY_OP = '*' OPERATORS = [ADD_OP, MULTIPLY_OP] def pprint_expr_trees(trees): - from parser import ExprParser print('[') for t in trees: - print(' ', ExprParser(t)) + print(' ', t) print(']')
Update pprint_expr_trees to adopt Expr
## Code Before: from __future__ import print_function ADD_OP = '+' MULTIPLY_OP = '*' OPERATORS = [ADD_OP, MULTIPLY_OP] def pprint_expr_trees(trees): from parser import ExprParser print('[') for t in trees: print(' ', ExprParser(t)) print(']') ## Instruction: Update pprint_expr_trees to adopt Expr ## Code After: from __future__ import print_function ADD_OP = '+' MULTIPLY_OP = '*' OPERATORS = [ADD_OP, MULTIPLY_OP] def pprint_expr_trees(trees): print('[') for t in trees: print(' ', t) print(']')
4c092df630ee645c510199031503585d2b731668
dht.py
dht.py
import time import thread import Adafruit_DHT as dht import config import gpio_lock h = 0.0 t = 0.0 def get_ht_thread(): global h global t while True: gpio_lock.acquire() ht = dht.read_retry(dht.DHT22, config.DHT22_GPIO_NUM) gpio_lock.release() h = '{0:0.1f}'.format(ht[0]) t = '{0:0.1f}'.format(ht[1]) time.sleep(2) def get_ht(): return (h, t) thread.start_new_thread(get_ht_thread, ()) if __name__ == '__main__': ht = get_ht() print('The humidity and temperature:') print(ht)
import time import thread import string import Adafruit_DHT as dht import config import gpio_lock h = 0.0 t = 0.0 def get_ht_thread(): global h global t while True: gpio_lock.acquire() ht = dht.read_retry(dht.DHT22, config.DHT22_GPIO_NUM) gpio_lock.release() h = '{0:0.1f}'.format(ht[0]) t = '{0:0.1f}'.format(ht[1]) h = string.atof(h) t = string.atof(t) time.sleep(2) def get_ht(): return (h, t) thread.start_new_thread(get_ht_thread, ()) if __name__ == '__main__': ht = get_ht() print('The humidity and temperature:') print(ht)
Change a report data format
Change a report data format
Python
mit
yunbademo/yunba-smarthome,yunbademo/yunba-smarthome
import time import thread + import string import Adafruit_DHT as dht import config import gpio_lock h = 0.0 t = 0.0 def get_ht_thread(): global h global t while True: gpio_lock.acquire() ht = dht.read_retry(dht.DHT22, config.DHT22_GPIO_NUM) gpio_lock.release() h = '{0:0.1f}'.format(ht[0]) t = '{0:0.1f}'.format(ht[1]) + h = string.atof(h) + t = string.atof(t) time.sleep(2) def get_ht(): return (h, t) thread.start_new_thread(get_ht_thread, ()) if __name__ == '__main__': ht = get_ht() print('The humidity and temperature:') print(ht)
Change a report data format
## Code Before: import time import thread import Adafruit_DHT as dht import config import gpio_lock h = 0.0 t = 0.0 def get_ht_thread(): global h global t while True: gpio_lock.acquire() ht = dht.read_retry(dht.DHT22, config.DHT22_GPIO_NUM) gpio_lock.release() h = '{0:0.1f}'.format(ht[0]) t = '{0:0.1f}'.format(ht[1]) time.sleep(2) def get_ht(): return (h, t) thread.start_new_thread(get_ht_thread, ()) if __name__ == '__main__': ht = get_ht() print('The humidity and temperature:') print(ht) ## Instruction: Change a report data format ## Code After: import time import thread import string import Adafruit_DHT as dht import config import gpio_lock h = 0.0 t = 0.0 def get_ht_thread(): global h global t while True: gpio_lock.acquire() ht = dht.read_retry(dht.DHT22, config.DHT22_GPIO_NUM) gpio_lock.release() h = '{0:0.1f}'.format(ht[0]) t = '{0:0.1f}'.format(ht[1]) h = string.atof(h) t = string.atof(t) time.sleep(2) def get_ht(): return (h, t) thread.start_new_thread(get_ht_thread, ()) if __name__ == '__main__': ht = get_ht() print('The humidity and temperature:') print(ht)
01b8f325b0108ca1d1456fd2510e2d7fce678a57
turbustat/tests/test_pspec.py
turbustat/tests/test_pspec.py
''' Test functions for PSpec ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import PowerSpectrum, PSpec_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testPSpec(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_PSpec_method(self): self.tester = \ PowerSpectrum(dataset1["moment0"], weights=dataset1["moment0_error"][0] ** 2.) self.tester.run() npt.assert_allclose(self.tester.ps1D, computed_data['pspec_val']) def test_PSpec_distance(self): self.tester_dist = \ PSpec_Distance(dataset1["moment0"], dataset2["moment0"], weights1=dataset1["moment0_error"][0] ** 2., weights2=dataset2["moment0_error"][0] ** 2.) self.tester_dist.distance_metric() npt.assert_almost_equal(self.tester_dist.distance, computed_distances['pspec_distance'])
''' Test functions for PSpec ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import PowerSpectrum, PSpec_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testPSpec(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_PSpec_method(self): self.tester = \ PowerSpectrum(dataset1["moment0"], weights=dataset1["moment0_error"][0] ** 2.) self.tester.run() npt.assert_allclose(self.tester.ps1D, computed_data['pspec_val']) def test_PSpec_distance(self): self.tester_dist = \ PSpec_Distance(dataset1["moment0"], dataset2["moment0"], weights1=dataset1["moment0_error"][0] ** 2., weights2=dataset2["moment0_error"][0] ** 2.) self.tester_dist.distance_metric() npt.assert_almost_equal(self.tester_dist.distance, computed_distances['pspec_distance']) def test_pspec_nonequal_shape(): mom0_sliced = dataset1["moment0"][0][:16, :] mom0_hdr = dataset1["moment0"][1] test = PowerSpectrum((mom0_sliced, mom0_hdr)).run() test_T = PowerSpectrum((mom0_sliced.T, mom0_hdr)).run() npt.assert_almost_equal(test.slope, test_T.slope, decimal=7)
Add test to ensure power spectrum slope is same w/ transposed array
Add test to ensure power spectrum slope is same w/ transposed array
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
''' Test functions for PSpec ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import PowerSpectrum, PSpec_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testPSpec(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_PSpec_method(self): self.tester = \ PowerSpectrum(dataset1["moment0"], weights=dataset1["moment0_error"][0] ** 2.) self.tester.run() npt.assert_allclose(self.tester.ps1D, computed_data['pspec_val']) def test_PSpec_distance(self): self.tester_dist = \ PSpec_Distance(dataset1["moment0"], dataset2["moment0"], weights1=dataset1["moment0_error"][0] ** 2., weights2=dataset2["moment0_error"][0] ** 2.) self.tester_dist.distance_metric() npt.assert_almost_equal(self.tester_dist.distance, computed_distances['pspec_distance']) + + def test_pspec_nonequal_shape(): + + mom0_sliced = dataset1["moment0"][0][:16, :] + mom0_hdr = dataset1["moment0"][1] + + test = PowerSpectrum((mom0_sliced, mom0_hdr)).run() + test_T = PowerSpectrum((mom0_sliced.T, mom0_hdr)).run() + + npt.assert_almost_equal(test.slope, test_T.slope, decimal=7) +
Add test to ensure power spectrum slope is same w/ transposed array
## Code Before: ''' Test functions for PSpec ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import PowerSpectrum, PSpec_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testPSpec(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_PSpec_method(self): self.tester = \ PowerSpectrum(dataset1["moment0"], weights=dataset1["moment0_error"][0] ** 2.) self.tester.run() npt.assert_allclose(self.tester.ps1D, computed_data['pspec_val']) def test_PSpec_distance(self): self.tester_dist = \ PSpec_Distance(dataset1["moment0"], dataset2["moment0"], weights1=dataset1["moment0_error"][0] ** 2., weights2=dataset2["moment0_error"][0] ** 2.) self.tester_dist.distance_metric() npt.assert_almost_equal(self.tester_dist.distance, computed_distances['pspec_distance']) ## Instruction: Add test to ensure power spectrum slope is same w/ transposed array ## Code After: ''' Test functions for PSpec ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import PowerSpectrum, PSpec_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testPSpec(TestCase): def setUp(self): self.dataset1 = dataset1 self.dataset2 = dataset2 def test_PSpec_method(self): self.tester = \ PowerSpectrum(dataset1["moment0"], weights=dataset1["moment0_error"][0] ** 2.) self.tester.run() npt.assert_allclose(self.tester.ps1D, computed_data['pspec_val']) def test_PSpec_distance(self): self.tester_dist = \ PSpec_Distance(dataset1["moment0"], dataset2["moment0"], weights1=dataset1["moment0_error"][0] ** 2., weights2=dataset2["moment0_error"][0] ** 2.) self.tester_dist.distance_metric() npt.assert_almost_equal(self.tester_dist.distance, computed_distances['pspec_distance']) def test_pspec_nonequal_shape(): mom0_sliced = dataset1["moment0"][0][:16, :] mom0_hdr = dataset1["moment0"][1] test = PowerSpectrum((mom0_sliced, mom0_hdr)).run() test_T = PowerSpectrum((mom0_sliced.T, mom0_hdr)).run() npt.assert_almost_equal(test.slope, test_T.slope, decimal=7)
63946ef78a842b82064b560dd0f73c9a5fe7ac82
puzzle/urls.py
puzzle/urls.py
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
Replace deprecated login/logout function-based views
Replace deprecated login/logout function-based views
Python
mit
jomoore/threepins,jomoore/threepins,jomoore/threepins
from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), - url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), + url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), - url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), + url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
Replace deprecated login/logout function-based views
## Code Before: from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.login, {'template_name': 'puzzle/login.html'}, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'latest'}, name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ] ## Instruction: Replace deprecated login/logout function-based views ## Code After: from django.conf.urls import include, url from django.contrib.auth import views as auth_views from puzzle import views from puzzle.feeds import PuzzleFeed urlpatterns = [ #pylint: disable=invalid-name url(r'^$', views.latest, name='latest'), url(r'^login/$', auth_views.LoginView.as_view(template_name='puzzle/login.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(next_page='latest'), name='logout'), url(r'^create/$', views.create, name='create'), url(r'^save/$', views.save, name='save'), url(r'^rss/$', PuzzleFeed(), name='rss'), url(r'^archive/$', views.users, name='users'), url(r'^profile/$', views.profile, name='profile'), url(r'^puzzle/(?P<number>\d+)/$', views.puzzle_redirect), url(r'^setter/(?P<author>\w+)/(?P<number>\d+)/', include([ url(r'^$', views.puzzle, name='puzzle'), url(r'^solution/$', views.solution, name='solution'), url(r'^edit/$', views.edit, name='edit'), ])), ]
afeccc72042f1cfa69c07814420b3aeedeeab9e5
main.py
main.py
import sys from PyQt4 import QtCore, QtGui from UI.utilities.account_manager import AccountManager from UI.mainUI import MainUI from UI.initial_window import InitialWindowUI if __name__ == "__main__": QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtGui.QApplication(sys.argv) locale = QtCore.QLocale.system().name() qtTranslator = QtCore.QTranslator() # try to load translation if qtTranslator.load("" + locale, ":tra/"): app.installTranslator(qtTranslator) account_manager = AccountManager() if account_manager.if_logged_in(): myapp = MainUI() myapp.show() else: initial_window = InitialWindowUI() initial_window.show() sys.exit(app.exec_())
import sys from PyQt4 import QtCore, QtGui from UI.utilities.account_manager import AccountManager from UI.mainUI import MainUI from UI.initial_window import InitialWindowUI import configparser # needed for Windows package builder if __name__ == "__main__": QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtGui.QApplication(sys.argv) locale = QtCore.QLocale.system().name() qtTranslator = QtCore.QTranslator() # try to load translation if qtTranslator.load("" + locale, ":tra/"): app.installTranslator(qtTranslator) account_manager = AccountManager() if account_manager.if_logged_in(): myapp = MainUI() myapp.show() else: initial_window = InitialWindowUI() initial_window.show() sys.exit(app.exec_())
Add configparser import to avoid windows packager error
Add configparser import to avoid windows packager error
Python
mit
lakewik/storj-gui-client
import sys from PyQt4 import QtCore, QtGui from UI.utilities.account_manager import AccountManager from UI.mainUI import MainUI from UI.initial_window import InitialWindowUI + import configparser # needed for Windows package builder if __name__ == "__main__": QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtGui.QApplication(sys.argv) locale = QtCore.QLocale.system().name() qtTranslator = QtCore.QTranslator() # try to load translation if qtTranslator.load("" + locale, ":tra/"): app.installTranslator(qtTranslator) account_manager = AccountManager() if account_manager.if_logged_in(): myapp = MainUI() myapp.show() else: initial_window = InitialWindowUI() initial_window.show() sys.exit(app.exec_())
Add configparser import to avoid windows packager error
## Code Before: import sys from PyQt4 import QtCore, QtGui from UI.utilities.account_manager import AccountManager from UI.mainUI import MainUI from UI.initial_window import InitialWindowUI if __name__ == "__main__": QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtGui.QApplication(sys.argv) locale = QtCore.QLocale.system().name() qtTranslator = QtCore.QTranslator() # try to load translation if qtTranslator.load("" + locale, ":tra/"): app.installTranslator(qtTranslator) account_manager = AccountManager() if account_manager.if_logged_in(): myapp = MainUI() myapp.show() else: initial_window = InitialWindowUI() initial_window.show() sys.exit(app.exec_()) ## Instruction: Add configparser import to avoid windows packager error ## Code After: import sys from PyQt4 import QtCore, QtGui from UI.utilities.account_manager import AccountManager from UI.mainUI import MainUI from UI.initial_window import InitialWindowUI import configparser # needed for Windows package builder if __name__ == "__main__": QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtGui.QApplication(sys.argv) locale = QtCore.QLocale.system().name() qtTranslator = QtCore.QTranslator() # try to load translation if qtTranslator.load("" + locale, ":tra/"): app.installTranslator(qtTranslator) account_manager = AccountManager() if account_manager.if_logged_in(): myapp = MainUI() myapp.show() else: initial_window = InitialWindowUI() initial_window.show() sys.exit(app.exec_())
324beaae091b2bc4699d4840ccd313aa0645b07e
nets.py
nets.py
class FeedForwardNet: pass
from layers import InputLayer, Layer, OutputLayer import math import random class FeedForwardNet(object): def __init__(self, inlayersize, layersize, outlayersize): self._inlayer = InputLayer(inlayersize) self._middlelayer = Layer(layersize) self._outlayer = OutputLayer(outlayersize) self._inlayer.connect_layer(self._middlelayer) self._middlelayer.connect_layer(self._outlayer) @property def neurons(self): return [self._inlayer.neurons, self._middlelayer.neurons, self._outlayer.neurons] def train(self, inputs, targets, verbose=False): ''' inputs: a sequence of floats that map to the input neurons targetlabels: a sequence of floats that are the desired output neuron values. ''' self._inlayer.inputs = inputs self._middlelayer.propagate() self._outlayer.propagate() self._outlayer.backpropagate1(targets) self._middlelayer.backpropagate1() self._outlayer.backpropagate2() self._middlelayer.backpropagate2() if verbose: print("Training results") print("\tInput: {0}".format(inputs)) print("\tTarget output: {0}".format(targets)) print("\tActual output: {0}".format(self._outlayer.outputs)) self.display_signals() print("") raw_input() def predict(self, inputs): ''' inputs: a sequence of floats that map to the input neurons return: a sequence of floats mapped from the output neurons ''' self._inlayer.inputs = inputs self._middlelayer.propagate() self._outlayer.propagate() return self._outlayer.outputs def display_signals(self): col1 = self._inlayer.inputs col2 = [x.signal for x in self._middlelayer.neurons] col3 = self._outlayer.outputs numrows = max(len(col1), len(col2), len(col3)) roundto = 3 #round to print("Signals") print("\tInput\tHidden\tOutput") for row in range(numrows): line = [] for col in col1, col2, col3: if len(col)-1 < row: line.append("") else: element = round(col[row], roundto) element = str(element) line.append(element) print('\t' + '\t'.join(line)) if __name__ == '__main__': f = FeedForwardNet(1, 2, 1) for i in range(50000): f.train((1, 1), (0,)) f.train((1, 0), (1,)) f.train((0, 1), (1,)) f.train((0, 0), (0,)) while True: x = input("Input: ") y = f.predict(x) print("Output: {0}".format(y))
Add main code and feed forward net class
Add main code and feed forward net class It can XOR, but sin function still fails
Python
mit
tmerr/trevornet
- class FeedForwardNet: - pass + from layers import InputLayer, Layer, OutputLayer + import math + import random + class FeedForwardNet(object): + def __init__(self, inlayersize, layersize, outlayersize): + self._inlayer = InputLayer(inlayersize) + self._middlelayer = Layer(layersize) + self._outlayer = OutputLayer(outlayersize) + + self._inlayer.connect_layer(self._middlelayer) + self._middlelayer.connect_layer(self._outlayer) + + @property + def neurons(self): + return [self._inlayer.neurons, self._middlelayer.neurons, self._outlayer.neurons] + + def train(self, inputs, targets, verbose=False): + ''' + inputs: a sequence of floats that map to the input neurons + targetlabels: a sequence of floats that are the desired output neuron + values. + ''' + + self._inlayer.inputs = inputs + self._middlelayer.propagate() + self._outlayer.propagate() + + self._outlayer.backpropagate1(targets) + self._middlelayer.backpropagate1() + + self._outlayer.backpropagate2() + self._middlelayer.backpropagate2() + + if verbose: + print("Training results") + print("\tInput: {0}".format(inputs)) + print("\tTarget output: {0}".format(targets)) + print("\tActual output: {0}".format(self._outlayer.outputs)) + self.display_signals() + print("") + raw_input() + + def predict(self, inputs): + ''' + inputs: a sequence of floats that map to the input neurons + return: a sequence of floats mapped from the output neurons + ''' + self._inlayer.inputs = inputs + self._middlelayer.propagate() + self._outlayer.propagate() + return self._outlayer.outputs + + def display_signals(self): + col1 = self._inlayer.inputs + col2 = [x.signal for x in self._middlelayer.neurons] + col3 = self._outlayer.outputs + numrows = max(len(col1), len(col2), len(col3)) + + roundto = 3 #round to + print("Signals") + print("\tInput\tHidden\tOutput") + for row in range(numrows): + line = [] + for col in col1, col2, col3: + if len(col)-1 < row: + line.append("") + else: + element = round(col[row], roundto) + element = str(element) + line.append(element) + print('\t' + '\t'.join(line)) + + if __name__ == '__main__': + f = FeedForwardNet(1, 2, 1) + + for i in range(50000): + f.train((1, 1), (0,)) + f.train((1, 0), (1,)) + f.train((0, 1), (1,)) + f.train((0, 0), (0,)) + + while True: + x = input("Input: ") + y = f.predict(x) + print("Output: {0}".format(y)) +
Add main code and feed forward net class
## Code Before: class FeedForwardNet: pass ## Instruction: Add main code and feed forward net class ## Code After: from layers import InputLayer, Layer, OutputLayer import math import random class FeedForwardNet(object): def __init__(self, inlayersize, layersize, outlayersize): self._inlayer = InputLayer(inlayersize) self._middlelayer = Layer(layersize) self._outlayer = OutputLayer(outlayersize) self._inlayer.connect_layer(self._middlelayer) self._middlelayer.connect_layer(self._outlayer) @property def neurons(self): return [self._inlayer.neurons, self._middlelayer.neurons, self._outlayer.neurons] def train(self, inputs, targets, verbose=False): ''' inputs: a sequence of floats that map to the input neurons targetlabels: a sequence of floats that are the desired output neuron values. ''' self._inlayer.inputs = inputs self._middlelayer.propagate() self._outlayer.propagate() self._outlayer.backpropagate1(targets) self._middlelayer.backpropagate1() self._outlayer.backpropagate2() self._middlelayer.backpropagate2() if verbose: print("Training results") print("\tInput: {0}".format(inputs)) print("\tTarget output: {0}".format(targets)) print("\tActual output: {0}".format(self._outlayer.outputs)) self.display_signals() print("") raw_input() def predict(self, inputs): ''' inputs: a sequence of floats that map to the input neurons return: a sequence of floats mapped from the output neurons ''' self._inlayer.inputs = inputs self._middlelayer.propagate() self._outlayer.propagate() return self._outlayer.outputs def display_signals(self): col1 = self._inlayer.inputs col2 = [x.signal for x in self._middlelayer.neurons] col3 = self._outlayer.outputs numrows = max(len(col1), len(col2), len(col3)) roundto = 3 #round to print("Signals") print("\tInput\tHidden\tOutput") for row in range(numrows): line = [] for col in col1, col2, col3: if len(col)-1 < row: line.append("") else: element = round(col[row], roundto) element = str(element) line.append(element) print('\t' + '\t'.join(line)) if __name__ == '__main__': f = FeedForwardNet(1, 2, 1) for i in range(50000): f.train((1, 1), (0,)) f.train((1, 0), (1,)) f.train((0, 1), (1,)) f.train((0, 0), (0,)) while True: x = input("Input: ") y = f.predict(x) print("Output: {0}".format(y))
ef4da4f081c083d88297795d145529c543d2595e
spam.py
spam.py
from sklearn.cross_validation import train_test_split from dataset_meta import DATASET_META from spam.common.utils import get_file_path_list file_path_list = get_file_path_list(DATASET_META) path, classification = zip(*file_path_list) unlabeled_path, labeled_path, \ unlabeled_class, labeled_class = train_test_split( path, classification, test_size=0.1, ) print(len(unlabeled_path)) print(len(unlabeled_class)) print(len(labeled_path)) print(len(labeled_class))
from sklearn.cross_validation import train_test_split from dataset_meta import DATASET_META from spam.common.utils import get_file_path_list file_path_list = get_file_path_list(DATASET_META) # transform list of tuple into two list # e.g. [('/path/to/file', 'spam')] ==> ['path/to/file'], ['spam'] path, classification = zip(*file_path_list) # split the data into unlabeled labeled unlabeled_path, labeled_path, \ unlabeled_class, labeled_class = train_test_split( path, classification, test_size=0.1, random_state=0, )
Set random state to 0, add comments and remove print.
Set random state to 0, add comments and remove print.
Python
mit
benigls/spam,benigls/spam
from sklearn.cross_validation import train_test_split from dataset_meta import DATASET_META from spam.common.utils import get_file_path_list file_path_list = get_file_path_list(DATASET_META) + + # transform list of tuple into two list + # e.g. [('/path/to/file', 'spam')] ==> ['path/to/file'], ['spam'] path, classification = zip(*file_path_list) + # split the data into unlabeled labeled unlabeled_path, labeled_path, \ unlabeled_class, labeled_class = train_test_split( path, classification, test_size=0.1, + random_state=0, ) - print(len(unlabeled_path)) - print(len(unlabeled_class)) - print(len(labeled_path)) - print(len(labeled_class)) -
Set random state to 0, add comments and remove print.
## Code Before: from sklearn.cross_validation import train_test_split from dataset_meta import DATASET_META from spam.common.utils import get_file_path_list file_path_list = get_file_path_list(DATASET_META) path, classification = zip(*file_path_list) unlabeled_path, labeled_path, \ unlabeled_class, labeled_class = train_test_split( path, classification, test_size=0.1, ) print(len(unlabeled_path)) print(len(unlabeled_class)) print(len(labeled_path)) print(len(labeled_class)) ## Instruction: Set random state to 0, add comments and remove print. ## Code After: from sklearn.cross_validation import train_test_split from dataset_meta import DATASET_META from spam.common.utils import get_file_path_list file_path_list = get_file_path_list(DATASET_META) # transform list of tuple into two list # e.g. [('/path/to/file', 'spam')] ==> ['path/to/file'], ['spam'] path, classification = zip(*file_path_list) # split the data into unlabeled labeled unlabeled_path, labeled_path, \ unlabeled_class, labeled_class = train_test_split( path, classification, test_size=0.1, random_state=0, )
718bd57ff648d431d8986a48d1c66877098c4081
urls.py
urls.py
from django.conf.urls import patterns, include, url from . import methods urlpatterns = patterns('', url(r'^crashreport\/submit\.php$', methods.post_crashreport, name='post_crashreport'), url(r'^issues\.xml$', methods.post_issue, name='post_issue'), )
from django.conf.urls import include, url from . import methods urlpatterns = ( url(r'^crashreport\/submit\.php$', methods.post_crashreport, name='post_crashreport'), url(r'^issues\.xml$', methods.post_issue, name='post_issue'), )
Update to Django 1.11.19 including updates to various dependencies
Update to Django 1.11.19 including updates to various dependencies
Python
mit
mback2k/django-app-bugs
- from django.conf.urls import patterns, include, url + from django.conf.urls import include, url from . import methods - urlpatterns = patterns('', + urlpatterns = ( url(r'^crashreport\/submit\.php$', methods.post_crashreport, name='post_crashreport'), url(r'^issues\.xml$', methods.post_issue, name='post_issue'), )
Update to Django 1.11.19 including updates to various dependencies
## Code Before: from django.conf.urls import patterns, include, url from . import methods urlpatterns = patterns('', url(r'^crashreport\/submit\.php$', methods.post_crashreport, name='post_crashreport'), url(r'^issues\.xml$', methods.post_issue, name='post_issue'), ) ## Instruction: Update to Django 1.11.19 including updates to various dependencies ## Code After: from django.conf.urls import include, url from . import methods urlpatterns = ( url(r'^crashreport\/submit\.php$', methods.post_crashreport, name='post_crashreport'), url(r'^issues\.xml$', methods.post_issue, name='post_issue'), )
d5240626528547e112c78af633c1f4494a5c6d91
common/lib/xmodule/xmodule/modulestore/django.py
common/lib/xmodule/xmodule/modulestore/django.py
from __future__ import absolute_import from importlib import import_module from django.conf import settings _MODULESTORES = {} FUNCTION_KEYS = ['render_template'] def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def modulestore(name='default'): global _MODULESTORES if name not in _MODULESTORES: class_ = load_function(settings.MODULESTORE[name]['ENGINE']) options = {} options.update(settings.MODULESTORE[name]['OPTIONS']) for key in FUNCTION_KEYS: if key in options: options[key] = load_function(options[key]) _MODULESTORES[name] = class_( **options ) return _MODULESTORES[name] # Initialize the modulestores immediately for store_name in settings.MODULESTORE: modulestore(store_name)
from __future__ import absolute_import from importlib import import_module from os import environ from django.conf import settings _MODULESTORES = {} FUNCTION_KEYS = ['render_template'] def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def modulestore(name='default'): global _MODULESTORES if name not in _MODULESTORES: class_ = load_function(settings.MODULESTORE[name]['ENGINE']) options = {} options.update(settings.MODULESTORE[name]['OPTIONS']) for key in FUNCTION_KEYS: if key in options: options[key] = load_function(options[key]) _MODULESTORES[name] = class_( **options ) return _MODULESTORES[name] if 'DJANGO_SETTINGS_MODULE' in environ: # Initialize the modulestores immediately for store_name in settings.MODULESTORE: modulestore(store_name)
Put quick check so we don't load course modules on init unless we're actually running in Django
Put quick check so we don't load course modules on init unless we're actually running in Django
Python
agpl-3.0
knehez/edx-platform,sudheerchintala/LearnEraPlatForm,lduarte1991/edx-platform,nanolearningllc/edx-platform-cypress,eestay/edx-platform,prarthitm/edxplatform,caesar2164/edx-platform,atsolakid/edx-platform,chauhanhardik/populo,CredoReference/edx-platform,motion2015/edx-platform,shabab12/edx-platform,shubhdev/openedx,Shrhawk/edx-platform,prarthitm/edxplatform,Softmotions/edx-platform,jruiperezv/ANALYSE,jamesblunt/edx-platform,deepsrijit1105/edx-platform,unicri/edx-platform,arbrandes/edx-platform,itsjeyd/edx-platform,ak2703/edx-platform,DNFcode/edx-platform,cselis86/edx-platform,knehez/edx-platform,cpennington/edx-platform,bigdatauniversity/edx-platform,wwj718/edx-platform,jazztpt/edx-platform,nanolearning/edx-platform,ahmadio/edx-platform,OmarIthawi/edx-platform,analyseuc3m/ANALYSE-v1,RPI-OPENEDX/edx-platform,wwj718/edx-platform,halvertoluke/edx-platform,torchingloom/edx-platform,nanolearningllc/edx-platform-cypress,rue89-tech/edx-platform,nttks/jenkins-test,martynovp/edx-platform,deepsrijit1105/edx-platform,jswope00/GAI,shubhdev/edxOnBaadal,nikolas/edx-platform,msegado/edx-platform,pabloborrego93/edx-platform,doganov/edx-platform,msegado/edx-platform,jonathan-beard/edx-platform,CredoReference/edx-platform,TsinghuaX/edx-platform,solashirai/edx-platform,adoosii/edx-platform,apigee/edx-platform,defance/edx-platform,andyzsf/edx,unicri/edx-platform,hmcmooc/muddx-platform,cpennington/edx-platform,wwj718/ANALYSE,vasyarv/edx-platform,hamzehd/edx-platform,kalebhartje/schoolboost,olexiim/edx-platform,beni55/edx-platform,nanolearning/edx-platform,mtlchun/edx,iivic/BoiseStateX,caesar2164/edx-platform,jonathan-beard/edx-platform,kxliugang/edx-platform,shurihell/testasia,chudaol/edx-platform,ampax/edx-platform-backup,atsolakid/edx-platform,rationalAgent/edx-platform-custom,pelikanchik/edx-platform,simbs/edx-platform,hkawasaki/kawasaki-aio8-0,kamalx/edx-platform,jazkarta/edx-platform-for-isc,UXE/local-edx,eestay/edx-platform,a-parhom/edx-platform,morpheby/levelup-by,ahmedaljazzar/edx-platform,bitifirefly/edx-platform,peterm-itr/edx-platform,raccoongang/edx-platform,Edraak/edx-platform,Shrhawk/edx-platform,kmoocdev/edx-platform,leansoft/edx-platform,atsolakid/edx-platform,EduPepperPD/pepper2013,hamzehd/edx-platform,gsehub/edx-platform,morenopc/edx-platform,apigee/edx-platform,SivilTaram/edx-platform,chand3040/cloud_that,CourseTalk/edx-platform,fintech-circle/edx-platform,MSOpenTech/edx-platform,B-MOOC/edx-platform,beni55/edx-platform,zhenzhai/edx-platform,dsajkl/reqiop,zofuthan/edx-platform,fly19890211/edx-platform,edry/edx-platform,atsolakid/edx-platform,adoosii/edx-platform,zerobatu/edx-platform,xinjiguaike/edx-platform,tanmaykm/edx-platform,simbs/edx-platform,nttks/jenkins-test,TsinghuaX/edx-platform,eemirtekin/edx-platform,ak2703/edx-platform,vismartltd/edx-platform,DefyVentures/edx-platform,devs1991/test_edx_docmode,olexiim/edx-platform,hastexo/edx-platform,Ayub-Khan/edx-platform,cselis86/edx-platform,tiagochiavericosta/edx-platform,iivic/BoiseStateX,teltek/edx-platform,dsajkl/reqiop,DefyVentures/edx-platform,marcore/edx-platform,kxliugang/edx-platform,teltek/edx-platform,xuxiao19910803/edx-platform,philanthropy-u/edx-platform,Softmotions/edx-platform,edry/edx-platform,appliedx/edx-platform,longmen21/edx-platform,analyseuc3m/ANALYSE-v1,edx-solutions/edx-platform,raccoongang/edx-platform,unicri/edx-platform,devs1991/test_edx_docmode,hkawasaki/kawasaki-aio8-2,ampax/edx-platform,zubair-arbi/edx-platform,yokose-ks/edx-platform,xingyepei/edx-platform,WatanabeYasumasa/edx-platform,arbrandes/edx-platform,motion2015/edx-platform,SravanthiSinha/edx-platform,wwj718/ANALYSE,ahmedaljazzar/edx-platform,ESOedX/edx-platform,UOMx/edx-platform,caesar2164/edx-platform,xinjiguaike/edx-platform,IITBinterns13/edx-platform-dev,vasyarv/edx-platform,jazkarta/edx-platform,marcore/edx-platform,fly19890211/edx-platform,4eek/edx-platform,mjg2203/edx-platform-seas,nanolearningllc/edx-platform-cypress,appsembler/edx-platform,a-parhom/edx-platform,tiagochiavericosta/edx-platform,raccoongang/edx-platform,shubhdev/edx-platform,naresh21/synergetics-edx-platform,gymnasium/edx-platform,tanmaykm/edx-platform,a-parhom/edx-platform,carsongee/edx-platform,Stanford-Online/edx-platform,hkawasaki/kawasaki-aio8-2,hmcmooc/muddx-platform,y12uc231/edx-platform,zerobatu/edx-platform,chauhanhardik/populo_2,IITBinterns13/edx-platform-dev,ampax/edx-platform,syjeon/new_edx,kmoocdev2/edx-platform,eemirtekin/edx-platform,CourseTalk/edx-platform,vismartltd/edx-platform,eduNEXT/edunext-platform,xuxiao19910803/edx,yokose-ks/edx-platform,syjeon/new_edx,J861449197/edx-platform,IONISx/edx-platform,louyihua/edx-platform,romain-li/edx-platform,xinjiguaike/edx-platform,martynovp/edx-platform,edx/edx-platform,sameetb-cuelogic/edx-platform-test,angelapper/edx-platform,DefyVentures/edx-platform,nanolearning/edx-platform,ahmedaljazzar/edx-platform,Ayub-Khan/edx-platform,alexthered/kienhoc-platform,jazkarta/edx-platform,AkA84/edx-platform,Kalyzee/edx-platform,LICEF/edx-platform,zadgroup/edx-platform,mushtaqak/edx-platform,shubhdev/edxOnBaadal,hkawasaki/kawasaki-aio8-1,jazztpt/edx-platform,JioEducation/edx-platform,ferabra/edx-platform,SivilTaram/edx-platform,cyanna/edx-platform,beacloudgenius/edx-platform,y12uc231/edx-platform,cyanna/edx-platform,mjg2203/edx-platform-seas,utecuy/edx-platform,hastexo/edx-platform,mitocw/edx-platform,stvstnfrd/edx-platform,Livit/Livit.Learn.EdX,Edraak/circleci-edx-platform,amir-qayyum-khan/edx-platform,nanolearning/edx-platform,cyanna/edx-platform,alexthered/kienhoc-platform,mcgachey/edx-platform,mcgachey/edx-platform,shubhdev/openedx,rue89-tech/edx-platform,ovnicraft/edx-platform,JCBarahona/edX,EDUlib/edx-platform,cognitiveclass/edx-platform,Shrhawk/edx-platform,miptliot/edx-platform,ahmadiga/min_edx,nttks/edx-platform,teltek/edx-platform,praveen-pal/edx-platform,EduPepperPD/pepper2013,inares/edx-platform,shashank971/edx-platform,cselis86/edx-platform,utecuy/edx-platform,WatanabeYasumasa/edx-platform,alexthered/kienhoc-platform,jazkarta/edx-platform-for-isc,shubhdev/edx-platform,miptliot/edx-platform,jazkarta/edx-platform-for-isc,auferack08/edx-platform,kalebhartje/schoolboost,jbassen/edx-platform,jbassen/edx-platform,pepeportela/edx-platform,JCBarahona/edX,martynovp/edx-platform,peterm-itr/edx-platform,vasyarv/edx-platform,naresh21/synergetics-edx-platform,CredoReference/edx-platform,hkawasaki/kawasaki-aio8-1,jamesblunt/edx-platform,bitifirefly/edx-platform,apigee/edx-platform,xingyepei/edx-platform,jolyonb/edx-platform,hastexo/edx-platform,10clouds/edx-platform,mcgachey/edx-platform,bdero/edx-platform,shubhdev/edx-platform,simbs/edx-platform,nagyistoce/edx-platform,valtech-mooc/edx-platform,nttks/jenkins-test,torchingloom/edx-platform,pelikanchik/edx-platform,antoviaque/edx-platform,synergeticsedx/deployment-wipro,bdero/edx-platform,cecep-edu/edx-platform,zofuthan/edx-platform,rhndg/openedx,tanmaykm/edx-platform,doismellburning/edx-platform,jelugbo/tundex,don-github/edx-platform,rismalrv/edx-platform,syjeon/new_edx,IITBinterns13/edx-platform-dev,dsajkl/123,msegado/edx-platform,cselis86/edx-platform,jonathan-beard/edx-platform,chrisndodge/edx-platform,EDUlib/edx-platform,devs1991/test_edx_docmode,ampax/edx-platform-backup,EduPepperPD/pepper2013,J861449197/edx-platform,benpatterson/edx-platform,leansoft/edx-platform,jzoldak/edx-platform,Livit/Livit.Learn.EdX,nttks/jenkins-test,deepsrijit1105/edx-platform,J861449197/edx-platform,cognitiveclass/edx-platform,jonathan-beard/edx-platform,hkawasaki/kawasaki-aio8-0,IONISx/edx-platform,zhenzhai/edx-platform,simbs/edx-platform,TeachAtTUM/edx-platform,xuxiao19910803/edx,abdoosh00/edraak,proversity-org/edx-platform,waheedahmed/edx-platform,valtech-mooc/edx-platform,LearnEra/LearnEraPlaftform,bigdatauniversity/edx-platform,UXE/local-edx,kmoocdev/edx-platform,zofuthan/edx-platform,kmoocdev2/edx-platform,jruiperezv/ANALYSE,jruiperezv/ANALYSE,iivic/BoiseStateX,pku9104038/edx-platform,CourseTalk/edx-platform,praveen-pal/edx-platform,edx/edx-platform,B-MOOC/edx-platform,solashirai/edx-platform,solashirai/edx-platform,UOMx/edx-platform,bigdatauniversity/edx-platform,yokose-ks/edx-platform,4eek/edx-platform,fly19890211/edx-platform,hmcmooc/muddx-platform,mjirayu/sit_academy,lduarte1991/edx-platform,zhenzhai/edx-platform,longmen21/edx-platform,jamiefolsom/edx-platform,ubc/edx-platform,jazztpt/edx-platform,auferack08/edx-platform,auferack08/edx-platform,kxliugang/edx-platform,dkarakats/edx-platform,jbzdak/edx-platform,pomegranited/edx-platform,inares/edx-platform,zhenzhai/edx-platform,cselis86/edx-platform,mcgachey/edx-platform,bitifirefly/edx-platform,dcosentino/edx-platform,halvertoluke/edx-platform,synergeticsedx/deployment-wipro,kursitet/edx-platform,shabab12/edx-platform,kalebhartje/schoolboost,ESOedX/edx-platform,nttks/edx-platform,EduPepperPDTesting/pepper2013-testing,zadgroup/edx-platform,IndonesiaX/edx-platform,IONISx/edx-platform,MSOpenTech/edx-platform,Softmotions/edx-platform,TeachAtTUM/edx-platform,Lektorium-LLC/edx-platform,SravanthiSinha/edx-platform,ZLLab-Mooc/edx-platform,chauhanhardik/populo,carsongee/edx-platform,jswope00/griffinx,jzoldak/edx-platform,BehavioralInsightsTeam/edx-platform,jbzdak/edx-platform,Edraak/edx-platform,rhndg/openedx,vikas1885/test1,shashank971/edx-platform,shubhdev/edxOnBaadal,xuxiao19910803/edx-platform,Edraak/edraak-platform,Ayub-Khan/edx-platform,wwj718/edx-platform,morenopc/edx-platform,utecuy/edx-platform,jazkarta/edx-platform-for-isc,adoosii/edx-platform,edx-solutions/edx-platform,hamzehd/edx-platform,xuxiao19910803/edx,vikas1885/test1,jelugbo/tundex,motion2015/a3,kursitet/edx-platform,Kalyzee/edx-platform,dkarakats/edx-platform,hastexo/edx-platform,ahmadio/edx-platform,polimediaupv/edx-platform,wwj718/ANALYSE,ferabra/edx-platform,BehavioralInsightsTeam/edx-platform,UOMx/edx-platform,gymnasium/edx-platform,vismartltd/edx-platform,IONISx/edx-platform,jzoldak/edx-platform,mitocw/edx-platform,benpatterson/edx-platform,ahmedaljazzar/edx-platform,miptliot/edx-platform,hkawasaki/kawasaki-aio8-1,Endika/edx-platform,vikas1885/test1,vismartltd/edx-platform,morenopc/edx-platform,edry/edx-platform,playm2mboy/edx-platform,jolyonb/edx-platform,cecep-edu/edx-platform,shubhdev/edxOnBaadal,fintech-circle/edx-platform,jjmiranda/edx-platform,jjmiranda/edx-platform,mushtaqak/edx-platform,benpatterson/edx-platform,Livit/Livit.Learn.EdX,eduNEXT/edunext-platform,gymnasium/edx-platform,arifsetiawan/edx-platform,mcgachey/edx-platform,ubc/edx-platform,chand3040/cloud_that,pelikanchik/edx-platform,zubair-arbi/edx-platform,stvstnfrd/edx-platform,lduarte1991/edx-platform,chudaol/edx-platform,rhndg/openedx,PepperPD/edx-pepper-platform,louyihua/edx-platform,unicri/edx-platform,antonve/s4-project-mooc,J861449197/edx-platform,SivilTaram/edx-platform,appsembler/edx-platform,valtech-mooc/edx-platform,xingyepei/edx-platform,franosincic/edx-platform,nanolearningllc/edx-platform-cypress,Edraak/edraak-platform,fly19890211/edx-platform,Livit/Livit.Learn.EdX,alexthered/kienhoc-platform,pomegranited/edx-platform,nikolas/edx-platform,Shrhawk/edx-platform,stvstnfrd/edx-platform,LearnEra/LearnEraPlaftform,chudaol/edx-platform,CredoReference/edx-platform,eduNEXT/edx-platform,abdoosh00/edx-rtl-final,antoviaque/edx-platform,synergeticsedx/deployment-wipro,valtech-mooc/edx-platform,MakeHer/edx-platform,abdoosh00/edx-rtl-final,motion2015/edx-platform,shubhdev/openedx,JCBarahona/edX,franosincic/edx-platform,nikolas/edx-platform,ZLLab-Mooc/edx-platform,Lektorium-LLC/edx-platform,kalebhartje/schoolboost,bdero/edx-platform,ampax/edx-platform-backup,4eek/edx-platform,beacloudgenius/edx-platform,analyseuc3m/ANALYSE-v1,Endika/edx-platform,MSOpenTech/edx-platform,nagyistoce/edx-platform,B-MOOC/edx-platform,nikolas/edx-platform,pepeportela/edx-platform,y12uc231/edx-platform,appliedx/edx-platform,cecep-edu/edx-platform,openfun/edx-platform,auferack08/edx-platform,dsajkl/123,Softmotions/edx-platform,SravanthiSinha/edx-platform,Edraak/circleci-edx-platform,angelapper/edx-platform,valtech-mooc/edx-platform,OmarIthawi/edx-platform,utecuy/edx-platform,kmoocdev2/edx-platform,mjirayu/sit_academy,tiagochiavericosta/edx-platform,etzhou/edx-platform,don-github/edx-platform,hkawasaki/kawasaki-aio8-2,dkarakats/edx-platform,SivilTaram/edx-platform,kamalx/edx-platform,Unow/edx-platform,rationalAgent/edx-platform-custom,jswope00/GAI,dcosentino/edx-platform,MakeHer/edx-platform,devs1991/test_edx_docmode,ahmadiga/min_edx,jamiefolsom/edx-platform,shashank971/edx-platform,mtlchun/edx,antoviaque/edx-platform,franosincic/edx-platform,stvstnfrd/edx-platform,B-MOOC/edx-platform,longmen21/edx-platform,CourseTalk/edx-platform,nanolearning/edx-platform,dcosentino/edx-platform,jswope00/GAI,dsajkl/123,Semi-global/edx-platform,motion2015/edx-platform,amir-qayyum-khan/edx-platform,devs1991/test_edx_docmode,shurihell/testasia,Kalyzee/edx-platform,pabloborrego93/edx-platform,hamzehd/edx-platform,wwj718/edx-platform,chudaol/edx-platform,ferabra/edx-platform,knehez/edx-platform,hkawasaki/kawasaki-aio8-1,leansoft/edx-platform,kxliugang/edx-platform,4eek/edx-platform,mahendra-r/edx-platform,Endika/edx-platform,polimediaupv/edx-platform,eemirtekin/edx-platform,y12uc231/edx-platform,ovnicraft/edx-platform,olexiim/edx-platform,JioEducation/edx-platform,mushtaqak/edx-platform,bigdatauniversity/edx-platform,J861449197/edx-platform,kursitet/edx-platform,abdoosh00/edx-rtl-final,pabloborrego93/edx-platform,appsembler/edx-platform,hkawasaki/kawasaki-aio8-0,vikas1885/test1,xingyepei/edx-platform,DNFcode/edx-platform,naresh21/synergetics-edx-platform,EDUlib/edx-platform,jbassen/edx-platform,zerobatu/edx-platform,SravanthiSinha/edx-platform,kxliugang/edx-platform,Edraak/circleci-edx-platform,eestay/edx-platform,etzhou/edx-platform,praveen-pal/edx-platform,louyihua/edx-platform,gsehub/edx-platform,xuxiao19910803/edx-platform,prarthitm/edxplatform,rismalrv/edx-platform,kmoocdev/edx-platform,Edraak/circleci-edx-platform,shashank971/edx-platform,jzoldak/edx-platform,MSOpenTech/edx-platform,vasyarv/edx-platform,iivic/BoiseStateX,morenopc/edx-platform,TsinghuaX/edx-platform,eestay/edx-platform,Semi-global/edx-platform,procangroup/edx-platform,etzhou/edx-platform,vikas1885/test1,jruiperezv/ANALYSE,devs1991/test_edx_docmode,nanolearningllc/edx-platform-cypress,ubc/edx-platform,dkarakats/edx-platform,mahendra-r/edx-platform,wwj718/ANALYSE,nttks/edx-platform,EduPepperPDTesting/pepper2013-testing,chudaol/edx-platform,polimediaupv/edx-platform,eduNEXT/edx-platform,doismellburning/edx-platform,LICEF/edx-platform,kursitet/edx-platform,ubc/edx-platform,antonve/s4-project-mooc,zubair-arbi/edx-platform,torchingloom/edx-platform,louyihua/edx-platform,UXE/local-edx,morpheby/levelup-by,pabloborrego93/edx-platform,angelapper/edx-platform,EduPepperPDTesting/pepper2013-testing,cyanna/edx-platform,EduPepperPDTesting/pepper2013-testing,hkawasaki/kawasaki-aio8-0,arifsetiawan/edx-platform,appliedx/edx-platform,alexthered/kienhoc-platform,ahmadio/edx-platform,RPI-OPENEDX/edx-platform,amir-qayyum-khan/edx-platform,zofuthan/edx-platform,jswope00/griffinx,cognitiveclass/edx-platform,appsembler/edx-platform,philanthropy-u/edx-platform,jbzdak/edx-platform,devs1991/test_edx_docmode,edx-solutions/edx-platform,ak2703/edx-platform,romain-li/edx-platform,Edraak/edraak-platform,abdoosh00/edraak,jamiefolsom/edx-platform,franosincic/edx-platform,ferabra/edx-platform,jazkarta/edx-platform-for-isc,msegado/edx-platform,xinjiguaike/edx-platform,ahmadiga/min_edx,pelikanchik/edx-platform,RPI-OPENEDX/edx-platform,tiagochiavericosta/edx-platform,beacloudgenius/edx-platform,doganov/edx-platform,martynovp/edx-platform,zadgroup/edx-platform,amir-qayyum-khan/edx-platform,IndonesiaX/edx-platform,jazkarta/edx-platform,rationalAgent/edx-platform-custom,nanolearningllc/edx-platform-cypress-2,nanolearningllc/edx-platform-cypress-2,Edraak/edraak-platform,itsjeyd/edx-platform,teltek/edx-platform,doganov/edx-platform,bitifirefly/edx-platform,sameetb-cuelogic/edx-platform-test,kmoocdev2/edx-platform,cecep-edu/edx-platform,10clouds/edx-platform,beacloudgenius/edx-platform,arifsetiawan/edx-platform,shurihell/testasia,inares/edx-platform,rismalrv/edx-platform,Edraak/edx-platform,dsajkl/123,jbassen/edx-platform,Ayub-Khan/edx-platform,jolyonb/edx-platform,chauhanhardik/populo_2,edx/edx-platform,DefyVentures/edx-platform,knehez/edx-platform,defance/edx-platform,apigee/edx-platform,DNFcode/edx-platform,shubhdev/openedx,10clouds/edx-platform,WatanabeYasumasa/edx-platform,zhenzhai/edx-platform,pepeportela/edx-platform,mtlchun/edx,BehavioralInsightsTeam/edx-platform,jolyonb/edx-platform,edx-solutions/edx-platform,miptliot/edx-platform,Endika/edx-platform,wwj718/ANALYSE,ZLLab-Mooc/edx-platform,procangroup/edx-platform,doismellburning/edx-platform,waheedahmed/edx-platform,ovnicraft/edx-platform,andyzsf/edx,jamesblunt/edx-platform,proversity-org/edx-platform,Edraak/circleci-edx-platform,ESOedX/edx-platform,angelapper/edx-platform,proversity-org/edx-platform,antonve/s4-project-mooc,doismellburning/edx-platform,prarthitm/edxplatform,chauhanhardik/populo,ampax/edx-platform-backup,unicri/edx-platform,Unow/edx-platform,MakeHer/edx-platform,itsjeyd/edx-platform,pdehaye/theming-edx-platform,shubhdev/openedx,tiagochiavericosta/edx-platform,SravanthiSinha/edx-platform,ak2703/edx-platform,itsjeyd/edx-platform,procangroup/edx-platform,motion2015/a3,AkA84/edx-platform,eduNEXT/edx-platform,playm2mboy/edx-platform,mitocw/edx-platform,deepsrijit1105/edx-platform,edx/edx-platform,leansoft/edx-platform,AkA84/edx-platform,chauhanhardik/populo,hkawasaki/kawasaki-aio8-2,rationalAgent/edx-platform-custom,analyseuc3m/ANALYSE-v1,nagyistoce/edx-platform,PepperPD/edx-pepper-platform,chand3040/cloud_that,xuxiao19910803/edx,MakeHer/edx-platform,gsehub/edx-platform,jelugbo/tundex,Edraak/edx-platform,iivic/BoiseStateX,xingyepei/edx-platform,atsolakid/edx-platform,chauhanhardik/populo_2,antonve/s4-project-mooc,jamiefolsom/edx-platform,a-parhom/edx-platform,IONISx/edx-platform,procangroup/edx-platform,mbareta/edx-platform-ft,romain-li/edx-platform,cognitiveclass/edx-platform,mjirayu/sit_academy,jswope00/griffinx,beacloudgenius/edx-platform,DefyVentures/edx-platform,motion2015/edx-platform,knehez/edx-platform,defance/edx-platform,PepperPD/edx-pepper-platform,mitocw/edx-platform,waheedahmed/edx-platform,mbareta/edx-platform-ft,ak2703/edx-platform,LICEF/edx-platform,solashirai/edx-platform,morpheby/levelup-by,Edraak/edx-platform,polimediaupv/edx-platform,dcosentino/edx-platform,UXE/local-edx,Stanford-Online/edx-platform,playm2mboy/edx-platform,waheedahmed/edx-platform,shashank971/edx-platform,gymnasium/edx-platform,yokose-ks/edx-platform,AkA84/edx-platform,ahmadiga/min_edx,torchingloom/edx-platform,Semi-global/edx-platform,jelugbo/tundex,LICEF/edx-platform,proversity-org/edx-platform,nttks/edx-platform,olexiim/edx-platform,shabab12/edx-platform,kamalx/edx-platform,abdoosh00/edraak,10clouds/edx-platform,PepperPD/edx-pepper-platform,eduNEXT/edunext-platform,ESOedX/edx-platform,eestay/edx-platform,sudheerchintala/LearnEraPlatForm,zadgroup/edx-platform,benpatterson/edx-platform,chrisndodge/edx-platform,y12uc231/edx-platform,eduNEXT/edunext-platform,EduPepperPDTesting/pepper2013-testing,morpheby/levelup-by,cpennington/edx-platform,antonve/s4-project-mooc,bitifirefly/edx-platform,BehavioralInsightsTeam/edx-platform,TsinghuaX/edx-platform,chauhanhardik/populo_2,PepperPD/edx-pepper-platform,Unow/edx-platform,DNFcode/edx-platform,dsajkl/reqiop,mushtaqak/edx-platform,kmoocdev/edx-platform,romain-li/edx-platform,utecuy/edx-platform,Ayub-Khan/edx-platform,abdoosh00/edraak,longmen21/edx-platform,hmcmooc/muddx-platform,xuxiao19910803/edx-platform,martynovp/edx-platform,benpatterson/edx-platform,nikolas/edx-platform,rhndg/openedx,openfun/edx-platform,sameetb-cuelogic/edx-platform-test,jazkarta/edx-platform,jswope00/GAI,waheedahmed/edx-platform,leansoft/edx-platform,mushtaqak/edx-platform,ampax/edx-platform-backup,solashirai/edx-platform,rue89-tech/edx-platform,alu042/edx-platform,fly19890211/edx-platform,Lektorium-LLC/edx-platform,jamesblunt/edx-platform,jazztpt/edx-platform,cpennington/edx-platform,adoosii/edx-platform,morenopc/edx-platform,chand3040/cloud_that,caesar2164/edx-platform,halvertoluke/edx-platform,OmarIthawi/edx-platform,sameetb-cuelogic/edx-platform-test,xuxiao19910803/edx,simbs/edx-platform,mbareta/edx-platform-ft,mbareta/edx-platform-ft,mtlchun/edx,pku9104038/edx-platform,openfun/edx-platform,polimediaupv/edx-platform,Kalyzee/edx-platform,kmoocdev2/edx-platform,zofuthan/edx-platform,EduPepperPDTesting/pepper2013-testing,pomegranited/edx-platform,mtlchun/edx,ahmadio/edx-platform,rue89-tech/edx-platform,msegado/edx-platform,ampax/edx-platform,kamalx/edx-platform,etzhou/edx-platform,nagyistoce/edx-platform,kamalx/edx-platform,andyzsf/edx,jamesblunt/edx-platform,nttks/jenkins-test,vasyarv/edx-platform,adoosii/edx-platform,eemirtekin/edx-platform,EDUlib/edx-platform,jswope00/griffinx,arifsetiawan/edx-platform,halvertoluke/edx-platform,OmarIthawi/edx-platform,zadgroup/edx-platform,TeachAtTUM/edx-platform,TeachAtTUM/edx-platform,andyzsf/edx,jamiefolsom/edx-platform,zerobatu/edx-platform,appliedx/edx-platform,Kalyzee/edx-platform,jazztpt/edx-platform,Semi-global/edx-platform,Semi-global/edx-platform,pomegranited/edx-platform,eemirtekin/edx-platform,devs1991/test_edx_docmode,Softmotions/edx-platform,sudheerchintala/LearnEraPlatForm,sudheerchintala/LearnEraPlatForm,IITBinterns13/edx-platform-dev,pdehaye/theming-edx-platform,mjg2203/edx-platform-seas,mahendra-r/edx-platform,alu042/edx-platform,shurihell/testasia,xinjiguaike/edx-platform,UOMx/edx-platform,mahendra-r/edx-platform,mjg2203/edx-platform-seas,shubhdev/edxOnBaadal,dkarakats/edx-platform,longmen21/edx-platform,nttks/edx-platform,MakeHer/edx-platform,IndonesiaX/edx-platform,kmoocdev/edx-platform,mahendra-r/edx-platform,nagyistoce/edx-platform,philanthropy-u/edx-platform,mjirayu/sit_academy,appliedx/edx-platform,jonathan-beard/edx-platform,edry/edx-platform,arbrandes/edx-platform,kalebhartje/schoolboost,fintech-circle/edx-platform,JCBarahona/edX,nanolearningllc/edx-platform-cypress-2,pomegranited/edx-platform,ahmadio/edx-platform,rismalrv/edx-platform,ovnicraft/edx-platform,playm2mboy/edx-platform,DNFcode/edx-platform,dsajkl/reqiop,openfun/edx-platform,ubc/edx-platform,chrisndodge/edx-platform,cecep-edu/edx-platform,JioEducation/edx-platform,inares/edx-platform,rismalrv/edx-platform,ferabra/edx-platform,carsongee/edx-platform,doganov/edx-platform,shubhdev/edx-platform,cognitiveclass/edx-platform,antoviaque/edx-platform,romain-li/edx-platform,peterm-itr/edx-platform,philanthropy-u/edx-platform,abdoosh00/edx-rtl-final,synergeticsedx/deployment-wipro,olexiim/edx-platform,pku9104038/edx-platform,shubhdev/edx-platform,ZLLab-Mooc/edx-platform,alu042/edx-platform,JCBarahona/edX,LearnEra/LearnEraPlaftform,jazkarta/edx-platform,IndonesiaX/edx-platform,JioEducation/edx-platform,jruiperezv/ANALYSE,chrisndodge/edx-platform,xuxiao19910803/edx-platform,franosincic/edx-platform,4eek/edx-platform,doismellburning/edx-platform,Stanford-Online/edx-platform,peterm-itr/edx-platform,beni55/edx-platform,etzhou/edx-platform,Stanford-Online/edx-platform,edry/edx-platform,pku9104038/edx-platform,rue89-tech/edx-platform,ovnicraft/edx-platform,yokose-ks/edx-platform,chauhanhardik/populo,marcore/edx-platform,RPI-OPENEDX/edx-platform,alu042/edx-platform,nanolearningllc/edx-platform-cypress-2,marcore/edx-platform,MSOpenTech/edx-platform,chauhanhardik/populo_2,dcosentino/edx-platform,arifsetiawan/edx-platform,naresh21/synergetics-edx-platform,sameetb-cuelogic/edx-platform-test,zerobatu/edx-platform,pdehaye/theming-edx-platform,chand3040/cloud_that,raccoongang/edx-platform,tanmaykm/edx-platform,syjeon/new_edx,pdehaye/theming-edx-platform,beni55/edx-platform,zubair-arbi/edx-platform,motion2015/a3,cyanna/edx-platform,rationalAgent/edx-platform-custom,hamzehd/edx-platform,gsehub/edx-platform,wwj718/edx-platform,jelugbo/tundex,praveen-pal/edx-platform,mjirayu/sit_academy,inares/edx-platform,EduPepperPD/pepper2013,bdero/edx-platform,zubair-arbi/edx-platform,fintech-circle/edx-platform,ZLLab-Mooc/edx-platform,beni55/edx-platform,jbassen/edx-platform,Lektorium-LLC/edx-platform,bigdatauniversity/edx-platform,jbzdak/edx-platform,don-github/edx-platform,carsongee/edx-platform,Shrhawk/edx-platform,halvertoluke/edx-platform,jswope00/griffinx,jjmiranda/edx-platform,arbrandes/edx-platform,openfun/edx-platform,kursitet/edx-platform,don-github/edx-platform,ampax/edx-platform,playm2mboy/edx-platform,don-github/edx-platform,B-MOOC/edx-platform,AkA84/edx-platform,IndonesiaX/edx-platform,torchingloom/edx-platform,rhndg/openedx,LICEF/edx-platform,nanolearningllc/edx-platform-cypress-2,eduNEXT/edx-platform,RPI-OPENEDX/edx-platform,Unow/edx-platform,jjmiranda/edx-platform,defance/edx-platform,shurihell/testasia,doganov/edx-platform,lduarte1991/edx-platform,WatanabeYasumasa/edx-platform,ahmadiga/min_edx,LearnEra/LearnEraPlaftform,motion2015/a3,dsajkl/123,EduPepperPD/pepper2013,motion2015/a3,SivilTaram/edx-platform,pepeportela/edx-platform,vismartltd/edx-platform,jbzdak/edx-platform,shabab12/edx-platform
from __future__ import absolute_import - from importlib import import_module + from os import environ from django.conf import settings _MODULESTORES = {} FUNCTION_KEYS = ['render_template'] def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def modulestore(name='default'): global _MODULESTORES if name not in _MODULESTORES: class_ = load_function(settings.MODULESTORE[name]['ENGINE']) options = {} options.update(settings.MODULESTORE[name]['OPTIONS']) for key in FUNCTION_KEYS: if key in options: options[key] = load_function(options[key]) _MODULESTORES[name] = class_( **options ) return _MODULESTORES[name] + if 'DJANGO_SETTINGS_MODULE' in environ: - # Initialize the modulestores immediately + # Initialize the modulestores immediately - for store_name in settings.MODULESTORE: + for store_name in settings.MODULESTORE: - modulestore(store_name) + modulestore(store_name)
Put quick check so we don't load course modules on init unless we're actually running in Django
## Code Before: from __future__ import absolute_import from importlib import import_module from django.conf import settings _MODULESTORES = {} FUNCTION_KEYS = ['render_template'] def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def modulestore(name='default'): global _MODULESTORES if name not in _MODULESTORES: class_ = load_function(settings.MODULESTORE[name]['ENGINE']) options = {} options.update(settings.MODULESTORE[name]['OPTIONS']) for key in FUNCTION_KEYS: if key in options: options[key] = load_function(options[key]) _MODULESTORES[name] = class_( **options ) return _MODULESTORES[name] # Initialize the modulestores immediately for store_name in settings.MODULESTORE: modulestore(store_name) ## Instruction: Put quick check so we don't load course modules on init unless we're actually running in Django ## Code After: from __future__ import absolute_import from importlib import import_module from os import environ from django.conf import settings _MODULESTORES = {} FUNCTION_KEYS = ['render_template'] def load_function(path): """ Load a function by name. path is a string of the form "path.to.module.function" returns the imported python object `function` from `path.to.module` """ module_path, _, name = path.rpartition('.') return getattr(import_module(module_path), name) def modulestore(name='default'): global _MODULESTORES if name not in _MODULESTORES: class_ = load_function(settings.MODULESTORE[name]['ENGINE']) options = {} options.update(settings.MODULESTORE[name]['OPTIONS']) for key in FUNCTION_KEYS: if key in options: options[key] = load_function(options[key]) _MODULESTORES[name] = class_( **options ) return _MODULESTORES[name] if 'DJANGO_SETTINGS_MODULE' in environ: # Initialize the modulestores immediately for store_name in settings.MODULESTORE: modulestore(store_name)
7f317126d7d422b073cb4e4a8698757fe1e763f3
wqflask/wqflask/decorators.py
wqflask/wqflask/decorators.py
"""This module contains gn2 decorators""" from flask import g from functools import wraps def edit_access_required(f): """Use this for endpoints where admins are required""" @wraps(f) def wrap(*args, **kwargs): if g.user_session.record.get(b"user_email_address") not in [ b"labwilliams@gmail.com"]: return "You need to be admin", 401 return f(*args, **kwargs) return wrap
"""This module contains gn2 decorators""" from flask import g from typing import Dict from functools import wraps from utility.hmac import hmac_creation import json import requests def edit_access_required(f): """Use this for endpoints where admins are required""" @wraps(f) def wrap(*args, **kwargs): resource_id: str = "" if kwargs.get("inbredset_id"): # data type: dataset-publish resource_id = hmac_creation("dataset-publish:" f"{kwargs.get('inbredset_id')}:" f"{kwargs.get('name')}") if kwargs.get("dataset_name"): # data type: dataset-probe resource_id = hmac_creation("dataset-probeset:" f"{kwargs.get('dataset_name')}") response: Dict = {} try: _user_id = g.user_session.record.get(b"user_id", "").decode("utf-8") response = json.loads( requests.get("http://localhost:8080/" "available?resource=" f"{resource_id}&user={_user_id}").content) except: response = {} if "edit" not in response.get("data", []): return "You need to be admin", 401 return f(*args, **kwargs) return wrap
Replace hard-coded e-mails with gn-proxy queries
Replace hard-coded e-mails with gn-proxy queries * wqflask/wqflask/decorators.py (edit_access_required.wrap): Query the proxy to see the access rights of a given user.
Python
agpl-3.0
genenetwork/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2
"""This module contains gn2 decorators""" from flask import g + from typing import Dict from functools import wraps + from utility.hmac import hmac_creation + + import json + import requests def edit_access_required(f): """Use this for endpoints where admins are required""" @wraps(f) def wrap(*args, **kwargs): - if g.user_session.record.get(b"user_email_address") not in [ - b"labwilliams@gmail.com"]: + resource_id: str = "" + if kwargs.get("inbredset_id"): # data type: dataset-publish + resource_id = hmac_creation("dataset-publish:" + f"{kwargs.get('inbredset_id')}:" + f"{kwargs.get('name')}") + if kwargs.get("dataset_name"): # data type: dataset-probe + resource_id = hmac_creation("dataset-probeset:" + f"{kwargs.get('dataset_name')}") + response: Dict = {} + try: + _user_id = g.user_session.record.get(b"user_id", + "").decode("utf-8") + response = json.loads( + requests.get("http://localhost:8080/" + "available?resource=" + f"{resource_id}&user={_user_id}").content) + except: + response = {} + if "edit" not in response.get("data", []): return "You need to be admin", 401 return f(*args, **kwargs) return wrap
Replace hard-coded e-mails with gn-proxy queries
## Code Before: """This module contains gn2 decorators""" from flask import g from functools import wraps def edit_access_required(f): """Use this for endpoints where admins are required""" @wraps(f) def wrap(*args, **kwargs): if g.user_session.record.get(b"user_email_address") not in [ b"labwilliams@gmail.com"]: return "You need to be admin", 401 return f(*args, **kwargs) return wrap ## Instruction: Replace hard-coded e-mails with gn-proxy queries ## Code After: """This module contains gn2 decorators""" from flask import g from typing import Dict from functools import wraps from utility.hmac import hmac_creation import json import requests def edit_access_required(f): """Use this for endpoints where admins are required""" @wraps(f) def wrap(*args, **kwargs): resource_id: str = "" if kwargs.get("inbredset_id"): # data type: dataset-publish resource_id = hmac_creation("dataset-publish:" f"{kwargs.get('inbredset_id')}:" f"{kwargs.get('name')}") if kwargs.get("dataset_name"): # data type: dataset-probe resource_id = hmac_creation("dataset-probeset:" f"{kwargs.get('dataset_name')}") response: Dict = {} try: _user_id = g.user_session.record.get(b"user_id", "").decode("utf-8") response = json.loads( requests.get("http://localhost:8080/" "available?resource=" f"{resource_id}&user={_user_id}").content) except: response = {} if "edit" not in response.get("data", []): return "You need to be admin", 401 return f(*args, **kwargs) return wrap
28353efe2802059c1da8b1c81b157dc6e773032e
salt/modules/monit.py
salt/modules/monit.py
''' Salt module to manage monit ''' def version(): ''' List monit version Cli Example:: salt '*' monit.version ''' cmd = 'monit -V' res = __salt__['cmd.run'](cmd) return res.split("\n")[0] def status(): ''' Monit status CLI Example:: salt '*' monit.status ''' cmd = 'monit status' res = __salt__['cmd.run'](cmd) return res.split("\n") def start(): ''' Starts monit CLI Example:: salt '*' monit.start *Note need to add check to insure its running* `ps ax | grep monit | grep -v grep or something` ''' cmd = 'monit' res = __salt__['cmd.run'](cmd) return "Monit started" def stop(): ''' Stop monit CLI Example:: salt '*' monit.stop *Note Needs check as above* ''' def _is_bsd(): return True if __grains__['os'] == 'FreeBSD' else False if _is_bsd(): cmd = "/usr/local/etc/rc.d/monit stop" else: cmd = "/etc/init.d/monit stop" res = __salt__['cmd.run'](cmd) return "Monit Stopped" def monitor_all(): ''' Initializing all monit modules. ''' cmd = 'monit monitor all' res = __salt__['cmd.run'](cmd) if res: return "All Services initaialized" return "Issue starting monitoring on all services" def unmonitor_all(): ''' unmonitor all services. ''' cmd = 'monit unmonitor all' res = __salt__['cmd.run'](cmd) if res: return "All Services unmonitored" return "Issue unmonitoring all services"
''' Monit service module. This module will create a monit type service watcher. ''' import os def start(name): ''' CLI Example:: salt '*' monit.start <service name> ''' cmd = "monit start {0}".format(name) return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stops service via monit CLI Example:: salt '*' monit.stop <service name> ''' cmd = "monit stop {0}".format(name) return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart service via monit CLI Example:: salt '*' monit.restart <service name> ''' cmd = "monit restart {0}".format(name) return not __salt__['cmd.retcode'](cmd)
Check to see if we are going donw the right path
Check to see if we are going donw the right path
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' - Salt module to manage monit + Monit service module. This module will create a monit type + service watcher. ''' - def version(): + import os + + def start(name): ''' - List monit version + + CLI Example:: + salt '*' monit.start <service name> + ''' + cmd = "monit start {0}".format(name) - Cli Example:: - - salt '*' monit.version - ''' - - cmd = 'monit -V' - res = __salt__['cmd.run'](cmd) + return not __salt__['cmd.retcode'](cmd) - return res.split("\n")[0] - def status(): + def stop(name): ''' - Monit status + Stops service via monit CLI Example:: - salt '*' monit.status + salt '*' monit.stop <service name> ''' + cmd = "monit stop {0}".format(name) - cmd = 'monit status' - res = __salt__['cmd.run'](cmd) - return res.split("\n") + return not __salt__['cmd.retcode'](cmd) + + - def start(): + def restart(name): ''' - Starts monit + Restart service via monit CLI Example:: - salt '*' monit.start + salt '*' monit.restart <service name> - *Note need to add check to insure its running* - `ps ax | grep monit | grep -v grep or something` ''' - cmd = 'monit' + cmd = "monit restart {0}".format(name) + - res = __salt__['cmd.run'](cmd) + return not __salt__['cmd.retcode'](cmd) - return "Monit started" - def stop(): - ''' - Stop monit - - CLI Example:: - - salt '*' monit.stop - *Note Needs check as above* - ''' - def _is_bsd(): - return True if __grains__['os'] == 'FreeBSD' else False - - if _is_bsd(): - cmd = "/usr/local/etc/rc.d/monit stop" - else: - cmd = "/etc/init.d/monit stop" - res = __salt__['cmd.run'](cmd) - return "Monit Stopped" - - - def monitor_all(): - ''' - Initializing all monit modules. - ''' - cmd = 'monit monitor all' - res = __salt__['cmd.run'](cmd) - if res: - return "All Services initaialized" - return "Issue starting monitoring on all services" - - - def unmonitor_all(): - ''' - unmonitor all services. - ''' - cmd = 'monit unmonitor all' - res = __salt__['cmd.run'](cmd) - if res: - return "All Services unmonitored" - return "Issue unmonitoring all services" -
Check to see if we are going donw the right path
## Code Before: ''' Salt module to manage monit ''' def version(): ''' List monit version Cli Example:: salt '*' monit.version ''' cmd = 'monit -V' res = __salt__['cmd.run'](cmd) return res.split("\n")[0] def status(): ''' Monit status CLI Example:: salt '*' monit.status ''' cmd = 'monit status' res = __salt__['cmd.run'](cmd) return res.split("\n") def start(): ''' Starts monit CLI Example:: salt '*' monit.start *Note need to add check to insure its running* `ps ax | grep monit | grep -v grep or something` ''' cmd = 'monit' res = __salt__['cmd.run'](cmd) return "Monit started" def stop(): ''' Stop monit CLI Example:: salt '*' monit.stop *Note Needs check as above* ''' def _is_bsd(): return True if __grains__['os'] == 'FreeBSD' else False if _is_bsd(): cmd = "/usr/local/etc/rc.d/monit stop" else: cmd = "/etc/init.d/monit stop" res = __salt__['cmd.run'](cmd) return "Monit Stopped" def monitor_all(): ''' Initializing all monit modules. ''' cmd = 'monit monitor all' res = __salt__['cmd.run'](cmd) if res: return "All Services initaialized" return "Issue starting monitoring on all services" def unmonitor_all(): ''' unmonitor all services. ''' cmd = 'monit unmonitor all' res = __salt__['cmd.run'](cmd) if res: return "All Services unmonitored" return "Issue unmonitoring all services" ## Instruction: Check to see if we are going donw the right path ## Code After: ''' Monit service module. This module will create a monit type service watcher. ''' import os def start(name): ''' CLI Example:: salt '*' monit.start <service name> ''' cmd = "monit start {0}".format(name) return not __salt__['cmd.retcode'](cmd) def stop(name): ''' Stops service via monit CLI Example:: salt '*' monit.stop <service name> ''' cmd = "monit stop {0}".format(name) return not __salt__['cmd.retcode'](cmd) def restart(name): ''' Restart service via monit CLI Example:: salt '*' monit.restart <service name> ''' cmd = "monit restart {0}".format(name) return not __salt__['cmd.retcode'](cmd)
4ec2b94551858e404f0de6d8ad3827d9c6138491
slurmec2utils/sysinit.py
slurmec2utils/sysinit.py
from __future__ import absolute_import, print_function import boto.s3 from boto.s3.key import Key from .clusterconfig import ClusterConfiguration from .instanceinfo import get_instance_id def check_munge_
from __future__ import absolute_import, print_function import boto.s3 from boto.s3.key import Key from .clusterconfig import ClusterConfiguration from .instanceinfo import get_instance_id def get_munge_key(cluster_configuration=None): if cluster_configuration is None: cluster_configuration = ClusterConfiguration()
Fix syntax errors. (preventing install)
Fix syntax errors. (preventing install)
Python
apache-2.0
dacut/slurm-ec2-utils,dacut/slurm-ec2-utils
from __future__ import absolute_import, print_function import boto.s3 from boto.s3.key import Key from .clusterconfig import ClusterConfiguration from .instanceinfo import get_instance_id - def check_munge_ + def get_munge_key(cluster_configuration=None): + if cluster_configuration is None: + cluster_configuration = ClusterConfiguration()
Fix syntax errors. (preventing install)
## Code Before: from __future__ import absolute_import, print_function import boto.s3 from boto.s3.key import Key from .clusterconfig import ClusterConfiguration from .instanceinfo import get_instance_id def check_munge_ ## Instruction: Fix syntax errors. (preventing install) ## Code After: from __future__ import absolute_import, print_function import boto.s3 from boto.s3.key import Key from .clusterconfig import ClusterConfiguration from .instanceinfo import get_instance_id def get_munge_key(cluster_configuration=None): if cluster_configuration is None: cluster_configuration = ClusterConfiguration()
0464ac83d8aca12193a7629e72b880d5b8e2707a
plinth/modules/first_boot/templatetags/firstboot_extras.py
plinth/modules/first_boot/templatetags/firstboot_extras.py
from django import template from plinth import kvstore register = template.Library() @register.simple_tag def firstboot_is_finished(): state = kvstore.get_default('firstboot_state', 0) return state >= 10
from django import template from plinth import kvstore register = template.Library() @register.simple_tag def firstboot_is_finished(): """Return whether firstboot process is completed.""" state = kvstore.get_default('firstboot_state', 0) return state >= 10
Add doc strings for custom tags
firstboot: Add doc strings for custom tags
Python
agpl-3.0
vignanl/Plinth,freedomboxtwh/Plinth,harry-7/Plinth,kkampardi/Plinth,harry-7/Plinth,freedomboxtwh/Plinth,kkampardi/Plinth,freedomboxtwh/Plinth,freedomboxtwh/Plinth,harry-7/Plinth,vignanl/Plinth,kkampardi/Plinth,vignanl/Plinth,kkampardi/Plinth,vignanl/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth,freedomboxtwh/Plinth
from django import template from plinth import kvstore register = template.Library() @register.simple_tag def firstboot_is_finished(): + """Return whether firstboot process is completed.""" state = kvstore.get_default('firstboot_state', 0) return state >= 10
Add doc strings for custom tags
## Code Before: from django import template from plinth import kvstore register = template.Library() @register.simple_tag def firstboot_is_finished(): state = kvstore.get_default('firstboot_state', 0) return state >= 10 ## Instruction: Add doc strings for custom tags ## Code After: from django import template from plinth import kvstore register = template.Library() @register.simple_tag def firstboot_is_finished(): """Return whether firstboot process is completed.""" state = kvstore.get_default('firstboot_state', 0) return state >= 10
00229b2ced2f042cdcbb24bfaac4d33051930b86
source/bark/logger.py
source/bark/logger.py
import copy import bark from .log import Log class Logger(Log): '''Helper for emitting logs. A logger can be used to preset common information (such as a name) and then emit :py:class:`~bark.log.Log` records with that information already present. ''' def __init__(self, name, **kw): '''Initialise logger with identifying *name*.''' kw['name'] = name super(Logger, self).__init__(**kw) def log(self, message, **kw): '''Emit a :py:class:`~bark.log.Log` record. A copy of this logger's information is made and then merged with the passed in *kw* arguments before being emitted. ''' log = copy.deepcopy(self) log.update(**kw) log['message'] = message # Call global handle method. bark.handle(log)
import copy import bark from .log import Log class Logger(Log): '''Helper for emitting logs. A logger can be used to preset common information (such as a name) and then emit :py:class:`~bark.log.Log` records with that information already present. ''' def __init__(self, name, _handle=bark.handle, **kw): '''Initialise logger with identifying *name*. If you need to override the default handle then pass in a custom *_handle* ''' kw['name'] = name super(Logger, self).__init__(**kw) self._handle = _handle def log(self, message, **kw): '''Emit a :py:class:`~bark.log.Log` record. A copy of this logger's information is made and then merged with the passed in *kw* arguments before being emitted. ''' log = copy.deepcopy(self) log.update(**kw) log['message'] = message self._handle(log)
Allow handle to be passed in to avoid embedded global reference.
Allow handle to be passed in to avoid embedded global reference.
Python
apache-2.0
4degrees/mill,4degrees/sawmill
import copy import bark from .log import Log class Logger(Log): '''Helper for emitting logs. A logger can be used to preset common information (such as a name) and then emit :py:class:`~bark.log.Log` records with that information already present. ''' - def __init__(self, name, **kw): + def __init__(self, name, _handle=bark.handle, **kw): - '''Initialise logger with identifying *name*.''' + '''Initialise logger with identifying *name*. + + If you need to override the default handle then pass in a custom + *_handle* + + ''' kw['name'] = name super(Logger, self).__init__(**kw) + self._handle = _handle def log(self, message, **kw): '''Emit a :py:class:`~bark.log.Log` record. A copy of this logger's information is made and then merged with the passed in *kw* arguments before being emitted. ''' log = copy.deepcopy(self) log.update(**kw) log['message'] = message - # Call global handle method. - bark.handle(log) + self._handle(log)
Allow handle to be passed in to avoid embedded global reference.
## Code Before: import copy import bark from .log import Log class Logger(Log): '''Helper for emitting logs. A logger can be used to preset common information (such as a name) and then emit :py:class:`~bark.log.Log` records with that information already present. ''' def __init__(self, name, **kw): '''Initialise logger with identifying *name*.''' kw['name'] = name super(Logger, self).__init__(**kw) def log(self, message, **kw): '''Emit a :py:class:`~bark.log.Log` record. A copy of this logger's information is made and then merged with the passed in *kw* arguments before being emitted. ''' log = copy.deepcopy(self) log.update(**kw) log['message'] = message # Call global handle method. bark.handle(log) ## Instruction: Allow handle to be passed in to avoid embedded global reference. ## Code After: import copy import bark from .log import Log class Logger(Log): '''Helper for emitting logs. A logger can be used to preset common information (such as a name) and then emit :py:class:`~bark.log.Log` records with that information already present. ''' def __init__(self, name, _handle=bark.handle, **kw): '''Initialise logger with identifying *name*. If you need to override the default handle then pass in a custom *_handle* ''' kw['name'] = name super(Logger, self).__init__(**kw) self._handle = _handle def log(self, message, **kw): '''Emit a :py:class:`~bark.log.Log` record. A copy of this logger's information is made and then merged with the passed in *kw* arguments before being emitted. ''' log = copy.deepcopy(self) log.update(**kw) log['message'] = message self._handle(log)
d504abc78d94e8af90a5bf8950f3ad4e2d47e5f7
src/ansible/models.py
src/ansible/models.py
from django.db import models class Playbook(models.Model): class Meta: verbose_name_plural = "playbooks" name = models.CharField(max_length=200) path = models.CharField(max_length=200, default="~/") ansible_config = models.CharField(max_length=200, default="~/") inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") def __str__(self): return "Playbook name: %s" % self.playbook.name
from django.db import models class Playbook(models.Model): class Meta: verbose_name_plural = "playbooks" name = models.CharField(max_length=200) path = models.CharField(max_length=200, default="~/") ansible_config = models.CharField(max_length=200, default="~/") inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") def __str__(self): return "%s" % self.name
Fix string output of Playbook
Fix string output of Playbook
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
from django.db import models class Playbook(models.Model): class Meta: verbose_name_plural = "playbooks" name = models.CharField(max_length=200) path = models.CharField(max_length=200, default="~/") ansible_config = models.CharField(max_length=200, default="~/") inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") def __str__(self): - return "Playbook name: %s" % self.playbook.name + return "%s" % self.name
Fix string output of Playbook
## Code Before: from django.db import models class Playbook(models.Model): class Meta: verbose_name_plural = "playbooks" name = models.CharField(max_length=200) path = models.CharField(max_length=200, default="~/") ansible_config = models.CharField(max_length=200, default="~/") inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") def __str__(self): return "Playbook name: %s" % self.playbook.name ## Instruction: Fix string output of Playbook ## Code After: from django.db import models class Playbook(models.Model): class Meta: verbose_name_plural = "playbooks" name = models.CharField(max_length=200) path = models.CharField(max_length=200, default="~/") ansible_config = models.CharField(max_length=200, default="~/") inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") def __str__(self): return "%s" % self.name
0d1aa7e08ef2572d2e13218d7d8942d8d2a7550e
app/logic/latexprinter.py
app/logic/latexprinter.py
import sympy from sympy.printing.latex import LatexPrinter class GammaLatexPrinter(LatexPrinter): def _needs_function_brackets(self, expr): if expr.func == sympy.Abs: return False return super(GammaLatexPrinter, self)._needs_function_brackets(expr) def latex(expr, **settings): settings['fold_func_brackets'] = True return GammaLatexPrinter(settings).doprint(expr)
import sympy from sympy.printing.latex import LatexPrinter class GammaLatexPrinter(LatexPrinter): def _needs_function_brackets(self, expr): if expr.func == sympy.Abs: return False return super(GammaLatexPrinter, self)._needs_function_brackets(expr) def latex(expr, **settings): settings['fold_func_brackets'] = True settings['inv_trig_style'] = 'power' return GammaLatexPrinter(settings).doprint(expr)
Print inverse trig functions using powers
Print inverse trig functions using powers
Python
bsd-3-clause
bolshoibooze/sympy_gamma,iScienceLuvr/sympy_gamma,debugger22/sympy_gamma,debugger22/sympy_gamma,iScienceLuvr/sympy_gamma,kaichogami/sympy_gamma,bolshoibooze/sympy_gamma,iScienceLuvr/sympy_gamma,kaichogami/sympy_gamma,bolshoibooze/sympy_gamma,github4ry/sympy_gamma,github4ry/sympy_gamma,github4ry/sympy_gamma,kaichogami/sympy_gamma
import sympy from sympy.printing.latex import LatexPrinter class GammaLatexPrinter(LatexPrinter): def _needs_function_brackets(self, expr): if expr.func == sympy.Abs: return False return super(GammaLatexPrinter, self)._needs_function_brackets(expr) def latex(expr, **settings): settings['fold_func_brackets'] = True + settings['inv_trig_style'] = 'power' return GammaLatexPrinter(settings).doprint(expr)
Print inverse trig functions using powers
## Code Before: import sympy from sympy.printing.latex import LatexPrinter class GammaLatexPrinter(LatexPrinter): def _needs_function_brackets(self, expr): if expr.func == sympy.Abs: return False return super(GammaLatexPrinter, self)._needs_function_brackets(expr) def latex(expr, **settings): settings['fold_func_brackets'] = True return GammaLatexPrinter(settings).doprint(expr) ## Instruction: Print inverse trig functions using powers ## Code After: import sympy from sympy.printing.latex import LatexPrinter class GammaLatexPrinter(LatexPrinter): def _needs_function_brackets(self, expr): if expr.func == sympy.Abs: return False return super(GammaLatexPrinter, self)._needs_function_brackets(expr) def latex(expr, **settings): settings['fold_func_brackets'] = True settings['inv_trig_style'] = 'power' return GammaLatexPrinter(settings).doprint(expr)
311b0d5a0baabbb9c1476a156dbae1b919478704
src/upgradegit/cli.py
src/upgradegit/cli.py
import click import requirements import os import re @click.command() @click.option('--file', default='requirements.txt', help='File to upgrade') @click.option('--branch', default='master', help='Branch to upgrade from') def upgrade(file, branch): lines = [] with open(file, 'r') as f: for req in requirements.parse(f): line = '' if (req.uri): reg = r'([0-9a-z]*)(?=(\s+refs\/heads\/'+branch+'))' uri = req.uri.replace('git+ssh://', 'ssh://git@') cmd = 'git ls-remote {} {} HEAD'.format(uri, branch) result = os.popen(cmd).read() result = result.strip() results = re.findall(reg, result) result = results[0][0] line = re.sub(r'\@([0-9a-f]*)(?=(#|$))', '@'+result, req.line) else: name = req.name spec_op = req.specs[0][0] spec_ver = req.specs[0][1] line = '{name}{spec_op}{spec_ver}'.format( name=name, spec_op=spec_op, spec_ver=spec_ver) lines.append(line) with open(file, 'w') as f: for line in lines: f.write(line+'\n') if __name__ == '__main__': upgrade()
import click import requirements import os import re @click.command() @click.option('--file', default='requirements.txt', help='File to upgrade') @click.option('--branch', default='master', help='Branch to upgrade from') def upgrade(file, branch): lines = [] with open(file, 'r') as f: for req in requirements.parse(f): line = '' if (req.uri): reg = r'([0-9a-z]*)(?=(\s+refs\/heads\/'+branch+'))' uri = req.uri.replace('git+ssh://', 'ssh://git@') cmd = 'git ls-remote {} {} HEAD'.format(uri, branch) result = os.popen(cmd).read() result = result.strip() results = re.findall(reg, result) result = results[0][0] line = re.sub(r'.git(?=(#|$))', '.git@'+result, req.line) else: name = req.name spec_op = req.specs[0][0] spec_ver = req.specs[0][1] line = '{name}{spec_op}{spec_ver}'.format( name=name, spec_op=spec_op, spec_ver=spec_ver) lines.append(line) with open(file, 'w') as f: for line in lines: f.write(line+'\n') if __name__ == '__main__': upgrade()
Allow for requirements without a hash
Allow for requirements without a hash
Python
mit
bevanmw/gitupgrade
import click import requirements import os import re @click.command() @click.option('--file', default='requirements.txt', help='File to upgrade') @click.option('--branch', default='master', help='Branch to upgrade from') def upgrade(file, branch): lines = [] with open(file, 'r') as f: for req in requirements.parse(f): line = '' if (req.uri): reg = r'([0-9a-z]*)(?=(\s+refs\/heads\/'+branch+'))' uri = req.uri.replace('git+ssh://', 'ssh://git@') cmd = 'git ls-remote {} {} HEAD'.format(uri, branch) result = os.popen(cmd).read() result = result.strip() results = re.findall(reg, result) result = results[0][0] - line = re.sub(r'\@([0-9a-f]*)(?=(#|$))', '@'+result, req.line) + line = re.sub(r'.git(?=(#|$))', '.git@'+result, req.line) else: name = req.name spec_op = req.specs[0][0] spec_ver = req.specs[0][1] line = '{name}{spec_op}{spec_ver}'.format( name=name, spec_op=spec_op, spec_ver=spec_ver) lines.append(line) with open(file, 'w') as f: for line in lines: f.write(line+'\n') if __name__ == '__main__': upgrade()
Allow for requirements without a hash
## Code Before: import click import requirements import os import re @click.command() @click.option('--file', default='requirements.txt', help='File to upgrade') @click.option('--branch', default='master', help='Branch to upgrade from') def upgrade(file, branch): lines = [] with open(file, 'r') as f: for req in requirements.parse(f): line = '' if (req.uri): reg = r'([0-9a-z]*)(?=(\s+refs\/heads\/'+branch+'))' uri = req.uri.replace('git+ssh://', 'ssh://git@') cmd = 'git ls-remote {} {} HEAD'.format(uri, branch) result = os.popen(cmd).read() result = result.strip() results = re.findall(reg, result) result = results[0][0] line = re.sub(r'\@([0-9a-f]*)(?=(#|$))', '@'+result, req.line) else: name = req.name spec_op = req.specs[0][0] spec_ver = req.specs[0][1] line = '{name}{spec_op}{spec_ver}'.format( name=name, spec_op=spec_op, spec_ver=spec_ver) lines.append(line) with open(file, 'w') as f: for line in lines: f.write(line+'\n') if __name__ == '__main__': upgrade() ## Instruction: Allow for requirements without a hash ## Code After: import click import requirements import os import re @click.command() @click.option('--file', default='requirements.txt', help='File to upgrade') @click.option('--branch', default='master', help='Branch to upgrade from') def upgrade(file, branch): lines = [] with open(file, 'r') as f: for req in requirements.parse(f): line = '' if (req.uri): reg = r'([0-9a-z]*)(?=(\s+refs\/heads\/'+branch+'))' uri = req.uri.replace('git+ssh://', 'ssh://git@') cmd = 'git ls-remote {} {} HEAD'.format(uri, branch) result = os.popen(cmd).read() result = result.strip() results = re.findall(reg, result) result = results[0][0] line = re.sub(r'.git(?=(#|$))', '.git@'+result, req.line) else: name = req.name spec_op = req.specs[0][0] spec_ver = req.specs[0][1] line = '{name}{spec_op}{spec_ver}'.format( name=name, spec_op=spec_op, spec_ver=spec_ver) lines.append(line) with open(file, 'w') as f: for line in lines: f.write(line+'\n') if __name__ == '__main__': upgrade()
2ba5f562edb568653574d329a9f1ffbe8b15e7c5
tests/test_caching.py
tests/test_caching.py
import os import tempfile from . import RTRSSTestCase from rtrss import caching, config class CachingTestCase(RTRSSTestCase): def setUp(self): fh, self.filename = tempfile.mkstemp(dir=config.DATA_DIR) os.close(fh) def tearDown(self): os.remove(self.filename) def test_open_for_atomic_write_writes(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data) def test_atomic_write_really_atomic(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename, 'w') as f1: f1.write('this will be overwritten') with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data)
import os import tempfile from . import TempDirTestCase from rtrss import caching class CachingTestCase(TempDirTestCase): def setUp(self): super(CachingTestCase, self).setUp() fh, self.filename = tempfile.mkstemp(dir=self.dir.path) os.close(fh) def tearDown(self): os.remove(self.filename) super(CachingTestCase, self).tearDown() def test_open_for_atomic_write_writes(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data) def test_atomic_write_really_atomic(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename, 'w') as f1: f1.write('this will be overwritten') with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data)
Update test case to use new base class
Update test case to use new base class
Python
apache-2.0
notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss
import os import tempfile - from . import RTRSSTestCase + from . import TempDirTestCase - from rtrss import caching, config + from rtrss import caching - class CachingTestCase(RTRSSTestCase): + class CachingTestCase(TempDirTestCase): def setUp(self): + super(CachingTestCase, self).setUp() - fh, self.filename = tempfile.mkstemp(dir=config.DATA_DIR) + fh, self.filename = tempfile.mkstemp(dir=self.dir.path) os.close(fh) def tearDown(self): os.remove(self.filename) + super(CachingTestCase, self).tearDown() def test_open_for_atomic_write_writes(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data) def test_atomic_write_really_atomic(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename, 'w') as f1: f1.write('this will be overwritten') with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data)
Update test case to use new base class
## Code Before: import os import tempfile from . import RTRSSTestCase from rtrss import caching, config class CachingTestCase(RTRSSTestCase): def setUp(self): fh, self.filename = tempfile.mkstemp(dir=config.DATA_DIR) os.close(fh) def tearDown(self): os.remove(self.filename) def test_open_for_atomic_write_writes(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data) def test_atomic_write_really_atomic(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename, 'w') as f1: f1.write('this will be overwritten') with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data) ## Instruction: Update test case to use new base class ## Code After: import os import tempfile from . import TempDirTestCase from rtrss import caching class CachingTestCase(TempDirTestCase): def setUp(self): super(CachingTestCase, self).setUp() fh, self.filename = tempfile.mkstemp(dir=self.dir.path) os.close(fh) def tearDown(self): os.remove(self.filename) super(CachingTestCase, self).tearDown() def test_open_for_atomic_write_writes(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data) def test_atomic_write_really_atomic(self): test_data = 'test' with caching.open_for_atomic_write(self.filename) as f: f.write(test_data) with open(self.filename, 'w') as f1: f1.write('this will be overwritten') with open(self.filename) as f: data = f.read() self.assertEqual(test_data, data)
39d45a64221b8146ac318cfeb833f977ad32fe48
app.py
app.py
import eventlet eventlet.monkey_patch() # NOLINT import importlib import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() token = sys.stdin.readline().strip() name = sys.argv[1] module = importlib.import_module(name) meta = module.__meta__ config = get_config(meta.get("config")) app = meta["class"](token, config) signal.signal(signal.SIGTERM, lambda x, y: app.on_service_stop()) signal.signal(signal.SIGINT, lambda x, y: app.on_service_stop()) app.before_service_start() app.on_service_start() def handle_main(): configure_logging() main_app = create_app() main_app.start()
import eventlet eventlet.monkey_patch() # NOLINT import importlib import os import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() token = sys.stdin.readline().strip() name = sys.argv[1] if len(sys.argv) > 2: # This is mostly for plugins. Need to change dir so imports can succeed. os.chdir(sys.argv[2]) sys.path.append(sys.argv[2]) module = importlib.import_module(name) meta = module.__meta__ config = get_config(meta.get("config")) app = meta["class"](token, config) signal.signal(signal.SIGTERM, lambda x, y: app.on_service_stop()) signal.signal(signal.SIGINT, lambda x, y: app.on_service_stop()) app.before_service_start() app.on_service_start() def handle_main(): configure_logging() main_app = create_app() main_app.start()
Support 2nd parameter for weave-launch so that a plugin from any directory can be loaded.
Support 2nd parameter for weave-launch so that a plugin from any directory can be loaded.
Python
mit
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
import eventlet eventlet.monkey_patch() # NOLINT import importlib + import os import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() token = sys.stdin.readline().strip() name = sys.argv[1] + if len(sys.argv) > 2: + # This is mostly for plugins. Need to change dir so imports can succeed. + os.chdir(sys.argv[2]) + sys.path.append(sys.argv[2]) + module = importlib.import_module(name) meta = module.__meta__ config = get_config(meta.get("config")) app = meta["class"](token, config) signal.signal(signal.SIGTERM, lambda x, y: app.on_service_stop()) signal.signal(signal.SIGINT, lambda x, y: app.on_service_stop()) app.before_service_start() app.on_service_start() def handle_main(): configure_logging() main_app = create_app() main_app.start()
Support 2nd parameter for weave-launch so that a plugin from any directory can be loaded.
## Code Before: import eventlet eventlet.monkey_patch() # NOLINT import importlib import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() token = sys.stdin.readline().strip() name = sys.argv[1] module = importlib.import_module(name) meta = module.__meta__ config = get_config(meta.get("config")) app = meta["class"](token, config) signal.signal(signal.SIGTERM, lambda x, y: app.on_service_stop()) signal.signal(signal.SIGINT, lambda x, y: app.on_service_stop()) app.before_service_start() app.on_service_start() def handle_main(): configure_logging() main_app = create_app() main_app.start() ## Instruction: Support 2nd parameter for weave-launch so that a plugin from any directory can be loaded. ## Code After: import eventlet eventlet.monkey_patch() # NOLINT import importlib import os import sys from weaveserver.main import create_app from weaveserver.core.logger import configure_logging def handle_launch(): import signal from weaveserver.core.config_loader import get_config configure_logging() token = sys.stdin.readline().strip() name = sys.argv[1] if len(sys.argv) > 2: # This is mostly for plugins. Need to change dir so imports can succeed. os.chdir(sys.argv[2]) sys.path.append(sys.argv[2]) module = importlib.import_module(name) meta = module.__meta__ config = get_config(meta.get("config")) app = meta["class"](token, config) signal.signal(signal.SIGTERM, lambda x, y: app.on_service_stop()) signal.signal(signal.SIGINT, lambda x, y: app.on_service_stop()) app.before_service_start() app.on_service_start() def handle_main(): configure_logging() main_app = create_app() main_app.start()
435e27f3104cfe6e4f6577c2a5121ae2a6347eb1
tornado_aws/exceptions.py
tornado_aws/exceptions.py
class AWSClientException(Exception): """Base exception class for AWSClient :ivar msg: The error message """ fmt = 'An error occurred' def __init__(self, **kwargs): super(AWSClientException, self).__init__(self.fmt.format(**kwargs)) class ConfigNotFound(AWSClientException): """The configuration file could not be parsed. :ivar path: The path to the config file """ fmt = 'The config file could not be found ({path})' class ConfigParserError(AWSClientException): """Error raised when parsing a configuration file with :py:class`configparser.RawConfigParser` :ivar path: The path to the config file """ fmt = 'Unable to parse config file ({path})' class NoCredentialsError(AWSClientException): """Raised when the credentials could not be located.""" fmt = 'Credentials not found' class NoProfileError(AWSClientException): """Raised when the specified profile could not be located. :ivar path: The path to the config file :ivar profile: The profile that was specified """ fmt = 'Profile ({profile}) not found ({path})'
class AWSClientException(Exception): """Base exception class for AWSClient :ivar msg: The error message """ fmt = 'An error occurred' def __init__(self, **kwargs): super(AWSClientException, self).__init__(self.fmt.format(**kwargs)) class AWSError(AWSClientException): """Raised when the credentials could not be located.""" fmt = '{message}' class ConfigNotFound(AWSClientException): """The configuration file could not be parsed. :ivar path: The path to the config file """ fmt = 'The config file could not be found ({path})' class ConfigParserError(AWSClientException): """Error raised when parsing a configuration file with :py:class`configparser.RawConfigParser` :ivar path: The path to the config file """ fmt = 'Unable to parse config file ({path})' class NoCredentialsError(AWSClientException): """Raised when the credentials could not be located.""" fmt = 'Credentials not found' class NoProfileError(AWSClientException): """Raised when the specified profile could not be located. :ivar path: The path to the config file :ivar profile: The profile that was specified """ fmt = 'Profile ({profile}) not found ({path})'
Add a new generic AWS Error exception
Add a new generic AWS Error exception
Python
bsd-3-clause
gmr/tornado-aws,gmr/tornado-aws
class AWSClientException(Exception): """Base exception class for AWSClient :ivar msg: The error message """ fmt = 'An error occurred' def __init__(self, **kwargs): super(AWSClientException, self).__init__(self.fmt.format(**kwargs)) + + + class AWSError(AWSClientException): + """Raised when the credentials could not be located.""" + fmt = '{message}' class ConfigNotFound(AWSClientException): """The configuration file could not be parsed. :ivar path: The path to the config file """ fmt = 'The config file could not be found ({path})' class ConfigParserError(AWSClientException): """Error raised when parsing a configuration file with :py:class`configparser.RawConfigParser` :ivar path: The path to the config file """ fmt = 'Unable to parse config file ({path})' class NoCredentialsError(AWSClientException): """Raised when the credentials could not be located.""" fmt = 'Credentials not found' class NoProfileError(AWSClientException): """Raised when the specified profile could not be located. :ivar path: The path to the config file :ivar profile: The profile that was specified """ fmt = 'Profile ({profile}) not found ({path})'
Add a new generic AWS Error exception
## Code Before: class AWSClientException(Exception): """Base exception class for AWSClient :ivar msg: The error message """ fmt = 'An error occurred' def __init__(self, **kwargs): super(AWSClientException, self).__init__(self.fmt.format(**kwargs)) class ConfigNotFound(AWSClientException): """The configuration file could not be parsed. :ivar path: The path to the config file """ fmt = 'The config file could not be found ({path})' class ConfigParserError(AWSClientException): """Error raised when parsing a configuration file with :py:class`configparser.RawConfigParser` :ivar path: The path to the config file """ fmt = 'Unable to parse config file ({path})' class NoCredentialsError(AWSClientException): """Raised when the credentials could not be located.""" fmt = 'Credentials not found' class NoProfileError(AWSClientException): """Raised when the specified profile could not be located. :ivar path: The path to the config file :ivar profile: The profile that was specified """ fmt = 'Profile ({profile}) not found ({path})' ## Instruction: Add a new generic AWS Error exception ## Code After: class AWSClientException(Exception): """Base exception class for AWSClient :ivar msg: The error message """ fmt = 'An error occurred' def __init__(self, **kwargs): super(AWSClientException, self).__init__(self.fmt.format(**kwargs)) class AWSError(AWSClientException): """Raised when the credentials could not be located.""" fmt = '{message}' class ConfigNotFound(AWSClientException): """The configuration file could not be parsed. :ivar path: The path to the config file """ fmt = 'The config file could not be found ({path})' class ConfigParserError(AWSClientException): """Error raised when parsing a configuration file with :py:class`configparser.RawConfigParser` :ivar path: The path to the config file """ fmt = 'Unable to parse config file ({path})' class NoCredentialsError(AWSClientException): """Raised when the credentials could not be located.""" fmt = 'Credentials not found' class NoProfileError(AWSClientException): """Raised when the specified profile could not be located. :ivar path: The path to the config file :ivar profile: The profile that was specified """ fmt = 'Profile ({profile}) not found ({path})'
35529cfd3f93723e8d60b43f58419385137b9a01
saltapi/cli.py
saltapi/cli.py
''' CLI entry-point for salt-api ''' # Import salt libs from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api libs import saltapi.client import saltapi.config import saltapi.version class SaltAPI(OptionParser, ConfigDirMixIn, LogLevelMixIn, PidfileMixin, DaemonMixIn, MergeConfigMixIn): ''' The cli parser object used to fire up the salt api system. ''' __metaclass__ = OptionParserMeta VERSION = saltapi.version.__version__ def setup_config(self): return saltapi.config.api_config(self.get_config_file_path('master')) def run(self): ''' Run the api ''' self.parse_args() self.process_config_dir() self.daemonize_if_required() self.set_pidfile() client = saltapi.client.SaltAPIClient(self.config) client.run()
''' CLI entry-point for salt-api ''' # Import salt libs from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api libs import saltapi.client import saltapi.config import saltapi.version class SaltAPI(OptionParser, ConfigDirMixIn, LogLevelMixIn, PidfileMixin, DaemonMixIn, MergeConfigMixIn): ''' The cli parser object used to fire up the salt api system. ''' __metaclass__ = OptionParserMeta VERSION = saltapi.version.__version__ def setup_config(self): return saltapi.config.api_config(self.get_config_file_path('master')) def run(self): ''' Run the api ''' self.parse_args() self.daemonize_if_required() self.set_pidfile() client = saltapi.client.SaltAPIClient(self.config) client.run()
Remove unnecessary call to `process_config_dir()`.
Remove unnecessary call to `process_config_dir()`.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
''' CLI entry-point for salt-api ''' # Import salt libs from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api libs import saltapi.client import saltapi.config import saltapi.version class SaltAPI(OptionParser, ConfigDirMixIn, LogLevelMixIn, PidfileMixin, DaemonMixIn, MergeConfigMixIn): ''' The cli parser object used to fire up the salt api system. ''' __metaclass__ = OptionParserMeta VERSION = saltapi.version.__version__ def setup_config(self): return saltapi.config.api_config(self.get_config_file_path('master')) def run(self): ''' Run the api ''' self.parse_args() - self.process_config_dir() self.daemonize_if_required() self.set_pidfile() client = saltapi.client.SaltAPIClient(self.config) client.run()
Remove unnecessary call to `process_config_dir()`.
## Code Before: ''' CLI entry-point for salt-api ''' # Import salt libs from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api libs import saltapi.client import saltapi.config import saltapi.version class SaltAPI(OptionParser, ConfigDirMixIn, LogLevelMixIn, PidfileMixin, DaemonMixIn, MergeConfigMixIn): ''' The cli parser object used to fire up the salt api system. ''' __metaclass__ = OptionParserMeta VERSION = saltapi.version.__version__ def setup_config(self): return saltapi.config.api_config(self.get_config_file_path('master')) def run(self): ''' Run the api ''' self.parse_args() self.process_config_dir() self.daemonize_if_required() self.set_pidfile() client = saltapi.client.SaltAPIClient(self.config) client.run() ## Instruction: Remove unnecessary call to `process_config_dir()`. ## Code After: ''' CLI entry-point for salt-api ''' # Import salt libs from salt.utils.parsers import ( ConfigDirMixIn, DaemonMixIn, LogLevelMixIn, MergeConfigMixIn, OptionParser, OptionParserMeta, PidfileMixin) # Import salt-api libs import saltapi.client import saltapi.config import saltapi.version class SaltAPI(OptionParser, ConfigDirMixIn, LogLevelMixIn, PidfileMixin, DaemonMixIn, MergeConfigMixIn): ''' The cli parser object used to fire up the salt api system. ''' __metaclass__ = OptionParserMeta VERSION = saltapi.version.__version__ def setup_config(self): return saltapi.config.api_config(self.get_config_file_path('master')) def run(self): ''' Run the api ''' self.parse_args() self.daemonize_if_required() self.set_pidfile() client = saltapi.client.SaltAPIClient(self.config) client.run()
c02b2711f1b18bba85155f8bf402b5b9824b6502
test/test_producer.py
test/test_producer.py
import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") def test_end_to_end(kafka_broker): connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") def test_end_to_end(kafka_broker): connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, group_id=None, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
Disable auto-commit / group assignment in producer test
Disable auto-commit / group assignment in producer test
Python
apache-2.0
Aloomaio/kafka-python,zackdever/kafka-python,wikimedia/operations-debs-python-kafka,ohmu/kafka-python,ohmu/kafka-python,mumrah/kafka-python,Yelp/kafka-python,Yelp/kafka-python,dpkp/kafka-python,wikimedia/operations-debs-python-kafka,dpkp/kafka-python,scrapinghub/kafka-python,mumrah/kafka-python,zackdever/kafka-python,Aloomaio/kafka-python,scrapinghub/kafka-python,DataDog/kafka-python
import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") def test_end_to_end(kafka_broker): connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, + group_id=None, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
Disable auto-commit / group assignment in producer test
## Code Before: import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") def test_end_to_end(kafka_broker): connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)]) ## Instruction: Disable auto-commit / group assignment in producer test ## Code After: import pytest from kafka import KafkaConsumer, KafkaProducer from test.conftest import version from test.testutil import random_string @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set") def test_end_to_end(kafka_broker): connect_str = 'localhost:' + str(kafka_broker.port) producer = KafkaProducer(bootstrap_servers=connect_str, max_block_ms=10000, value_serializer=str.encode) consumer = KafkaConsumer(bootstrap_servers=connect_str, group_id=None, consumer_timeout_ms=10000, auto_offset_reset='earliest', value_deserializer=bytes.decode) topic = random_string(5) for i in range(1000): producer.send(topic, 'msg %d' % i) producer.flush() producer.close() consumer.subscribe([topic]) msgs = set() for i in range(1000): try: msgs.add(next(consumer).value) except StopIteration: break assert msgs == set(['msg %d' % i for i in range(1000)])
84ad348562e64084894e7c033de870a016390134
server/auth/auth.py
server/auth/auth.py
import json from flask import Blueprint, request from flask.ext.login import current_user, logout_user, login_user from flask.ext.restful import Api, Resource, abort from server.models import Lecturer, db auth = Blueprint('auth', __name__) api = Api(auth) class LoginResource(Resource): def get(self): if current_user.is_active: return {'username': current_user.full_name} else: abort(403, message="The user is not logged in") def post(self): email = request.form['email'] password = request.form['password'] user = ( db.session.query(Lecturer) .filter(Lecturer.email == email) .filter(Lecturer.password == password) .first() ) if not user: abort(403, message="Invalid credentials") login_user(user) return {'username': current_user.full_name} class LogoutResource(Resource): def post(self): logout_user() return '', 204 api.add_resource(LoginResource, '/login') api.add_resource(LogoutResource, '/logout')
import json from flask import Blueprint, request from flask.ext.login import current_user, logout_user, login_user from flask.ext.restful import Api, Resource, abort, reqparse from server.models import Lecturer, db auth = Blueprint('auth', __name__) api = Api(auth) class LoginResource(Resource): def get(self): if current_user.is_active: return {'username': current_user.full_name} else: abort(403, message="The user is not logged in") def post(self): argparser = reqparse.RequestParser() argparser.add_argument('email', required=True) argparser.add_argument('password', required=True) args = argparser.parse_args() email = args.email password = args.password user = ( db.session.query(Lecturer) .filter(Lecturer.email == email) .filter(Lecturer.password == password) .first() ) if not user: abort(403, message="Invalid credentials") login_user(user) return {'username': current_user.full_name} class LogoutResource(Resource): def post(self): logout_user() return '', 204 api.add_resource(LoginResource, '/login') api.add_resource(LogoutResource, '/logout')
Fix Login API implementation not parsing JSON POST data
Fix Login API implementation not parsing JSON POST data
Python
mit
MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS,MACSIFS/IFS
import json from flask import Blueprint, request from flask.ext.login import current_user, logout_user, login_user - from flask.ext.restful import Api, Resource, abort + from flask.ext.restful import Api, Resource, abort, reqparse from server.models import Lecturer, db auth = Blueprint('auth', __name__) api = Api(auth) class LoginResource(Resource): def get(self): if current_user.is_active: return {'username': current_user.full_name} else: abort(403, message="The user is not logged in") def post(self): + argparser = reqparse.RequestParser() + argparser.add_argument('email', required=True) + argparser.add_argument('password', required=True) + args = argparser.parse_args() + - email = request.form['email'] + email = args.email - password = request.form['password'] + password = args.password user = ( db.session.query(Lecturer) .filter(Lecturer.email == email) .filter(Lecturer.password == password) .first() ) if not user: abort(403, message="Invalid credentials") login_user(user) return {'username': current_user.full_name} class LogoutResource(Resource): def post(self): logout_user() return '', 204 api.add_resource(LoginResource, '/login') api.add_resource(LogoutResource, '/logout')
Fix Login API implementation not parsing JSON POST data
## Code Before: import json from flask import Blueprint, request from flask.ext.login import current_user, logout_user, login_user from flask.ext.restful import Api, Resource, abort from server.models import Lecturer, db auth = Blueprint('auth', __name__) api = Api(auth) class LoginResource(Resource): def get(self): if current_user.is_active: return {'username': current_user.full_name} else: abort(403, message="The user is not logged in") def post(self): email = request.form['email'] password = request.form['password'] user = ( db.session.query(Lecturer) .filter(Lecturer.email == email) .filter(Lecturer.password == password) .first() ) if not user: abort(403, message="Invalid credentials") login_user(user) return {'username': current_user.full_name} class LogoutResource(Resource): def post(self): logout_user() return '', 204 api.add_resource(LoginResource, '/login') api.add_resource(LogoutResource, '/logout') ## Instruction: Fix Login API implementation not parsing JSON POST data ## Code After: import json from flask import Blueprint, request from flask.ext.login import current_user, logout_user, login_user from flask.ext.restful import Api, Resource, abort, reqparse from server.models import Lecturer, db auth = Blueprint('auth', __name__) api = Api(auth) class LoginResource(Resource): def get(self): if current_user.is_active: return {'username': current_user.full_name} else: abort(403, message="The user is not logged in") def post(self): argparser = reqparse.RequestParser() argparser.add_argument('email', required=True) argparser.add_argument('password', required=True) args = argparser.parse_args() email = args.email password = args.password user = ( db.session.query(Lecturer) .filter(Lecturer.email == email) .filter(Lecturer.password == password) .first() ) if not user: abort(403, message="Invalid credentials") login_user(user) return {'username': current_user.full_name} class LogoutResource(Resource): def post(self): logout_user() return '', 204 api.add_resource(LoginResource, '/login') api.add_resource(LogoutResource, '/logout')
645265be1097f463e9d12f2be1a3a4de2b136f0c
tests/test_pooling.py
tests/test_pooling.py
try: import queue except ImportError: import Queue as queue import pylibmc from nose.tools import eq_, ok_ from tests import PylibmcTestCase class PoolTestCase(PylibmcTestCase): pass class ClientPoolTests(PoolTestCase): def test_simple(self): a_str = "a" p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc: ok_(smc) ok_(smc.set(a_str, 1)) eq_(smc[a_str], 1) def test_exhaust(self): p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc1: with p.reserve() as smc2: self.assertRaises(queue.Empty, p.reserve().__enter__) # TODO Thread-mapped pool tests
try: import queue except ImportError: import Queue as queue import pylibmc from nose.tools import eq_, ok_ from tests import PylibmcTestCase class PoolTestCase(PylibmcTestCase): pass class ClientPoolTests(PoolTestCase): def test_simple(self): a_str = "a" p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc: ok_(smc) ok_(smc.set(a_str, 1)) eq_(smc[a_str], 1) def test_exhaust(self): p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc1: with p.reserve() as smc2: self.assertRaises(queue.Empty, p.reserve().__enter__) class ThreadMappedPoolTests(PoolTestCase): def test_simple(self): a_str = "a" p = pylibmc.ThreadMappedPool(self.mc) with p.reserve() as smc: ok_(smc) ok_(smc.set(a_str, 1)) eq_(smc[a_str], 1)
Add rudimentary testing for thread-mapped pools
Add rudimentary testing for thread-mapped pools Refs #174
Python
bsd-3-clause
lericson/pylibmc,lericson/pylibmc,lericson/pylibmc
try: import queue except ImportError: import Queue as queue import pylibmc from nose.tools import eq_, ok_ from tests import PylibmcTestCase class PoolTestCase(PylibmcTestCase): pass class ClientPoolTests(PoolTestCase): def test_simple(self): a_str = "a" p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc: ok_(smc) ok_(smc.set(a_str, 1)) eq_(smc[a_str], 1) def test_exhaust(self): p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc1: with p.reserve() as smc2: self.assertRaises(queue.Empty, p.reserve().__enter__) - # TODO Thread-mapped pool tests + class ThreadMappedPoolTests(PoolTestCase): + def test_simple(self): + a_str = "a" + p = pylibmc.ThreadMappedPool(self.mc) + with p.reserve() as smc: + ok_(smc) + ok_(smc.set(a_str, 1)) + eq_(smc[a_str], 1)
Add rudimentary testing for thread-mapped pools
## Code Before: try: import queue except ImportError: import Queue as queue import pylibmc from nose.tools import eq_, ok_ from tests import PylibmcTestCase class PoolTestCase(PylibmcTestCase): pass class ClientPoolTests(PoolTestCase): def test_simple(self): a_str = "a" p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc: ok_(smc) ok_(smc.set(a_str, 1)) eq_(smc[a_str], 1) def test_exhaust(self): p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc1: with p.reserve() as smc2: self.assertRaises(queue.Empty, p.reserve().__enter__) # TODO Thread-mapped pool tests ## Instruction: Add rudimentary testing for thread-mapped pools ## Code After: try: import queue except ImportError: import Queue as queue import pylibmc from nose.tools import eq_, ok_ from tests import PylibmcTestCase class PoolTestCase(PylibmcTestCase): pass class ClientPoolTests(PoolTestCase): def test_simple(self): a_str = "a" p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc: ok_(smc) ok_(smc.set(a_str, 1)) eq_(smc[a_str], 1) def test_exhaust(self): p = pylibmc.ClientPool(self.mc, 2) with p.reserve() as smc1: with p.reserve() as smc2: self.assertRaises(queue.Empty, p.reserve().__enter__) class ThreadMappedPoolTests(PoolTestCase): def test_simple(self): a_str = "a" p = pylibmc.ThreadMappedPool(self.mc) with p.reserve() as smc: ok_(smc) ok_(smc.set(a_str, 1)) eq_(smc[a_str], 1)
f33bbdaae182eee27ad372a6f0d10e9c7be66a6f
polygraph/types/__init__.py
polygraph/types/__init__.py
from .enum import EnumType from .field import field from .input_object import InputObject from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "field", "Float", "ID", "InputObject", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
from .enum import EnumType, EnumValue from .field import field from .input_object import InputObject, InputValue from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "EnumValue", "field", "Float", "ID", "InputObject", "InputValue", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
Fix polygraph.types import to include EnumValue and InputValue
Fix polygraph.types import to include EnumValue and InputValue
Python
mit
polygraph-python/polygraph
- from .enum import EnumType + from .enum import EnumType, EnumValue from .field import field - from .input_object import InputObject + from .input_object import InputObject, InputValue from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", + "EnumValue", "field", "Float", "ID", "InputObject", + "InputValue", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
Fix polygraph.types import to include EnumValue and InputValue
## Code Before: from .enum import EnumType from .field import field from .input_object import InputObject from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "field", "Float", "ID", "InputObject", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ] ## Instruction: Fix polygraph.types import to include EnumValue and InputValue ## Code After: from .enum import EnumType, EnumValue from .field import field from .input_object import InputObject, InputValue from .interface import Interface from .lazy_type import LazyType from .list import List from .nonnull import NonNull from .object_type import ObjectType from .scalar import ID, Boolean, Float, Int, String from .union import Union __all__ = [ "Boolean", "EnumType", "EnumValue", "field", "Float", "ID", "InputObject", "InputValue", "Int", "Interface", "LazyType", "List", "NonNull", "ObjectType", "String", "Union", ]
8c6940a82b4504786e221f0603b8995db41adcae
reddit2telegram/channels/r_wholesome/app.py
reddit2telegram/channels/r_wholesome/app.py
subreddit = 'wholesome' t_channel = '@r_wholesome' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'wholesome+WholesomeComics+wholesomegifs+wholesomepics+wholesomememes' t_channel = '@r_wholesome' def send_post(submission, r2t): return r2t.send_simple(submission)
Add a few subreddits to @r_wholesome
Add a few subreddits to @r_wholesome
Python
mit
Fillll/reddit2telegram,Fillll/reddit2telegram
- subreddit = 'wholesome' + subreddit = 'wholesome+WholesomeComics+wholesomegifs+wholesomepics+wholesomememes' t_channel = '@r_wholesome' def send_post(submission, r2t): return r2t.send_simple(submission)
Add a few subreddits to @r_wholesome
## Code Before: subreddit = 'wholesome' t_channel = '@r_wholesome' def send_post(submission, r2t): return r2t.send_simple(submission) ## Instruction: Add a few subreddits to @r_wholesome ## Code After: subreddit = 'wholesome+WholesomeComics+wholesomegifs+wholesomepics+wholesomememes' t_channel = '@r_wholesome' def send_post(submission, r2t): return r2t.send_simple(submission)
ba4589e727a49486134e0cceab842510be9661f4
mobile_app_connector/models/privacy_statement.py
mobile_app_connector/models/privacy_statement.py
from odoo import models, fields class PrivacyStatementAgreement(models.Model): _inherit = 'privacy.statement.agreement' origin_signature = fields.Selection( selection_add=[('mobile_app', 'Mobile App Registration')]) def mobile_get_privacy_notice(self, language, **params): return {'PrivacyNotice': self.env['compassion.privacy.statement'] .with_context(lang=language) .sudo().search([], limit=1).text}
from ..controllers.mobile_app_controller import _get_lang from odoo import models, fields class PrivacyStatementAgreement(models.Model): _inherit = 'privacy.statement.agreement' origin_signature = fields.Selection( selection_add=[('mobile_app', 'Mobile App Registration')]) def mobile_get_privacy_notice(self, **params): lang = _get_lang(self, params) return {'PrivacyNotice': self.env['compassion.privacy.statement'] .with_context(lang=lang) .sudo().search([], limit=1).text}
FIX language of privacy statement
FIX language of privacy statement
Python
agpl-3.0
eicher31/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules
- + from ..controllers.mobile_app_controller import _get_lang from odoo import models, fields class PrivacyStatementAgreement(models.Model): _inherit = 'privacy.statement.agreement' origin_signature = fields.Selection( selection_add=[('mobile_app', 'Mobile App Registration')]) - def mobile_get_privacy_notice(self, language, **params): + def mobile_get_privacy_notice(self, **params): + lang = _get_lang(self, params) return {'PrivacyNotice': self.env['compassion.privacy.statement'] - .with_context(lang=language) + .with_context(lang=lang) .sudo().search([], limit=1).text}
FIX language of privacy statement
## Code Before: from odoo import models, fields class PrivacyStatementAgreement(models.Model): _inherit = 'privacy.statement.agreement' origin_signature = fields.Selection( selection_add=[('mobile_app', 'Mobile App Registration')]) def mobile_get_privacy_notice(self, language, **params): return {'PrivacyNotice': self.env['compassion.privacy.statement'] .with_context(lang=language) .sudo().search([], limit=1).text} ## Instruction: FIX language of privacy statement ## Code After: from ..controllers.mobile_app_controller import _get_lang from odoo import models, fields class PrivacyStatementAgreement(models.Model): _inherit = 'privacy.statement.agreement' origin_signature = fields.Selection( selection_add=[('mobile_app', 'Mobile App Registration')]) def mobile_get_privacy_notice(self, **params): lang = _get_lang(self, params) return {'PrivacyNotice': self.env['compassion.privacy.statement'] .with_context(lang=lang) .sudo().search([], limit=1).text}
e5b802b62c3c13aa9d213ddf4f51706921904dd1
src/texture.py
src/texture.py
from OpenGL.GL import * import pygame class Texture(object): """An OpenGL texture""" def __init__(self, file_): # Load and allocate the texture self.surface = pygame.image.load(file_).convert_alpha() self.__texture = glGenTextures(1) self.reload() def reload(self): # Set up the texture glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.__texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pygame.image.tostring(self.surface, "RGBA", True)) def bind(self): glBindTexture(GL_TEXTURE_2D, self.__texture) w = property(lambda self: self.surface.get_width()) h = property(lambda self: self.surface.get_height())
from OpenGL.GL import * import pygame class Texture(object): """An OpenGL texture""" def __init__(self, file_): """Allocate and load the texture""" self.surface = pygame.image.load(file_).convert_alpha() self.__texture = glGenTextures(1) self.reload() def __del__(self): """Release the texture""" glDeleteTextures([self.__texture]) def reload(self): """Load the texture""" glBindTexture(GL_TEXTURE_2D, self.__texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pygame.image.tostring(self.surface, "RGBA", True)) def bind(self): """Make the texture active in the current OpenGL context""" glBindTexture(GL_TEXTURE_2D, self.__texture) w = property(lambda self: self.surface.get_width()) h = property(lambda self: self.surface.get_height())
Remove resource leak in Texture
Remove resource leak in Texture This commit adds code to Texture to delete allocated textures when they are garbage collected. Comments in Texture are also updated.
Python
mit
aarmea/mumei,aarmea/mumei,aarmea/mumei
from OpenGL.GL import * import pygame class Texture(object): """An OpenGL texture""" def __init__(self, file_): - # Load and allocate the texture + """Allocate and load the texture""" self.surface = pygame.image.load(file_).convert_alpha() self.__texture = glGenTextures(1) self.reload() + def __del__(self): + """Release the texture""" + glDeleteTextures([self.__texture]) + def reload(self): + """Load the texture""" - # Set up the texture - glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.__texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pygame.image.tostring(self.surface, "RGBA", True)) def bind(self): + """Make the texture active in the current OpenGL context""" glBindTexture(GL_TEXTURE_2D, self.__texture) w = property(lambda self: self.surface.get_width()) h = property(lambda self: self.surface.get_height())
Remove resource leak in Texture
## Code Before: from OpenGL.GL import * import pygame class Texture(object): """An OpenGL texture""" def __init__(self, file_): # Load and allocate the texture self.surface = pygame.image.load(file_).convert_alpha() self.__texture = glGenTextures(1) self.reload() def reload(self): # Set up the texture glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.__texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pygame.image.tostring(self.surface, "RGBA", True)) def bind(self): glBindTexture(GL_TEXTURE_2D, self.__texture) w = property(lambda self: self.surface.get_width()) h = property(lambda self: self.surface.get_height()) ## Instruction: Remove resource leak in Texture ## Code After: from OpenGL.GL import * import pygame class Texture(object): """An OpenGL texture""" def __init__(self, file_): """Allocate and load the texture""" self.surface = pygame.image.load(file_).convert_alpha() self.__texture = glGenTextures(1) self.reload() def __del__(self): """Release the texture""" glDeleteTextures([self.__texture]) def reload(self): """Load the texture""" glBindTexture(GL_TEXTURE_2D, self.__texture) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, self.w, self.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, pygame.image.tostring(self.surface, "RGBA", True)) def bind(self): """Make the texture active in the current OpenGL context""" glBindTexture(GL_TEXTURE_2D, self.__texture) w = property(lambda self: self.surface.get_width()) h = property(lambda self: self.surface.get_height())
129b4d169f33e46547a7a701e4e50b7dd9fe8468
traits/qt/__init__.py
traits/qt/__init__.py
import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside')
import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'" % qt_api)
Fix error message for invalid QT_API.
Fix error message for invalid QT_API.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': - raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside') + raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'" + % qt_api)
Fix error message for invalid QT_API.
## Code Before: import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError('Invalid Qt API %r, valid values are: pyqt or pyside') ## Instruction: Fix error message for invalid QT_API. ## Code After: import os def prepare_pyqt4(): # Set PySide compatible APIs. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: prepare_pyqt4() import PyQt4 qt_api = 'pyqt' except ImportError: raise ImportError('Cannot import PySide or PyQt4') elif qt_api == 'pyqt': prepare_pyqt4() elif qt_api != 'pyside': raise RuntimeError("Invalid Qt API %r, valid values are: 'pyqt' or 'pyside'" % qt_api)
b66143e2984fb390766cf47dd2297a3f06ad26d0
apps/home/views.py
apps/home/views.py
from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login from django.contrib.auth import get_user_model class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
Add import statement for get_user_model.
Add import statement for get_user_model.
Python
mit
dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse,dstl/lighthouse
from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login + from django.contrib.auth import get_user_model class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
Add import statement for get_user_model.
## Code Before: from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login')) ## Instruction: Add import statement for get_user_model. ## Code After: from django.core.urlresolvers import reverse from django.shortcuts import redirect from django.views.generic.base import View from django.contrib.auth import login from django.contrib.auth import get_user_model class Home(View): # Get the homepage. If the user isn't logged in, (we can find no trace # of the user) or they are logged in but somehow don't have a valid slug # then we bounce them to the login page. # Otherwise (for the moment) we take them to the list of links. def get(self, request, *args, **kwargs): userid = request.META.get('HTTP_KEYCLOAK_USERNAME') if userid: try: user = get_user_model().objects.get(userid=userid) except: user = get_user_model().objects.create_user( userid=userid, is_active=True) user.backend = 'django.contrib.auth.backends.ModelBackend' login(self.request, user) self.user = user return redirect(reverse('link-list')) try: u = request.user.slug if (u is not None and u is not ''): return redirect(reverse('link-list')) else: return redirect(reverse('login')) except: return redirect(reverse('login'))
f9332afe031f4d7875b8c6dd53392a46a198fc9e
evaluation/packages/utils.py
evaluation/packages/utils.py
def distanceToPrimitives(cloud, assign, primitives): return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in assign]
def distanceToPrimitives(cloud, assign, primitives): return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in assign] import packages.orderedSet as orderedSet def parseAngles(strAngle): angles = orderedSet.OrderedSet() angles.add(0.) if len(strAngle) == 1: strAngle = strAngle[0].split(',') for genAngle in strAngle: a = float(genAngle) while a <= 180.: angles.add(a) a+= float(genAngle) return angles
Add method to parse angle command line arguments
Add method to parse angle command line arguments
Python
apache-2.0
amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt
def distanceToPrimitives(cloud, assign, primitives): return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in assign] + + + + import packages.orderedSet as orderedSet + def parseAngles(strAngle): + angles = orderedSet.OrderedSet() + angles.add(0.) + if len(strAngle) == 1: + strAngle = strAngle[0].split(',') + for genAngle in strAngle: + a = float(genAngle) + while a <= 180.: + angles.add(a) + a+= float(genAngle) + + return angles + +
Add method to parse angle command line arguments
## Code Before: def distanceToPrimitives(cloud, assign, primitives): return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in assign] ## Instruction: Add method to parse angle command line arguments ## Code After: def distanceToPrimitives(cloud, assign, primitives): return [ [primVar.distanceTo(cloud[a[0]]) for primVar in primitives if primVar.uid == a[1]] for a in assign] import packages.orderedSet as orderedSet def parseAngles(strAngle): angles = orderedSet.OrderedSet() angles.add(0.) if len(strAngle) == 1: strAngle = strAngle[0].split(',') for genAngle in strAngle: a = float(genAngle) while a <= 180.: angles.add(a) a+= float(genAngle) return angles
21368fc9354e3c55132a0d42a734802c00466cb6
blimpy/__init__.py
blimpy/__init__.py
from __future__ import absolute_import try: from . import waterfall from .waterfall import Waterfall from .guppi import GuppiRaw from . import utils from . import fil2h5 from . import h52fil from . import h5diag from . import bl_scrunch from . import calcload from . import rawhdr from . import stax from . import stix from . import match_fils from blimpy.io import file_wrapper except: print("Warning: At least one utility could not be imported!") from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('blimpy').version except DistributionNotFound: __version__ = '0.0.0 - please install via pip/setup.py'
from __future__ import absolute_import try: from . import waterfall from .waterfall import Waterfall from .guppi import GuppiRaw from . import utils from . import fil2h5 from . import h52fil from . import h5diag from . import bl_scrunch from . import calcload from . import rawhdr from . import stax from . import stix from . import match_fils from . import dsamp from blimpy.io import file_wrapper except: print("Warning: At least one utility could not be imported!") from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('blimpy').version except DistributionNotFound: __version__ = '0.0.0 - please install via pip/setup.py'
Make dsamp a visible component of blimpy
Make dsamp a visible component of blimpy
Python
bsd-3-clause
UCBerkeleySETI/blimpy,UCBerkeleySETI/blimpy
from __future__ import absolute_import try: from . import waterfall from .waterfall import Waterfall from .guppi import GuppiRaw from . import utils from . import fil2h5 from . import h52fil from . import h5diag from . import bl_scrunch from . import calcload from . import rawhdr from . import stax from . import stix from . import match_fils + from . import dsamp from blimpy.io import file_wrapper except: print("Warning: At least one utility could not be imported!") from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('blimpy').version except DistributionNotFound: __version__ = '0.0.0 - please install via pip/setup.py'
Make dsamp a visible component of blimpy
## Code Before: from __future__ import absolute_import try: from . import waterfall from .waterfall import Waterfall from .guppi import GuppiRaw from . import utils from . import fil2h5 from . import h52fil from . import h5diag from . import bl_scrunch from . import calcload from . import rawhdr from . import stax from . import stix from . import match_fils from blimpy.io import file_wrapper except: print("Warning: At least one utility could not be imported!") from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('blimpy').version except DistributionNotFound: __version__ = '0.0.0 - please install via pip/setup.py' ## Instruction: Make dsamp a visible component of blimpy ## Code After: from __future__ import absolute_import try: from . import waterfall from .waterfall import Waterfall from .guppi import GuppiRaw from . import utils from . import fil2h5 from . import h52fil from . import h5diag from . import bl_scrunch from . import calcload from . import rawhdr from . import stax from . import stix from . import match_fils from . import dsamp from blimpy.io import file_wrapper except: print("Warning: At least one utility could not be imported!") from pkg_resources import get_distribution, DistributionNotFound try: __version__ = get_distribution('blimpy').version except DistributionNotFound: __version__ = '0.0.0 - please install via pip/setup.py'
a6fda9344461424d9da4f70772443a2a283a8da1
test/test_client.py
test/test_client.py
import unittest import delighted class ClientTest(unittest.TestCase): def test_instantiating_client_requires_api_key(self): self.assertRaises(ValueError, lambda: delighted.Client()) delighted.Client(api_key='abc123')
import unittest import delighted class ClientTest(unittest.TestCase): def test_instantiating_client_requires_api_key(self): original_api_key = delighted.api_key try: delighted.api_key = None self.assertRaises(ValueError, lambda: delighted.Client()) delighted.Client(api_key='abc123') except: delighted.api_key = original_api_key
Make no-api-key test more reliable
Make no-api-key test more reliable
Python
mit
mkdynamic/delighted-python,delighted/delighted-python,kaeawc/delighted-python
import unittest import delighted class ClientTest(unittest.TestCase): def test_instantiating_client_requires_api_key(self): + original_api_key = delighted.api_key + try: + delighted.api_key = None - self.assertRaises(ValueError, lambda: delighted.Client()) + self.assertRaises(ValueError, lambda: delighted.Client()) - delighted.Client(api_key='abc123') + delighted.Client(api_key='abc123') + except: + delighted.api_key = original_api_key
Make no-api-key test more reliable
## Code Before: import unittest import delighted class ClientTest(unittest.TestCase): def test_instantiating_client_requires_api_key(self): self.assertRaises(ValueError, lambda: delighted.Client()) delighted.Client(api_key='abc123') ## Instruction: Make no-api-key test more reliable ## Code After: import unittest import delighted class ClientTest(unittest.TestCase): def test_instantiating_client_requires_api_key(self): original_api_key = delighted.api_key try: delighted.api_key = None self.assertRaises(ValueError, lambda: delighted.Client()) delighted.Client(api_key='abc123') except: delighted.api_key = original_api_key
45990438d22dc15cdd62f85e541f929ca88eed6b
ggp-base/src_py/random_gamer.py
ggp-base/src_py/random_gamer.py
''' @author: Sam ''' import random from org.ggp.base.util.statemachine import MachineState from org.ggp.base.util.statemachine.implementation.prover import ProverStateMachine from org.ggp.base.player.gamer.statemachine import StateMachineGamer from org.ggp.base.player.gamer.statemachine.reflex.event import ReflexMoveSelectionEvent class PythonRandomGamer(StateMachineGamer): def getName(self): pass def stateMachineMetaGame(self, timeout): pass def stateMachineSelectMove(self, timeout): moves = self.getStateMachine().getLegalMoves(self.getCurrentState(), self.getRole()) selection = random.choice(moves) self.notifyObservers(ReflexMoveSelectionEvent(moves, selection, 1)) return selection def stateMachineStop(self): pass def stateMachineAbort(self): pass def getInitialStateMachine(self): return ProverStateMachine()
''' @author: Sam ''' import random from org.ggp.base.util.statemachine import MachineState from org.ggp.base.util.statemachine.implementation.prover import ProverStateMachine from org.ggp.base.player.gamer.statemachine import StateMachineGamer class PythonRandomGamer(StateMachineGamer): def getName(self): pass def stateMachineMetaGame(self, timeout): pass def stateMachineSelectMove(self, timeout): moves = self.getStateMachine().getLegalMoves(self.getCurrentState(), self.getRole()) selection = random.choice(moves) return selection def stateMachineStop(self): pass def stateMachineAbort(self): pass def getInitialStateMachine(self): return ProverStateMachine()
Fix a bug in the example python gamer.
Fix a bug in the example python gamer. git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@552 716a755e-b13f-cedc-210d-596dafc6fb9b
Python
bsd-3-clause
cerebro/ggp-base,cerebro/ggp-base
''' @author: Sam ''' import random from org.ggp.base.util.statemachine import MachineState from org.ggp.base.util.statemachine.implementation.prover import ProverStateMachine - from org.ggp.base.player.gamer.statemachine import StateMachineGamer - from org.ggp.base.player.gamer.statemachine.reflex.event import ReflexMoveSelectionEvent class PythonRandomGamer(StateMachineGamer): def getName(self): pass def stateMachineMetaGame(self, timeout): pass def stateMachineSelectMove(self, timeout): moves = self.getStateMachine().getLegalMoves(self.getCurrentState(), self.getRole()) selection = random.choice(moves) - self.notifyObservers(ReflexMoveSelectionEvent(moves, selection, 1)) return selection def stateMachineStop(self): pass def stateMachineAbort(self): pass def getInitialStateMachine(self): return ProverStateMachine()
Fix a bug in the example python gamer.
## Code Before: ''' @author: Sam ''' import random from org.ggp.base.util.statemachine import MachineState from org.ggp.base.util.statemachine.implementation.prover import ProverStateMachine from org.ggp.base.player.gamer.statemachine import StateMachineGamer from org.ggp.base.player.gamer.statemachine.reflex.event import ReflexMoveSelectionEvent class PythonRandomGamer(StateMachineGamer): def getName(self): pass def stateMachineMetaGame(self, timeout): pass def stateMachineSelectMove(self, timeout): moves = self.getStateMachine().getLegalMoves(self.getCurrentState(), self.getRole()) selection = random.choice(moves) self.notifyObservers(ReflexMoveSelectionEvent(moves, selection, 1)) return selection def stateMachineStop(self): pass def stateMachineAbort(self): pass def getInitialStateMachine(self): return ProverStateMachine() ## Instruction: Fix a bug in the example python gamer. ## Code After: ''' @author: Sam ''' import random from org.ggp.base.util.statemachine import MachineState from org.ggp.base.util.statemachine.implementation.prover import ProverStateMachine from org.ggp.base.player.gamer.statemachine import StateMachineGamer class PythonRandomGamer(StateMachineGamer): def getName(self): pass def stateMachineMetaGame(self, timeout): pass def stateMachineSelectMove(self, timeout): moves = self.getStateMachine().getLegalMoves(self.getCurrentState(), self.getRole()) selection = random.choice(moves) return selection def stateMachineStop(self): pass def stateMachineAbort(self): pass def getInitialStateMachine(self): return ProverStateMachine()
9548247251399a4fbe7a140c5d8db64e8dd71b46
cobe/instatrace.py
cobe/instatrace.py
import datetime import math import os import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: # rotate logs if os.path.exists(filename): now = datetime.datetime.now() stamp = now.strftime("%Y-%m-%d.%H%M%S") os.rename(filename, "%s.%s" % (filename, stamp)) self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """Microsecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def now_ms(self): """Millisecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*1000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra)) self._fd.flush()
import datetime import math import os import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: # rotate logs if os.path.exists(filename): now = datetime.datetime.now() stamp = now.strftime("%Y-%m-%d.%H%M%S") os.rename(filename, "%s.%s" % (filename, stamp)) self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """Microsecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def now_ms(self): """Millisecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*1000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra))
Remove a debugging flush() after every trace
Remove a debugging flush() after every trace
Python
mit
wodim/cobe-ng,wodim/cobe-ng,tiagochiavericosta/cobe,LeMagnesium/cobe,LeMagnesium/cobe,DarkMio/cobe,pteichman/cobe,meska/cobe,meska/cobe,pteichman/cobe,DarkMio/cobe,tiagochiavericosta/cobe
import datetime import math import os import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: # rotate logs if os.path.exists(filename): now = datetime.datetime.now() stamp = now.strftime("%Y-%m-%d.%H%M%S") os.rename(filename, "%s.%s" % (filename, stamp)) self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """Microsecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def now_ms(self): """Millisecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*1000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra)) - self._fd.flush()
Remove a debugging flush() after every trace
## Code Before: import datetime import math import os import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: # rotate logs if os.path.exists(filename): now = datetime.datetime.now() stamp = now.strftime("%Y-%m-%d.%H%M%S") os.rename(filename, "%s.%s" % (filename, stamp)) self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """Microsecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def now_ms(self): """Millisecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*1000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra)) self._fd.flush() ## Instruction: Remove a debugging flush() after every trace ## Code After: import datetime import math import os import time def singleton(cls): instances = {} def getinstance(): if cls not in instances: instances[cls] = cls() return instances[cls] return getinstance @singleton class Instatrace: def __init__(self): self._fd = None def init(self, filename): if self._fd is not None: self._fd.close() if filename is None: self._fd = None else: # rotate logs if os.path.exists(filename): now = datetime.datetime.now() stamp = now.strftime("%Y-%m-%d.%H%M%S") os.rename(filename, "%s.%s" % (filename, stamp)) self._fd = open(filename, "w") def is_enabled(self): return self._fd is not None def now(self): """Microsecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*100000) def now_ms(self): """Millisecond resolution, integer now""" if not self.is_enabled(): return 0 return int(time.time()*1000) def trace(self, statName, statValue, userData=None): if not self.is_enabled(): return extra = "" if userData is not None: extra = " " + repr(userData) self._fd.write("%s %d%s\n" % (statName, statValue, extra))
a456449c5a30ea9ad9af308ea407246425ad288e
students/crobison/session04/file_lab.py
students/crobison/session04/file_lab.py
import os cwd = os.getcwd() # write a program which prints the full path to all files # in the current directory, one per line for item in os.listdir(cwd): print(cwd + "/" + item) # write a program which copies a file from a source, to a # destination (without using shutil, or the OS copy command) file = open('file_lab01.txt', 'r') file_text = file.read() file_new = open('file_lab02.txt', 'w') file_new.write(file_text) file.close() file_new.close() # advanced: make it work for any size file: i.e. don’t read # the entire contents of the file into memory at once. file = open('file_lab01.txt', 'r') file_new = open('file_lab02.txt', 'w') file_text = file.readline() for line in file_text: file_new.write(line) line = file.readline() file.close() file_new.close() # not working correctl, second try: print('second try:') file_new = open('file_labe02.txt', 'w') with open('file_lab01.txt', 'r') as f: for line in f: file_text = f.readline() file_new.write(line) file_new.close()
import os cwd = os.getcwd() # write a program which prints the full path to all files # in the current directory, one per line for item in os.listdir(cwd): print(cwd + "/" + item) # write a program which copies a file from a source, to a # destination (without using shutil, or the OS copy command) file = open('file_lab01.txt', 'r') file_text = file.read() file_new = open('file_lab02.txt', 'w') file_new.write(file_text) file.close() file_new.close() # advanced: make it work for any size file: i.e. don’t read # the entire contents of the file into memory at once. with open('file_lab01.txt','r') as r, open('file_lab02.txt', 'w') as w: for line in r: w.write(line) r.close() w.close()
Fix section to read and write large files.
Fix section to read and write large files.
Python
unlicense
UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,Baumelbi/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,Baumelbi/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016
import os cwd = os.getcwd() # write a program which prints the full path to all files # in the current directory, one per line for item in os.listdir(cwd): print(cwd + "/" + item) # write a program which copies a file from a source, to a # destination (without using shutil, or the OS copy command) file = open('file_lab01.txt', 'r') file_text = file.read() file_new = open('file_lab02.txt', 'w') file_new.write(file_text) file.close() file_new.close() # advanced: make it work for any size file: i.e. don’t read # the entire contents of the file into memory at once. + with open('file_lab01.txt','r') as r, open('file_lab02.txt', 'w') as w: + for line in r: - file = open('file_lab01.txt', 'r') - file_new = open('file_lab02.txt', 'w') - file_text = file.readline() - for line in file_text: - file_new.write(line) + w.write(line) - line = file.readline() - file.close() + r.close() - file_new.close() + w.close() - # not working correctl, second try: - print('second try:') - file_new = open('file_labe02.txt', 'w') - with open('file_lab01.txt', 'r') as f: - for line in f: - file_text = f.readline() - file_new.write(line) - file_new.close()
Fix section to read and write large files.
## Code Before: import os cwd = os.getcwd() # write a program which prints the full path to all files # in the current directory, one per line for item in os.listdir(cwd): print(cwd + "/" + item) # write a program which copies a file from a source, to a # destination (without using shutil, or the OS copy command) file = open('file_lab01.txt', 'r') file_text = file.read() file_new = open('file_lab02.txt', 'w') file_new.write(file_text) file.close() file_new.close() # advanced: make it work for any size file: i.e. don’t read # the entire contents of the file into memory at once. file = open('file_lab01.txt', 'r') file_new = open('file_lab02.txt', 'w') file_text = file.readline() for line in file_text: file_new.write(line) line = file.readline() file.close() file_new.close() # not working correctl, second try: print('second try:') file_new = open('file_labe02.txt', 'w') with open('file_lab01.txt', 'r') as f: for line in f: file_text = f.readline() file_new.write(line) file_new.close() ## Instruction: Fix section to read and write large files. ## Code After: import os cwd = os.getcwd() # write a program which prints the full path to all files # in the current directory, one per line for item in os.listdir(cwd): print(cwd + "/" + item) # write a program which copies a file from a source, to a # destination (without using shutil, or the OS copy command) file = open('file_lab01.txt', 'r') file_text = file.read() file_new = open('file_lab02.txt', 'w') file_new.write(file_text) file.close() file_new.close() # advanced: make it work for any size file: i.e. don’t read # the entire contents of the file into memory at once. with open('file_lab01.txt','r') as r, open('file_lab02.txt', 'w') as w: for line in r: w.write(line) r.close() w.close()
818fdb1a2d2cfbe0ef3de66443eb726c4b0cead5
test/cli/test_cmd_piper.py
test/cli/test_cmd_piper.py
from piper import build from piper.db import core as db from piper.cli import cmd_piper import mock class TestEntry(object): @mock.patch('piper.cli.cmd_piper.CLIBase') def test_calls(self, clibase): self.mock = mock.Mock() cmd_piper.entry(self.mock) clibase.assert_called_once_with( 'piper', (build.ExecCLI, db.DbCLI), args=self.mock ) clibase.return_value.entry.assert_called_once_with() @mock.patch('piper.cli.cmd_piper.CLIBase') def test_return_value(self, clibase): ret = cmd_piper.entry() assert ret is clibase.return_value.entry.return_value
from piper import build from piper.db import core as db from piper.cli import cmd_piper from piper.cli.cli import CLIBase import mock class TestEntry(object): @mock.patch('piper.cli.cmd_piper.CLIBase') def test_calls(self, clibase): self.mock = mock.Mock() cmd_piper.entry(self.mock) clibase.assert_called_once_with( 'piper', (build.ExecCLI, db.DbCLI), args=self.mock ) clibase.return_value.entry.assert_called_once_with() @mock.patch('piper.cli.cmd_piper.CLIBase') def test_return_value(self, clibase): ret = cmd_piper.entry() assert ret is clibase.return_value.entry.return_value class TestEntryIntegration(object): def test_db_init(self): args = ['db', 'init'] cli = CLIBase('piper', (db.DbCLI,), args=args) db.DbCLI.db = mock.Mock() cli.entry() db.DbCLI.db.init.assert_called_once_with(cli.config)
Add integration test for db init
Add integration test for db init
Python
mit
thiderman/piper
from piper import build from piper.db import core as db from piper.cli import cmd_piper + from piper.cli.cli import CLIBase import mock class TestEntry(object): @mock.patch('piper.cli.cmd_piper.CLIBase') def test_calls(self, clibase): self.mock = mock.Mock() cmd_piper.entry(self.mock) clibase.assert_called_once_with( 'piper', (build.ExecCLI, db.DbCLI), args=self.mock ) clibase.return_value.entry.assert_called_once_with() @mock.patch('piper.cli.cmd_piper.CLIBase') def test_return_value(self, clibase): ret = cmd_piper.entry() assert ret is clibase.return_value.entry.return_value + + class TestEntryIntegration(object): + def test_db_init(self): + args = ['db', 'init'] + cli = CLIBase('piper', (db.DbCLI,), args=args) + + db.DbCLI.db = mock.Mock() + cli.entry() + db.DbCLI.db.init.assert_called_once_with(cli.config) +
Add integration test for db init
## Code Before: from piper import build from piper.db import core as db from piper.cli import cmd_piper import mock class TestEntry(object): @mock.patch('piper.cli.cmd_piper.CLIBase') def test_calls(self, clibase): self.mock = mock.Mock() cmd_piper.entry(self.mock) clibase.assert_called_once_with( 'piper', (build.ExecCLI, db.DbCLI), args=self.mock ) clibase.return_value.entry.assert_called_once_with() @mock.patch('piper.cli.cmd_piper.CLIBase') def test_return_value(self, clibase): ret = cmd_piper.entry() assert ret is clibase.return_value.entry.return_value ## Instruction: Add integration test for db init ## Code After: from piper import build from piper.db import core as db from piper.cli import cmd_piper from piper.cli.cli import CLIBase import mock class TestEntry(object): @mock.patch('piper.cli.cmd_piper.CLIBase') def test_calls(self, clibase): self.mock = mock.Mock() cmd_piper.entry(self.mock) clibase.assert_called_once_with( 'piper', (build.ExecCLI, db.DbCLI), args=self.mock ) clibase.return_value.entry.assert_called_once_with() @mock.patch('piper.cli.cmd_piper.CLIBase') def test_return_value(self, clibase): ret = cmd_piper.entry() assert ret is clibase.return_value.entry.return_value class TestEntryIntegration(object): def test_db_init(self): args = ['db', 'init'] cli = CLIBase('piper', (db.DbCLI,), args=args) db.DbCLI.db = mock.Mock() cli.entry() db.DbCLI.db.init.assert_called_once_with(cli.config)
f1df5f74699a152d8dc2cac8e4dcf80a1523ca99
setup.py
setup.py
from distutils.core import setup setup(name='dshelpers', version='1.3.0', description="Provides some helper functions used by the ScraperWiki Data Services team.", long_description="Provides some helper functions used by the ScraperWiki Data Services team.", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], author="ScraperWiki Limited", author_email='dataservices@scraperwiki.com', url='https://github.com/scraperwiki/data-services-helpers', license='BSD', py_modules=['dshelpers'], install_requires=['requests', 'requests_cache', 'mock', 'nose', 'scraperwiki'], )
from distutils.core import setup setup(name='dshelpers', version='1.3.0', description="Provides some helper functions used by The Sensible Code Company's Data Services team.", long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], author="The Sensible Code Company Limited", author_email='dataservices@sensiblecode.io', url='https://github.com/scraperwiki/data-services-helpers', license='BSD', py_modules=['dshelpers'], install_requires=['requests', 'requests_cache', 'mock', 'nose', 'scraperwiki'], )
Rename ScraperWiki to Sensible Code in README
Rename ScraperWiki to Sensible Code in README
Python
bsd-2-clause
scraperwiki/data-services-helpers
from distutils.core import setup setup(name='dshelpers', version='1.3.0', - description="Provides some helper functions used by the ScraperWiki Data Services team.", + description="Provides some helper functions used by The Sensible Code Company's Data Services team.", - long_description="Provides some helper functions used by the ScraperWiki Data Services team.", + long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], - author="ScraperWiki Limited", + author="The Sensible Code Company Limited", - author_email='dataservices@scraperwiki.com', + author_email='dataservices@sensiblecode.io', url='https://github.com/scraperwiki/data-services-helpers', license='BSD', py_modules=['dshelpers'], install_requires=['requests', 'requests_cache', 'mock', 'nose', 'scraperwiki'], )
Rename ScraperWiki to Sensible Code in README
## Code Before: from distutils.core import setup setup(name='dshelpers', version='1.3.0', description="Provides some helper functions used by the ScraperWiki Data Services team.", long_description="Provides some helper functions used by the ScraperWiki Data Services team.", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], author="ScraperWiki Limited", author_email='dataservices@scraperwiki.com', url='https://github.com/scraperwiki/data-services-helpers', license='BSD', py_modules=['dshelpers'], install_requires=['requests', 'requests_cache', 'mock', 'nose', 'scraperwiki'], ) ## Instruction: Rename ScraperWiki to Sensible Code in README ## Code After: from distutils.core import setup setup(name='dshelpers', version='1.3.0', description="Provides some helper functions used by The Sensible Code Company's Data Services team.", long_description="Provides some helper functions used by the The Sensible Code Company's Data Services team.", classifiers=["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", ], author="The Sensible Code Company Limited", author_email='dataservices@sensiblecode.io', url='https://github.com/scraperwiki/data-services-helpers', license='BSD', py_modules=['dshelpers'], install_requires=['requests', 'requests_cache', 'mock', 'nose', 'scraperwiki'], )
6353a3d1443c717b2d2e804190153f8be605c2f1
setup.py
setup.py
from distutils.core import setup with open('README.rst') as readme: long_description = readme.read() setup( name='udiskie', version='0.4.2', description='Removable disk automounter for udisks', long_description=long_description, author='Byron Clark', author_email='byron@theclarkfamily.name', maintainer='Thomas Gläßle', maintainer_email='t_glaessle@gmx.de', url='https://github.com/coldfix/udiskie', license='MIT', packages=[ 'udiskie', ], scripts=[ 'bin/udiskie', 'bin/udiskie-umount', ], )
from distutils.core import setup with open('README.rst') as readme: long_description = readme.read() setup( name='udiskie', version='0.4.2', description='Removable disk automounter for udisks', long_description=long_description, author='Byron Clark', author_email='byron@theclarkfamily.name', maintainer='Thomas Gläßle', maintainer_email='t_glaessle@gmx.de', url='https://github.com/coldfix/udiskie', license='MIT', packages=[ 'udiskie', ], scripts=[ 'bin/udiskie', 'bin/udiskie-umount', 'bin/udiskie-mount' ], )
Include udiskie-mount in binary distribution
Include udiskie-mount in binary distribution
Python
mit
khardix/udiskie,pstray/udiskie,coldfix/udiskie,coldfix/udiskie,mathstuf/udiskie,pstray/udiskie
from distutils.core import setup with open('README.rst') as readme: long_description = readme.read() setup( name='udiskie', version='0.4.2', description='Removable disk automounter for udisks', long_description=long_description, author='Byron Clark', author_email='byron@theclarkfamily.name', maintainer='Thomas Gläßle', maintainer_email='t_glaessle@gmx.de', url='https://github.com/coldfix/udiskie', license='MIT', packages=[ 'udiskie', ], scripts=[ 'bin/udiskie', 'bin/udiskie-umount', + 'bin/udiskie-mount' ], )
Include udiskie-mount in binary distribution
## Code Before: from distutils.core import setup with open('README.rst') as readme: long_description = readme.read() setup( name='udiskie', version='0.4.2', description='Removable disk automounter for udisks', long_description=long_description, author='Byron Clark', author_email='byron@theclarkfamily.name', maintainer='Thomas Gläßle', maintainer_email='t_glaessle@gmx.de', url='https://github.com/coldfix/udiskie', license='MIT', packages=[ 'udiskie', ], scripts=[ 'bin/udiskie', 'bin/udiskie-umount', ], ) ## Instruction: Include udiskie-mount in binary distribution ## Code After: from distutils.core import setup with open('README.rst') as readme: long_description = readme.read() setup( name='udiskie', version='0.4.2', description='Removable disk automounter for udisks', long_description=long_description, author='Byron Clark', author_email='byron@theclarkfamily.name', maintainer='Thomas Gläßle', maintainer_email='t_glaessle@gmx.de', url='https://github.com/coldfix/udiskie', license='MIT', packages=[ 'udiskie', ], scripts=[ 'bin/udiskie', 'bin/udiskie-umount', 'bin/udiskie-mount' ], )
dea503e03a7c18c256d902b0b6ad3cb66a7ce9a2
examples/flexure/example_point_load.py
examples/flexure/example_point_load.py
from landlab import RasterModelGrid from landlab.components.flexure import Flexure def add_load_to_middle_of_grid(grid, load): shape = grid.shape load_array = grid.field_values( "node", "lithosphere__overlying_pressure_increment" ).view() load_array.shape = shape load_array[shape[0] / 2, shape[1] / 2] = load def main(): (n_rows, n_cols) = (100, 100) (dy, dx) = (10e3, 10e3) grid = RasterModelGrid(n_rows, n_cols, dx) flex = Flexure(grid, method="flexure") add_load_to_middle_of_grid(grid, 1e7) flex.update() grid.imshow( "node", "lithosphere_surface__elevation_increment", symmetric_cbar=True, show=True, ) if __name__ == "__main__": main()
from landlab import RasterModelGrid from landlab.components.flexure import Flexure def add_load_to_middle_of_grid(grid, load): shape = grid.shape load_array = grid.field_values( "node", "lithosphere__overlying_pressure_increment" ).view() load_array.shape = shape load_array[shape[0] / 2, shape[1] / 2] = load def main(): (n_rows, n_cols) = (100, 100) spacing = (10e3, 10e3) grid = RasterModelGrid(n_rows, n_cols, spacing[1]) flex = Flexure(grid, method="flexure") add_load_to_middle_of_grid(grid, 1e7) flex.update() grid.imshow( "node", "lithosphere_surface__elevation_increment", symmetric_cbar=True, show=True, ) if __name__ == "__main__": main()
Fix F841: local variable is assigned to but never used.
Fix F841: local variable is assigned to but never used.
Python
mit
amandersillinois/landlab,cmshobe/landlab,landlab/landlab,cmshobe/landlab,amandersillinois/landlab,cmshobe/landlab,landlab/landlab,landlab/landlab
from landlab import RasterModelGrid from landlab.components.flexure import Flexure def add_load_to_middle_of_grid(grid, load): shape = grid.shape load_array = grid.field_values( "node", "lithosphere__overlying_pressure_increment" ).view() load_array.shape = shape load_array[shape[0] / 2, shape[1] / 2] = load def main(): (n_rows, n_cols) = (100, 100) - (dy, dx) = (10e3, 10e3) + spacing = (10e3, 10e3) - grid = RasterModelGrid(n_rows, n_cols, dx) + grid = RasterModelGrid(n_rows, n_cols, spacing[1]) flex = Flexure(grid, method="flexure") add_load_to_middle_of_grid(grid, 1e7) flex.update() grid.imshow( "node", "lithosphere_surface__elevation_increment", symmetric_cbar=True, show=True, ) if __name__ == "__main__": main()
Fix F841: local variable is assigned to but never used.
## Code Before: from landlab import RasterModelGrid from landlab.components.flexure import Flexure def add_load_to_middle_of_grid(grid, load): shape = grid.shape load_array = grid.field_values( "node", "lithosphere__overlying_pressure_increment" ).view() load_array.shape = shape load_array[shape[0] / 2, shape[1] / 2] = load def main(): (n_rows, n_cols) = (100, 100) (dy, dx) = (10e3, 10e3) grid = RasterModelGrid(n_rows, n_cols, dx) flex = Flexure(grid, method="flexure") add_load_to_middle_of_grid(grid, 1e7) flex.update() grid.imshow( "node", "lithosphere_surface__elevation_increment", symmetric_cbar=True, show=True, ) if __name__ == "__main__": main() ## Instruction: Fix F841: local variable is assigned to but never used. ## Code After: from landlab import RasterModelGrid from landlab.components.flexure import Flexure def add_load_to_middle_of_grid(grid, load): shape = grid.shape load_array = grid.field_values( "node", "lithosphere__overlying_pressure_increment" ).view() load_array.shape = shape load_array[shape[0] / 2, shape[1] / 2] = load def main(): (n_rows, n_cols) = (100, 100) spacing = (10e3, 10e3) grid = RasterModelGrid(n_rows, n_cols, spacing[1]) flex = Flexure(grid, method="flexure") add_load_to_middle_of_grid(grid, 1e7) flex.update() grid.imshow( "node", "lithosphere_surface__elevation_increment", symmetric_cbar=True, show=True, ) if __name__ == "__main__": main()
584956dce7cd607c6cb0d24d360d65d1c0be7005
lib/pylprof/dump-stats.py
lib/pylprof/dump-stats.py
import json stats = lp.get_stats() unit = stats.unit results = {} for function, timings in stats.timings.iteritems(): module, line, fname = function results[module] = {} for sample in timings: linenumber, ncalls, timing = sample if not results[module].get(linenumber): results[module][linenumber] = [] results[module][linenumber].append({ 'name' : '', 'timing' : [ncalls, timing*unit, timing*unit*ncalls] }) jsondump = json.dumps(results) print('statsstart' + jsondump + 'statsend') sys.stdout.flush() exit()
import json import sys from collections import defaultdict stats = lp.get_stats() unit = stats.unit results = {} for loc, timings in stats.timings.iteritems(): module, line, fname = loc if not results.get(module): results[module] = defaultdict(list) for sample in timings: linenumber, ncalls, timing = sample results[module][linenumber].append({ 'timing' : [ncalls, timing*unit, timing*unit*ncalls] }) statsdump = json.dumps(results) print('statsstart{0}statsend'.format(statsdump)) sys.stdout.flush() exit()
Fix bug when profiling multiple fcts per module
[pylprof] Fix bug when profiling multiple fcts per module
Python
mit
iddl/pprofile,iddl/pprofile
import json + import sys + from collections import defaultdict + stats = lp.get_stats() unit = stats.unit results = {} - for function, timings in stats.timings.iteritems(): + for loc, timings in stats.timings.iteritems(): - module, line, fname = function + module, line, fname = loc - results[module] = {} + if not results.get(module): + results[module] = defaultdict(list) for sample in timings: linenumber, ncalls, timing = sample - if not results[module].get(linenumber): - results[module][linenumber] = [] results[module][linenumber].append({ - 'name' : '', 'timing' : [ncalls, timing*unit, timing*unit*ncalls] }) - - jsondump = json.dumps(results) + statsdump = json.dumps(results) - print('statsstart' + jsondump + 'statsend') + print('statsstart{0}statsend'.format(statsdump)) sys.stdout.flush() exit()
Fix bug when profiling multiple fcts per module
## Code Before: import json stats = lp.get_stats() unit = stats.unit results = {} for function, timings in stats.timings.iteritems(): module, line, fname = function results[module] = {} for sample in timings: linenumber, ncalls, timing = sample if not results[module].get(linenumber): results[module][linenumber] = [] results[module][linenumber].append({ 'name' : '', 'timing' : [ncalls, timing*unit, timing*unit*ncalls] }) jsondump = json.dumps(results) print('statsstart' + jsondump + 'statsend') sys.stdout.flush() exit() ## Instruction: Fix bug when profiling multiple fcts per module ## Code After: import json import sys from collections import defaultdict stats = lp.get_stats() unit = stats.unit results = {} for loc, timings in stats.timings.iteritems(): module, line, fname = loc if not results.get(module): results[module] = defaultdict(list) for sample in timings: linenumber, ncalls, timing = sample results[module][linenumber].append({ 'timing' : [ncalls, timing*unit, timing*unit*ncalls] }) statsdump = json.dumps(results) print('statsstart{0}statsend'.format(statsdump)) sys.stdout.flush() exit()
2b58374504242d4019fde208296802fe4fb1c4b3
Lib/__init__.py
Lib/__init__.py
import os, sys SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0')) try: import pkg_resources # activate namespace packages (manipulates __path__) except ImportError: pass import numpy._import_tools as _ni pkgload = _ni.PackageLoader() del _ni from numpy import * del fft, ifft, info import numpy __all__.extend(filter(lambda x: x not in ['fft','ifft','info'], numpy.__all__)) del numpy from numpy.testing import ScipyTest test = ScipyTest('scipy').test __all__.append('test') from version import version as __version__ from numpy import __version__ as __numpy_version__ __all__.append('__version__') __all__.append('__numpy_version__') from __config__ import show as show_config pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
import os, sys SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0')) try: import pkg_resources # activate namespace packages (manipulates __path__) except ImportError: pass import numpy._import_tools as _ni pkgload = _ni.PackageLoader() del _ni from numpy.testing import ScipyTest test = ScipyTest('scipy').test __all__.append('test') from version import version as __version__ from numpy import __version__ as __numpy_version__ __all__.append('__version__') __all__.append('__numpy_version__') from __config__ import show as show_config pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
Remove auto include of numpy namespace.
Remove auto include of numpy namespace. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@1522 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,scipy/scipy-svn,scipy/scipy-svn,jasonmccampbell/scipy-refactor
import os, sys SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0')) try: import pkg_resources # activate namespace packages (manipulates __path__) except ImportError: pass import numpy._import_tools as _ni pkgload = _ni.PackageLoader() del _ni - from numpy import * - del fft, ifft, info - import numpy - __all__.extend(filter(lambda x: x not in ['fft','ifft','info'], numpy.__all__)) - del numpy - from numpy.testing import ScipyTest test = ScipyTest('scipy').test __all__.append('test') from version import version as __version__ from numpy import __version__ as __numpy_version__ __all__.append('__version__') __all__.append('__numpy_version__') from __config__ import show as show_config pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
Remove auto include of numpy namespace.
## Code Before: import os, sys SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0')) try: import pkg_resources # activate namespace packages (manipulates __path__) except ImportError: pass import numpy._import_tools as _ni pkgload = _ni.PackageLoader() del _ni from numpy import * del fft, ifft, info import numpy __all__.extend(filter(lambda x: x not in ['fft','ifft','info'], numpy.__all__)) del numpy from numpy.testing import ScipyTest test = ScipyTest('scipy').test __all__.append('test') from version import version as __version__ from numpy import __version__ as __numpy_version__ __all__.append('__version__') __all__.append('__numpy_version__') from __config__ import show as show_config pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True) ## Instruction: Remove auto include of numpy namespace. ## Code After: import os, sys SCIPY_IMPORT_VERBOSE = int(os.environ.get('SCIPY_IMPORT_VERBOSE','0')) try: import pkg_resources # activate namespace packages (manipulates __path__) except ImportError: pass import numpy._import_tools as _ni pkgload = _ni.PackageLoader() del _ni from numpy.testing import ScipyTest test = ScipyTest('scipy').test __all__.append('test') from version import version as __version__ from numpy import __version__ as __numpy_version__ __all__.append('__version__') __all__.append('__numpy_version__') from __config__ import show as show_config pkgload(verbose=SCIPY_IMPORT_VERBOSE,postpone=True)
e9c4881ee29ba104caf9fc8330583c254fe52c06
scripts/examples/Arduino/Portenta-H7/19-Low-Power/deep_sleep.py
scripts/examples/Arduino/Portenta-H7/19-Low-Power/deep_sleep.py
import pyb, machine, sensor # Create and init RTC object. rtc = pyb.RTC() # (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0)) # Print RTC info. print(rtc.datetime()) sensor.reset() # Enable sensor softsleep sensor.sleep(True) # Optionally bypass the regulator on OV7725 # for the lowest possible power consumption. if (sensor.get_id() == sensor.OV7725): # Bypass internal regulator sensor.__write_reg(0x4F, 0x18) # Shutdown the sensor (pulls PWDN high). sensor.shutdown(True) # Enable RTC interrupts every 30 seconds. # Note the camera will RESET after wakeup from Deepsleep Mode. rtc.wakeup(30000) # Enter Deepsleep Mode. machine.deepsleep()
import pyb, machine, sensor # Create and init RTC object. rtc = pyb.RTC() # (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0)) # Print RTC info. print(rtc.datetime()) sensor.reset() # Shutdown the sensor (pulls PWDN high). sensor.shutdown(True) # Enable RTC interrupts every 30 seconds. # Note the camera will RESET after wakeup from Deepsleep Mode. rtc.wakeup(30000) # Enter Deepsleep Mode. machine.deepsleep()
Remove sensor setting from deep sleep example
Remove sensor setting from deep sleep example
Python
mit
iabdalkader/openmv,openmv/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv,kwagyeman/openmv,openmv/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,kwagyeman/openmv,openmv/openmv
import pyb, machine, sensor # Create and init RTC object. rtc = pyb.RTC() # (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0)) # Print RTC info. print(rtc.datetime()) sensor.reset() - # Enable sensor softsleep - sensor.sleep(True) - - # Optionally bypass the regulator on OV7725 - # for the lowest possible power consumption. - if (sensor.get_id() == sensor.OV7725): - # Bypass internal regulator - sensor.__write_reg(0x4F, 0x18) - # Shutdown the sensor (pulls PWDN high). sensor.shutdown(True) # Enable RTC interrupts every 30 seconds. # Note the camera will RESET after wakeup from Deepsleep Mode. rtc.wakeup(30000) # Enter Deepsleep Mode. machine.deepsleep()
Remove sensor setting from deep sleep example
## Code Before: import pyb, machine, sensor # Create and init RTC object. rtc = pyb.RTC() # (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0)) # Print RTC info. print(rtc.datetime()) sensor.reset() # Enable sensor softsleep sensor.sleep(True) # Optionally bypass the regulator on OV7725 # for the lowest possible power consumption. if (sensor.get_id() == sensor.OV7725): # Bypass internal regulator sensor.__write_reg(0x4F, 0x18) # Shutdown the sensor (pulls PWDN high). sensor.shutdown(True) # Enable RTC interrupts every 30 seconds. # Note the camera will RESET after wakeup from Deepsleep Mode. rtc.wakeup(30000) # Enter Deepsleep Mode. machine.deepsleep() ## Instruction: Remove sensor setting from deep sleep example ## Code After: import pyb, machine, sensor # Create and init RTC object. rtc = pyb.RTC() # (year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) rtc.datetime((2014, 5, 1, 4, 13, 0, 0, 0)) # Print RTC info. print(rtc.datetime()) sensor.reset() # Shutdown the sensor (pulls PWDN high). sensor.shutdown(True) # Enable RTC interrupts every 30 seconds. # Note the camera will RESET after wakeup from Deepsleep Mode. rtc.wakeup(30000) # Enter Deepsleep Mode. machine.deepsleep()
ae8273f86fc3cc7fdacadf495aa148dda796f11b
printcli.py
printcli.py
import argparse import os from labelprinter import Labelprinter if os.path.isfile('labelprinterServeConf_local.py'): import labelprinterServeConf_local as conf else: import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
import argparse import os from labelprinter import Labelprinter import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
Make the CLI use the new config (see e4054fb).
Make the CLI use the new config (see e4054fb).
Python
mit
chaosdorf/labello,chaosdorf/labello,chaosdorf/labello
import argparse import os from labelprinter import Labelprinter - - if os.path.isfile('labelprinterServeConf_local.py'): - import labelprinterServeConf_local as conf - else: - import labelprinterServeConf as conf + import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
Make the CLI use the new config (see e4054fb).
## Code Before: import argparse import os from labelprinter import Labelprinter if os.path.isfile('labelprinterServeConf_local.py'): import labelprinterServeConf_local as conf else: import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter) ## Instruction: Make the CLI use the new config (see e4054fb). ## Code After: import argparse import os from labelprinter import Labelprinter import labelprinterServeConf as conf def text(args, labelprinter): bold = 'on' if args.bold else 'off' labelprinter.printText(args.text, charSize=args.char_size, font=args.font, align=args.align, bold=bold, charStyle=args.char_style, cut=args.cut ) parser = argparse.ArgumentParser(description="A command line interface to Labello.") subparsers = parser.add_subparsers(help="commands") parser_text = subparsers.add_parser("text", help="print a text") parser_text.add_argument("text", type=str, help="the text to print") parser_text.add_argument("--char_size", type=str, default='42') parser_text.add_argument("--font", type=str, default='lettergothic') parser_text.add_argument("--align", type=str, default='left') parser_text.add_argument("--bold", action='store_true') parser_text.add_argument("--char_style", type=str, default='normal') parser_text.add_argument("--cut", type=str, default='full') parser_text.set_defaults(func=text) args = parser.parse_args() labelprinter = Labelprinter(conf=conf) args.func(args, labelprinter)
68e6321113c249508dad89688e58860ef5728d64
microscopes/lda/runner.py
microscopes/lda/runner.py
from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import lda_sample_dispersion class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) lda_sample_dispersion(self._latent, r)
from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import sample_gamma, sample_alpha class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) sample_gamma(self._latent, r, 5, 0.1) sample_alpha(self._latent, r, 5, 0.1)
Use C++ implementations of hp sampling
Use C++ implementations of hp sampling
Python
bsd-3-clause
datamicroscopes/lda,datamicroscopes/lda,datamicroscopes/lda
from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs - from microscopes.lda.kernels import lda_sample_dispersion + from microscopes.lda.kernels import sample_gamma, sample_alpha class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) - lda_sample_dispersion(self._latent, r) + sample_gamma(self._latent, r, 5, 0.1) + sample_alpha(self._latent, r, 5, 0.1)
Use C++ implementations of hp sampling
## Code Before: from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import lda_sample_dispersion class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) lda_sample_dispersion(self._latent, r) ## Instruction: Use C++ implementations of hp sampling ## Code After: from microscopes.common import validator from microscopes.common.rng import rng from microscopes.lda.kernels import lda_crp_gibbs from microscopes.lda.kernels import sample_gamma, sample_alpha class runner(object): """The LDA runner Parameters ---------- defn : ``model_definition``: The structural definition. view : A list of list of serializable objects (the 'documents') latent : ``state``: The initialization state. """ def __init__(self, defn, view, latent, kernel_config='assign'): self._defn = defn self._view = view self._latent = latent def run(self, r, niters=10000): """Run the lda kernel for `niters`, in a single thread. Parameters ---------- r : random state niters : int """ validator.validate_type(r, rng, param_name='r') validator.validate_positive(niters, param_name='niters') for _ in xrange(niters): lda_crp_gibbs(self._latent, r) sample_gamma(self._latent, r, 5, 0.1) sample_alpha(self._latent, r, 5, 0.1)
a32e61e9cdf2eababb568659766688a731b121cb
warlock/__init__.py
warlock/__init__.py
"""Public-facing Warlock API""" from warlock.core import model_factory # NOQA from warlock.exceptions import InvalidOperation # NOQA
"""Public-facing Warlock API""" from warlock.core import model_factory # noqa: F401 from warlock.exceptions import InvalidOperation # noqa: F401
Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook
Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook
Python
apache-2.0
bcwaldon/warlock
"""Public-facing Warlock API""" - from warlock.core import model_factory # NOQA + from warlock.core import model_factory # noqa: F401 - from warlock.exceptions import InvalidOperation # NOQA + from warlock.exceptions import InvalidOperation # noqa: F401
Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook
## Code Before: """Public-facing Warlock API""" from warlock.core import model_factory # NOQA from warlock.exceptions import InvalidOperation # NOQA ## Instruction: Apply 'no blanket NOQA statements' fixes enforced by pre-commit hook ## Code After: """Public-facing Warlock API""" from warlock.core import model_factory # noqa: F401 from warlock.exceptions import InvalidOperation # noqa: F401
3dae7f461d34efceb2e8b0194306d85236fea1fc
src/main/python/piglatin.py
src/main/python/piglatin.py
import sys def parseCommandLine(argv): print 'Inside parser' return argv[1] if len(argv) > 1 else "" if __name__ == "__main__": latin = parseCommandLine(sys.argv) print(latin) print("igpay atinlay")
import sys def parseCommandLine(argv): return argv[1] if len(argv) > 1 else "" if __name__ == "__main__": latin = parseCommandLine(sys.argv) print(latin) print("igpay atinlay")
Test case failing for python3 removed
Test case failing for python3 removed
Python
mit
oneyoke/sw_asgmt_2
import sys def parseCommandLine(argv): - print 'Inside parser' return argv[1] if len(argv) > 1 else "" if __name__ == "__main__": latin = parseCommandLine(sys.argv) print(latin) print("igpay atinlay")
Test case failing for python3 removed
## Code Before: import sys def parseCommandLine(argv): print 'Inside parser' return argv[1] if len(argv) > 1 else "" if __name__ == "__main__": latin = parseCommandLine(sys.argv) print(latin) print("igpay atinlay") ## Instruction: Test case failing for python3 removed ## Code After: import sys def parseCommandLine(argv): return argv[1] if len(argv) > 1 else "" if __name__ == "__main__": latin = parseCommandLine(sys.argv) print(latin) print("igpay atinlay")
cdbe3f5ed5e65a14c1f40cc5daa84a9103e4322d
tests/test_boto_store.py
tests/test_boto_store.py
import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentials, ids=[c['access_key'] for c in boto_credentials]) def credentials(request): return request.param @pytest.yield_fixture() def bucket(credentials): with boto_bucket(**credentials) as bucket: yield bucket class TestBotoStorage(BasicStore, UrlStore): @pytest.fixture(params=['', '/test-prefix']) def prefix(self, request): return request.param @pytest.fixture def store(self, bucket, prefix): return BotoStore(bucket, prefix) def test_get_filename_nonexistant(self, store): # NOTE: boto misbehaves here and tries to erase the target file # the parent tests use /dev/null, which you really should not try # to os.remove! with TempDir() as tmpdir: with pytest.raises(KeyError): store.get_file('nonexistantkey', os.path.join(tmpdir, 'a'))
import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentials, ids=[c['access_key'] for c in boto_credentials]) def credentials(request): return request.param @pytest.yield_fixture() def bucket(credentials): with boto_bucket(**credentials) as bucket: yield bucket class TestBotoStorage(BasicStore, UrlStore): @pytest.fixture(params=['', '/test-prefix']) def prefix(self, request): return request.param @pytest.fixture def store(self, bucket, prefix): return BotoStore(bucket, prefix) def test_get_filename_nonexistant(self, store, key): # NOTE: boto misbehaves here and tries to erase the target file # the parent tests use /dev/null, which you really should not try # to os.remove! with TempDir() as tmpdir: with pytest.raises(KeyError): store.get_file(key, os.path.join(tmpdir, 'a'))
Use key fixture in boto tests.
Use key fixture in boto tests.
Python
mit
fmarczin/simplekv,fmarczin/simplekv,karteek/simplekv,mbr/simplekv,karteek/simplekv,mbr/simplekv
import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentials, ids=[c['access_key'] for c in boto_credentials]) def credentials(request): return request.param @pytest.yield_fixture() def bucket(credentials): with boto_bucket(**credentials) as bucket: yield bucket class TestBotoStorage(BasicStore, UrlStore): @pytest.fixture(params=['', '/test-prefix']) def prefix(self, request): return request.param @pytest.fixture def store(self, bucket, prefix): return BotoStore(bucket, prefix) - def test_get_filename_nonexistant(self, store): + def test_get_filename_nonexistant(self, store, key): # NOTE: boto misbehaves here and tries to erase the target file # the parent tests use /dev/null, which you really should not try # to os.remove! with TempDir() as tmpdir: with pytest.raises(KeyError): - store.get_file('nonexistantkey', os.path.join(tmpdir, 'a')) + store.get_file(key, os.path.join(tmpdir, 'a'))
Use key fixture in boto tests.
## Code Before: import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentials, ids=[c['access_key'] for c in boto_credentials]) def credentials(request): return request.param @pytest.yield_fixture() def bucket(credentials): with boto_bucket(**credentials) as bucket: yield bucket class TestBotoStorage(BasicStore, UrlStore): @pytest.fixture(params=['', '/test-prefix']) def prefix(self, request): return request.param @pytest.fixture def store(self, bucket, prefix): return BotoStore(bucket, prefix) def test_get_filename_nonexistant(self, store): # NOTE: boto misbehaves here and tries to erase the target file # the parent tests use /dev/null, which you really should not try # to os.remove! with TempDir() as tmpdir: with pytest.raises(KeyError): store.get_file('nonexistantkey', os.path.join(tmpdir, 'a')) ## Instruction: Use key fixture in boto tests. ## Code After: import os from tempdir import TempDir import pytest boto = pytest.importorskip('boto') from simplekv.net.botostore import BotoStore from basic_store import BasicStore from url_store import UrlStore from bucket_manager import boto_credentials, boto_bucket @pytest.fixture(params=boto_credentials, ids=[c['access_key'] for c in boto_credentials]) def credentials(request): return request.param @pytest.yield_fixture() def bucket(credentials): with boto_bucket(**credentials) as bucket: yield bucket class TestBotoStorage(BasicStore, UrlStore): @pytest.fixture(params=['', '/test-prefix']) def prefix(self, request): return request.param @pytest.fixture def store(self, bucket, prefix): return BotoStore(bucket, prefix) def test_get_filename_nonexistant(self, store, key): # NOTE: boto misbehaves here and tries to erase the target file # the parent tests use /dev/null, which you really should not try # to os.remove! with TempDir() as tmpdir: with pytest.raises(KeyError): store.get_file(key, os.path.join(tmpdir, 'a'))
d65f39d85e98be8651863bcf617fb218e266d0bb
mpfmc/uix/relative_animation.py
mpfmc/uix/relative_animation.py
from kivy.animation import Animation class RelativeAnimation(Animation): """Class that extends the Kivy Animation base class to add relative animation property target values that are calculated when the animation starts.""" def _initialize(self, widget): """Initializes the animation and calculates the property target value based on the current value plus the desired delta. Notes: Do not call the base class _initialize method as this override completely replaces the base class method.""" d = self._widgets[widget.uid] = { 'widget': widget, 'properties': {}, 'time': None} # get current values and calculate target values p = d['properties'] for key, value in self._animated_properties.items(): original_value = getattr(widget, key) if isinstance(original_value, (tuple, list)): original_value = original_value[:] target_value = map(lambda x, y: x + y, original_value, value) elif isinstance(original_value, dict): original_value = original_value.copy() target_value = value else: target_value = original_value + value p[key] = (original_value, target_value) # install clock self._clock_install()
from kivy.animation import Animation class RelativeAnimation(Animation): """Class that extends the Kivy Animation base class to add relative animation property target values that are calculated when the animation starts.""" def _initialize(self, widget): """Initializes the animation and calculates the property target value based on the current value plus the desired delta. Notes: Do not call the base class _initialize method as this override completely replaces the base class method.""" d = self._widgets[widget.uid] = { 'widget': widget, 'properties': {}, 'time': None} # get current values and calculate target values p = d['properties'] for key, value in self._animated_properties.items(): original_value = getattr(widget, key) if isinstance(original_value, (tuple, list)): original_value = original_value[:] target_value = [x + y for x, y in zip(original_value, value)] elif isinstance(original_value, dict): original_value = original_value.copy() target_value = value else: target_value = original_value + value p[key] = (original_value, target_value) # install clock self._clock_install()
Fix relative animation of list values
Fix relative animation of list values
Python
mit
missionpinball/mpf-mc,missionpinball/mpf-mc,missionpinball/mpf-mc
from kivy.animation import Animation class RelativeAnimation(Animation): """Class that extends the Kivy Animation base class to add relative animation property target values that are calculated when the animation starts.""" def _initialize(self, widget): """Initializes the animation and calculates the property target value based on the current value plus the desired delta. Notes: Do not call the base class _initialize method as this override completely replaces the base class method.""" d = self._widgets[widget.uid] = { 'widget': widget, 'properties': {}, 'time': None} # get current values and calculate target values p = d['properties'] for key, value in self._animated_properties.items(): original_value = getattr(widget, key) if isinstance(original_value, (tuple, list)): original_value = original_value[:] - target_value = map(lambda x, y: x + y, original_value, value) + target_value = [x + y for x, y in zip(original_value, value)] elif isinstance(original_value, dict): original_value = original_value.copy() target_value = value else: target_value = original_value + value p[key] = (original_value, target_value) # install clock self._clock_install()
Fix relative animation of list values
## Code Before: from kivy.animation import Animation class RelativeAnimation(Animation): """Class that extends the Kivy Animation base class to add relative animation property target values that are calculated when the animation starts.""" def _initialize(self, widget): """Initializes the animation and calculates the property target value based on the current value plus the desired delta. Notes: Do not call the base class _initialize method as this override completely replaces the base class method.""" d = self._widgets[widget.uid] = { 'widget': widget, 'properties': {}, 'time': None} # get current values and calculate target values p = d['properties'] for key, value in self._animated_properties.items(): original_value = getattr(widget, key) if isinstance(original_value, (tuple, list)): original_value = original_value[:] target_value = map(lambda x, y: x + y, original_value, value) elif isinstance(original_value, dict): original_value = original_value.copy() target_value = value else: target_value = original_value + value p[key] = (original_value, target_value) # install clock self._clock_install() ## Instruction: Fix relative animation of list values ## Code After: from kivy.animation import Animation class RelativeAnimation(Animation): """Class that extends the Kivy Animation base class to add relative animation property target values that are calculated when the animation starts.""" def _initialize(self, widget): """Initializes the animation and calculates the property target value based on the current value plus the desired delta. Notes: Do not call the base class _initialize method as this override completely replaces the base class method.""" d = self._widgets[widget.uid] = { 'widget': widget, 'properties': {}, 'time': None} # get current values and calculate target values p = d['properties'] for key, value in self._animated_properties.items(): original_value = getattr(widget, key) if isinstance(original_value, (tuple, list)): original_value = original_value[:] target_value = [x + y for x, y in zip(original_value, value)] elif isinstance(original_value, dict): original_value = original_value.copy() target_value = value else: target_value = original_value + value p[key] = (original_value, target_value) # install clock self._clock_install()
12585ce38fc3ec7a0ddcf448cc398f694c7e29fb
dakis/api/views.py
dakis/api/views.py
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author',) def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author', 'details') def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
Exclude details field from editable through API
Exclude details field from editable through API
Python
agpl-3.0
niekas/dakis,niekas/dakis,niekas/dakis
from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment - exclude = ('author',) + exclude = ('author', 'details') def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
Exclude details field from editable through API
## Code Before: from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author',) def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer ## Instruction: Exclude details field from editable through API ## Code After: from rest_framework import serializers, viewsets from rest_framework import filters from django.contrib.auth.models import User from dakis.core.models import Experiment, Task class ExperimentSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Experiment exclude = ('author', 'details') def create(self, data): user = self.context['request'].user if user.is_authenticated(): data['author'] = user return super(ExperimentSerializer, self).create(data) class TaskSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(label='ID', read_only=True) class Meta: model = Task class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'username', 'email') class ExperimentViewSet(viewsets.ModelViewSet): queryset = Experiment.objects.all() serializer_class = ExperimentSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer filter_fields = ('experiment', 'func_cls', 'func_id', 'status') filter_backends = (filters.DjangoFilterBackend,) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer
cfb50f4ff62770c397634897e09497b74b396067
notifications/level_starting.py
notifications/level_starting.py
from consts.notification_type import NotificationType from notifications.base_notification import BaseNotification class CompLevelStartingNotification(BaseNotification): def __init__(self, match, event): self.match = match self.event = event def _build_dict(self): data = {} data['message_type'] = NotificationType.type_names[NotificationType.LEVEL_STARTING] data['message_data'] = {} data['message_data']['event_name'] = self.event.name data['message_data']['comp_level'] = self.match.comp_level data['message_data']['scheduled_time'] = self.match.time return data
from consts.notification_type import NotificationType from notifications.base_notification import BaseNotification class CompLevelStartingNotification(BaseNotification): def __init__(self, match, event): self.match = match self.event = event def _build_dict(self): data = {} data['message_type'] = NotificationType.type_names[NotificationType.LEVEL_STARTING] data['message_data'] = {} data['message_data']['event_name'] = self.event.name data['message_data']['event_key'] = self.event.key_name data['message_data']['comp_level'] = self.match.comp_level data['message_data']['scheduled_time'] = self.match.time return data
Add event key to comp level starting notification
Add event key to comp level starting notification
Python
mit
josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,bvisness/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,bdaroz/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,josephbisch/the-blue-alliance,1fish2/the-blue-alliance,1fish2/the-blue-alliance,tsteward/the-blue-alliance,verycumbersome/the-blue-alliance,1fish2/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,bvisness/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,1fish2/the-blue-alliance,1fish2/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,1fish2/the-blue-alliance,the-blue-alliance/the-blue-alliance,synth3tk/the-blue-alliance,bvisness/the-blue-alliance,fangeugene/the-blue-alliance
from consts.notification_type import NotificationType from notifications.base_notification import BaseNotification class CompLevelStartingNotification(BaseNotification): def __init__(self, match, event): self.match = match self.event = event def _build_dict(self): data = {} data['message_type'] = NotificationType.type_names[NotificationType.LEVEL_STARTING] data['message_data'] = {} data['message_data']['event_name'] = self.event.name + data['message_data']['event_key'] = self.event.key_name data['message_data']['comp_level'] = self.match.comp_level data['message_data']['scheduled_time'] = self.match.time return data
Add event key to comp level starting notification
## Code Before: from consts.notification_type import NotificationType from notifications.base_notification import BaseNotification class CompLevelStartingNotification(BaseNotification): def __init__(self, match, event): self.match = match self.event = event def _build_dict(self): data = {} data['message_type'] = NotificationType.type_names[NotificationType.LEVEL_STARTING] data['message_data'] = {} data['message_data']['event_name'] = self.event.name data['message_data']['comp_level'] = self.match.comp_level data['message_data']['scheduled_time'] = self.match.time return data ## Instruction: Add event key to comp level starting notification ## Code After: from consts.notification_type import NotificationType from notifications.base_notification import BaseNotification class CompLevelStartingNotification(BaseNotification): def __init__(self, match, event): self.match = match self.event = event def _build_dict(self): data = {} data['message_type'] = NotificationType.type_names[NotificationType.LEVEL_STARTING] data['message_data'] = {} data['message_data']['event_name'] = self.event.name data['message_data']['event_key'] = self.event.key_name data['message_data']['comp_level'] = self.match.comp_level data['message_data']['scheduled_time'] = self.match.time return data