commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
3.52k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
fuzzy_diff
stringlengths
17
3.24k
99884ec3e960fa7b73e10a6969c455de6eca542b
src/ggrc_workflows/migrations/versions/20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py
src/ggrc_workflows/migrations/versions/20140715214934_26d9c9c91542_add_cycletaskgroupobject_object.py
# revision identifiers, used by Alembic. revision = '26d9c9c91542' down_revision = '19a67dc67c3' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False)) op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False)) def downgrade(): op.drop_column('cycle_task_group_objects', 'object_type') op.drop_column('cycle_task_group_objects', 'object_id')
# revision identifiers, used by Alembic. revision = '26d9c9c91542' down_revision = '19a67dc67c3' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False)) op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False)) op.execute(''' UPDATE cycle_task_group_objects JOIN task_group_objects ON cycle_task_group_objects.task_group_object_id = task_group_objects.id SET cycle_task_group_objects.object_id = task_group_objects.object_id, cycle_task_group_objects.object_type = task_group_objects.object_type; ''') def downgrade(): op.drop_column('cycle_task_group_objects', 'object_type') op.drop_column('cycle_task_group_objects', 'object_id')
Update migration to fix existing CycleTaskGroupObjects
Update migration to fix existing CycleTaskGroupObjects
Python
apache-2.0
NejcZupec/ggrc-core,hasanalom/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,vladan-m/ggrc-core,plamut/ggrc-core,uskudnik/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,vladan-m/ggrc-core,hyperNURb/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,vladan-m/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,prasannav7/ggrc-core,uskudnik/ggrc-core,vladan-m/ggrc-core,uskudnik/ggrc-core,jmakov/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,kr41/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,vladan-m/ggrc-core,kr41/ggrc-core,hyperNURb/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,uskudnik/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,josthkko/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,uskudnik/ggrc-core
# revision identifiers, used by Alembic. revision = '26d9c9c91542' down_revision = '19a67dc67c3' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False)) op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False)) + op.execute(''' + UPDATE cycle_task_group_objects + JOIN task_group_objects + ON cycle_task_group_objects.task_group_object_id = task_group_objects.id + SET + cycle_task_group_objects.object_id = task_group_objects.object_id, + cycle_task_group_objects.object_type = task_group_objects.object_type; + ''') + def downgrade(): op.drop_column('cycle_task_group_objects', 'object_type') op.drop_column('cycle_task_group_objects', 'object_id')
Update migration to fix existing CycleTaskGroupObjects
## Code Before: # revision identifiers, used by Alembic. revision = '26d9c9c91542' down_revision = '19a67dc67c3' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False)) op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False)) def downgrade(): op.drop_column('cycle_task_group_objects', 'object_type') op.drop_column('cycle_task_group_objects', 'object_id') ## Instruction: Update migration to fix existing CycleTaskGroupObjects ## Code After: # revision identifiers, used by Alembic. revision = '26d9c9c91542' down_revision = '19a67dc67c3' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('cycle_task_group_objects', sa.Column('object_id', sa.Integer(), nullable=False)) op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False)) op.execute(''' UPDATE cycle_task_group_objects JOIN task_group_objects ON cycle_task_group_objects.task_group_object_id = task_group_objects.id SET cycle_task_group_objects.object_id = task_group_objects.object_id, cycle_task_group_objects.object_type = task_group_objects.object_type; ''') def downgrade(): op.drop_column('cycle_task_group_objects', 'object_type') op.drop_column('cycle_task_group_objects', 'object_id')
# ... existing code ... op.add_column('cycle_task_group_objects', sa.Column('object_type', sa.String(length=250), nullable=False)) op.execute(''' UPDATE cycle_task_group_objects JOIN task_group_objects ON cycle_task_group_objects.task_group_object_id = task_group_objects.id SET cycle_task_group_objects.object_id = task_group_objects.object_id, cycle_task_group_objects.object_type = task_group_objects.object_type; ''') def downgrade(): # ... rest of the code ...
a6e6c32fc8455303c44cebdfa7507300d298aa24
mediacrush/mcmanage/files.py
mediacrush/mcmanage/files.py
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
Add support for ./hash to mcmanage
Add support for ./hash to mcmanage
Python
mit
roderickm/MediaCrush,roderickm/MediaCrush,nerdzeu/NERDZCrush,roderickm/MediaCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush,MediaCrush/MediaCrush,nerdzeu/NERDZCrush
from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] + if hash.startswith("./"): + hash = hash[2:] f = File.from_hash(hash) if not f: - print("%r is not a valid file." % arguments["<hash>"]) + print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
Add support for ./hash to mcmanage
## Code Before: from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] f = File.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.") ## Instruction: Add support for ./hash to mcmanage ## Code After: from ..objects import File, Album, Feedback, RedisObject, FailedFile from ..files import delete_file def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) print("Done, thank you.") def files_nsfw(arguments): hash = arguments['<hash>'] klass = RedisObject.klass(hash) f = File.from_hash(hash) o = klass.from_hash(hash) if not f: print("%r is not a valid file." % arguments["<hash>"]) return setattr(o.flags, 'nsfw', True) o.save() print("Done, thank you.")
# ... existing code ... def files_delete(arguments): hash = arguments['<hash>'] if hash.startswith("./"): hash = hash[2:] f = File.from_hash(hash) if not f: print("%r is not a valid file." % hash) return delete_file(f) # ... rest of the code ...
86a8034101c27ffd9daf15b6cd884c6b511feecc
python/protein-translation/protein_translation.py
python/protein-translation/protein_translation.py
CODON_TO_PROTEIN = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": "STOP", "UAG": "STOP", "UGA": "STOP" } def proteins(strand): return [CODON_TO_PROTEIN[strand]]
CODON_TO_PROTEIN = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": "STOP", "UAG": "STOP", "UGA": "STOP" } def proteins(strand): return [CODON_TO_PROTEIN[strand]]
Fix mapping for codon keys for Tyrosine
Fix mapping for codon keys for Tyrosine
Python
mit
rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism
CODON_TO_PROTEIN = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", + "UAU": "Tyrosine", + "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": "STOP", "UAG": "STOP", "UGA": "STOP" } def proteins(strand): return [CODON_TO_PROTEIN[strand]]
Fix mapping for codon keys for Tyrosine
## Code Before: CODON_TO_PROTEIN = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": "STOP", "UAG": "STOP", "UGA": "STOP" } def proteins(strand): return [CODON_TO_PROTEIN[strand]] ## Instruction: Fix mapping for codon keys for Tyrosine ## Code After: CODON_TO_PROTEIN = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCC": "Serine", "UCA": "Serine", "UCG": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": "STOP", "UAG": "STOP", "UGA": "STOP" } def proteins(strand): return [CODON_TO_PROTEIN[strand]]
... "UCA": "Serine", "UCG": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", ...
dd8c4843b7872023e276247a4d8de052b42fa9a6
token_stream.py
token_stream.py
class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator(self, char): return char in '+*' def read_while(self, predicate_func): _str = "" while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()): _str += self.input_stream.next() return _str def read_number(self): number = self.read_while(self.is_digit) return {'type': 'num', 'value': int(number)} def read_operator(self): operator = self.read_while(self.is_operator) return {'type': 'op', 'value': operator} def read_next(self): _ = self.read_while(self.is_whitespace) if self.input_stream.is_eof(): return None char = self.input_stream.peek() if self.is_digit(char): return self.read_number() if self.is_operator(char): return self.read_operator() self.input_stream.croak("Can't handle character: " + char) self.input_stream.next() return None
operators = { '+': {'prec': 10, 'assoc': 'left'}, '*': {'prec': 20, 'assoc': 'left'} } class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator(self, char): return char in operators def read_while(self, predicate_func): _str = "" while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()): _str += self.input_stream.next() return _str def read_number(self): number = self.read_while(self.is_digit) return {'type': 'num', 'value': int(number)} def read_operator(self): operator = self.read_while(self.is_operator) return {'type': 'op', 'value': operator} def read_next(self): _ = self.read_while(self.is_whitespace) if self.input_stream.is_eof(): return None char = self.input_stream.peek() if self.is_digit(char): return self.read_number() if self.is_operator(char): return self.read_operator() self.input_stream.croak("Can't handle character: " + char) self.input_stream.next() return None
Define precedence and associativity for operators
Define precedence and associativity for operators
Python
mit
babu-thomas/calculator-parser
+ operators = { + '+': {'prec': 10, 'assoc': 'left'}, + '*': {'prec': 20, 'assoc': 'left'} + } + class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator(self, char): - return char in '+*' + return char in operators def read_while(self, predicate_func): _str = "" while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()): _str += self.input_stream.next() return _str def read_number(self): number = self.read_while(self.is_digit) return {'type': 'num', 'value': int(number)} def read_operator(self): operator = self.read_while(self.is_operator) return {'type': 'op', 'value': operator} def read_next(self): _ = self.read_while(self.is_whitespace) if self.input_stream.is_eof(): return None char = self.input_stream.peek() if self.is_digit(char): return self.read_number() if self.is_operator(char): return self.read_operator() self.input_stream.croak("Can't handle character: " + char) self.input_stream.next() return None
Define precedence and associativity for operators
## Code Before: class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator(self, char): return char in '+*' def read_while(self, predicate_func): _str = "" while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()): _str += self.input_stream.next() return _str def read_number(self): number = self.read_while(self.is_digit) return {'type': 'num', 'value': int(number)} def read_operator(self): operator = self.read_while(self.is_operator) return {'type': 'op', 'value': operator} def read_next(self): _ = self.read_while(self.is_whitespace) if self.input_stream.is_eof(): return None char = self.input_stream.peek() if self.is_digit(char): return self.read_number() if self.is_operator(char): return self.read_operator() self.input_stream.croak("Can't handle character: " + char) self.input_stream.next() return None ## Instruction: Define precedence and associativity for operators ## Code After: operators = { '+': {'prec': 10, 'assoc': 'left'}, '*': {'prec': 20, 'assoc': 'left'} } class TokenStream: def __init__(self, input_stream): self.input_stream = input_stream def is_whitespace(self, char): return char in ' \t' def is_digit(self, char): return char.isdigit() def is_operator(self, char): return char in operators def read_while(self, predicate_func): _str = "" while not self.input_stream.is_eof() and predicate_func(self.input_stream.peek()): _str += self.input_stream.next() return _str def read_number(self): number = self.read_while(self.is_digit) return {'type': 'num', 'value': int(number)} def read_operator(self): operator = self.read_while(self.is_operator) return {'type': 'op', 'value': operator} def read_next(self): _ = self.read_while(self.is_whitespace) if self.input_stream.is_eof(): return None char = self.input_stream.peek() if self.is_digit(char): return self.read_number() if self.is_operator(char): return self.read_operator() self.input_stream.croak("Can't handle character: " + char) self.input_stream.next() return None
# ... existing code ... operators = { '+': {'prec': 10, 'assoc': 'left'}, '*': {'prec': 20, 'assoc': 'left'} } class TokenStream: def __init__(self, input_stream): # ... modified code ... def is_operator(self, char): return char in operators def read_while(self, predicate_func): # ... rest of the code ...
3f394b37174d97b53fdef8ce662e258c6b2aa337
src/appleseed.python/studio/__init__.py
src/appleseed.python/studio/__init__.py
import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = "PyQt4" from _appleseedstudio import *
import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"]) from _appleseedstudio import *
Add PySide to as.studio init preferred binding
Add PySide to as.studio init preferred binding
Python
mit
luisbarrancos/appleseed,est77/appleseed,appleseedhq/appleseed,pjessesco/appleseed,gospodnetic/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,dictoon/appleseed,Aakash1312/appleseed,Biart95/appleseed,Vertexwahn/appleseed,dictoon/appleseed,Biart95/appleseed,aytekaman/appleseed,pjessesco/appleseed,aytekaman/appleseed,est77/appleseed,Biart95/appleseed,pjessesco/appleseed,Biart95/appleseed,gospodnetic/appleseed,dictoon/appleseed,pjessesco/appleseed,luisbarrancos/appleseed,Vertexwahn/appleseed,dictoon/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,Biart95/appleseed,luisbarrancos/appleseed,est77/appleseed,luisbarrancos/appleseed,pjessesco/appleseed,Aakash1312/appleseed,aytekaman/appleseed,gospodnetic/appleseed,Vertexwahn/appleseed,gospodnetic/appleseed,Aakash1312/appleseed,Aakash1312/appleseed,est77/appleseed,appleseedhq/appleseed,est77/appleseed,Vertexwahn/appleseed,aytekaman/appleseed,Aakash1312/appleseed,appleseedhq/appleseed,aytekaman/appleseed,gospodnetic/appleseed,dictoon/appleseed
import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): - os.environ["QT_PREFERRED_BINDING"] = "PyQt4" + os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"]) from _appleseedstudio import *
Add PySide to as.studio init preferred binding
## Code Before: import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = "PyQt4" from _appleseedstudio import * ## Instruction: Add PySide to as.studio init preferred binding ## Code After: import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"]) from _appleseedstudio import *
# ... existing code ... # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"]) from _appleseedstudio import * # ... rest of the code ...
a7028ca3d3dea5a9f8891dfd2947b671bbe02b7e
pentai/gui/my_button.py
pentai/gui/my_button.py
from kivy.uix.button import Button import audio as a_m class MyButton(Button): def on_touch_up(self, touch, *args, **kwargs): if self.collide_point(*touch.pos): if not hasattr(self, "silent"): a_m.instance.click() super(MyButton, self).on_touch_up(touch, *args, **kwargs) def sim_press(self): self.state = "down" def sim_release(self, ignored=None): self.state = "normal" if not hasattr(self, "silent"): a_m.instance.click()
from kivy.uix.button import Button import audio as a_m from pentai.base.defines import * class MyButton(Button): def __init__(self, *args, **kwargs): super(MyButton, self).__init__(*args, **kwargs) self.silent = False def on_touch_up(self, touch, *args, **kwargs): if self.collide_point(*touch.pos): if not self.silent: a_m.instance.click() super(MyButton, self).on_touch_up(touch, *args, **kwargs) def sim_press(self): self.state = "down" def sim_release(self, ignored=None): self.state = "normal" if not self.silent: a_m.instance.click()
Make "silent" an attribute from __init__
Make "silent" an attribute from __init__
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
from kivy.uix.button import Button import audio as a_m + from pentai.base.defines import * class MyButton(Button): + def __init__(self, *args, **kwargs): + super(MyButton, self).__init__(*args, **kwargs) + self.silent = False + def on_touch_up(self, touch, *args, **kwargs): if self.collide_point(*touch.pos): - if not hasattr(self, "silent"): + if not self.silent: a_m.instance.click() super(MyButton, self).on_touch_up(touch, *args, **kwargs) def sim_press(self): self.state = "down" def sim_release(self, ignored=None): self.state = "normal" - if not hasattr(self, "silent"): + if not self.silent: a_m.instance.click()
Make "silent" an attribute from __init__
## Code Before: from kivy.uix.button import Button import audio as a_m class MyButton(Button): def on_touch_up(self, touch, *args, **kwargs): if self.collide_point(*touch.pos): if not hasattr(self, "silent"): a_m.instance.click() super(MyButton, self).on_touch_up(touch, *args, **kwargs) def sim_press(self): self.state = "down" def sim_release(self, ignored=None): self.state = "normal" if not hasattr(self, "silent"): a_m.instance.click() ## Instruction: Make "silent" an attribute from __init__ ## Code After: from kivy.uix.button import Button import audio as a_m from pentai.base.defines import * class MyButton(Button): def __init__(self, *args, **kwargs): super(MyButton, self).__init__(*args, **kwargs) self.silent = False def on_touch_up(self, touch, *args, **kwargs): if self.collide_point(*touch.pos): if not self.silent: a_m.instance.click() super(MyButton, self).on_touch_up(touch, *args, **kwargs) def sim_press(self): self.state = "down" def sim_release(self, ignored=None): self.state = "normal" if not self.silent: a_m.instance.click()
// ... existing code ... from kivy.uix.button import Button import audio as a_m from pentai.base.defines import * class MyButton(Button): def __init__(self, *args, **kwargs): super(MyButton, self).__init__(*args, **kwargs) self.silent = False def on_touch_up(self, touch, *args, **kwargs): if self.collide_point(*touch.pos): if not self.silent: a_m.instance.click() super(MyButton, self).on_touch_up(touch, *args, **kwargs) // ... modified code ... def sim_release(self, ignored=None): self.state = "normal" if not self.silent: a_m.instance.click() // ... rest of the code ...
f034f69a24cd2a4048e23c54c73badd0674eb1aa
views/base.py
views/base.py
from datetime import datetime, timedelta from flask import Blueprint, render_template from sqlalchemy import and_ from models import Event blueprint = Blueprint("base", __name__) @blueprint.route("/") def index(): upcoming = Event.query.filter_by(published=True).order_by(Event.start_time).first() return render_template("base/index.j2", upcoming=upcoming) @blueprint.route("/about") def about(): return render_template("base/about.j2") @blueprint.route("/events") def events(): eventlist = Event.query.filter(and_(Event.published is True, Event.start_time < (datetime.now() + timedelta(seconds=1)))).order_by(Event.start_time.desc()).all() return render_template("base/events.j2", events=eventlist)
from datetime import datetime, timedelta from flask import Blueprint, render_template from sqlalchemy import and_ from models import Event blueprint = Blueprint("base", __name__) @blueprint.route("/") def index(): upcoming = Event.query.filter_by(published=True).order_by(Event.start_time).first() return render_template("base/index.j2", upcoming=upcoming) @blueprint.route("/about") def about(): return render_template("base/about.j2") @blueprint.route("/events") def events(): next_event = Event.query.filter(and_(Event.published == True, Event.start_time > datetime.now())).order_by(Event.start_time).first() eventlist = Event.query.filter(and_(Event.published == True, Event.start_time < datetime.now())).order_by(Event.start_time.desc()).all() if next_event: eventlist.insert(0, next_event) return render_template("base/events.j2", events=eventlist)
Fix the events page, so that upcoming event shows up.
Fix the events page, so that upcoming event shows up.
Python
mit
saseumn/website,saseumn/website
from datetime import datetime, timedelta from flask import Blueprint, render_template from sqlalchemy import and_ from models import Event blueprint = Blueprint("base", __name__) @blueprint.route("/") def index(): upcoming = Event.query.filter_by(published=True).order_by(Event.start_time).first() return render_template("base/index.j2", upcoming=upcoming) @blueprint.route("/about") def about(): return render_template("base/about.j2") @blueprint.route("/events") def events(): + next_event = Event.query.filter(and_(Event.published == True, Event.start_time > datetime.now())).order_by(Event.start_time).first() - eventlist = Event.query.filter(and_(Event.published is True, Event.start_time < (datetime.now() + timedelta(seconds=1)))).order_by(Event.start_time.desc()).all() + eventlist = Event.query.filter(and_(Event.published == True, Event.start_time < datetime.now())).order_by(Event.start_time.desc()).all() + if next_event: + eventlist.insert(0, next_event) return render_template("base/events.j2", events=eventlist)
Fix the events page, so that upcoming event shows up.
## Code Before: from datetime import datetime, timedelta from flask import Blueprint, render_template from sqlalchemy import and_ from models import Event blueprint = Blueprint("base", __name__) @blueprint.route("/") def index(): upcoming = Event.query.filter_by(published=True).order_by(Event.start_time).first() return render_template("base/index.j2", upcoming=upcoming) @blueprint.route("/about") def about(): return render_template("base/about.j2") @blueprint.route("/events") def events(): eventlist = Event.query.filter(and_(Event.published is True, Event.start_time < (datetime.now() + timedelta(seconds=1)))).order_by(Event.start_time.desc()).all() return render_template("base/events.j2", events=eventlist) ## Instruction: Fix the events page, so that upcoming event shows up. ## Code After: from datetime import datetime, timedelta from flask import Blueprint, render_template from sqlalchemy import and_ from models import Event blueprint = Blueprint("base", __name__) @blueprint.route("/") def index(): upcoming = Event.query.filter_by(published=True).order_by(Event.start_time).first() return render_template("base/index.j2", upcoming=upcoming) @blueprint.route("/about") def about(): return render_template("base/about.j2") @blueprint.route("/events") def events(): next_event = Event.query.filter(and_(Event.published == True, Event.start_time > datetime.now())).order_by(Event.start_time).first() eventlist = Event.query.filter(and_(Event.published == True, Event.start_time < datetime.now())).order_by(Event.start_time.desc()).all() if next_event: eventlist.insert(0, next_event) return render_template("base/events.j2", events=eventlist)
// ... existing code ... @blueprint.route("/events") def events(): next_event = Event.query.filter(and_(Event.published == True, Event.start_time > datetime.now())).order_by(Event.start_time).first() eventlist = Event.query.filter(and_(Event.published == True, Event.start_time < datetime.now())).order_by(Event.start_time.desc()).all() if next_event: eventlist.insert(0, next_event) return render_template("base/events.j2", events=eventlist) // ... rest of the code ...
c7621bd5c5e48c8d45ae70836b681b715348d0ba
modules/module_oraakkeli.py
modules/module_oraakkeli.py
import urllib def command_oraakkeli(bot, user, channel, args): """Asks a question from the oracle (http://www.lintukoto.net/viihde/oraakkeli/)""" if not args: return args = urllib.quote_plus(args) answer = getUrl("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys=%s&html=0" % args).getContent() bot.say(channel, "Oraakkeli vastaa: %s" % answer)
import urllib def command_oraakkeli(bot, user, channel, args): """Asks a question from the oracle (http://www.lintukoto.net/viihde/oraakkeli/)""" if not args: return args = urllib.quote_plus(args) answer = getUrl("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys=%s&html=0" % args).getContent() answer = unicode(answer) answer = answer.encode("utf-8") bot.say(channel, "Oraakkeli vastaa: %s" % answer)
Update oracle module for UTF-8
Update oracle module for UTF-8 git-svn-id: 056f9092885898c4775d98c479d2d33d00273e45@99 dda364a1-ef19-0410-af65-756c83048fb2
Python
bsd-3-clause
EArmour/pyfibot,nigeljonez/newpyfibot,huqa/pyfibot,aapa/pyfibot,EArmour/pyfibot,rnyberg/pyfibot,rnyberg/pyfibot,lepinkainen/pyfibot,aapa/pyfibot,lepinkainen/pyfibot,huqa/pyfibot
import urllib def command_oraakkeli(bot, user, channel, args): """Asks a question from the oracle (http://www.lintukoto.net/viihde/oraakkeli/)""" if not args: return args = urllib.quote_plus(args) answer = getUrl("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys=%s&html=0" % args).getContent() + answer = unicode(answer) + answer = answer.encode("utf-8") + bot.say(channel, "Oraakkeli vastaa: %s" % answer)
Update oracle module for UTF-8
## Code Before: import urllib def command_oraakkeli(bot, user, channel, args): """Asks a question from the oracle (http://www.lintukoto.net/viihde/oraakkeli/)""" if not args: return args = urllib.quote_plus(args) answer = getUrl("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys=%s&html=0" % args).getContent() bot.say(channel, "Oraakkeli vastaa: %s" % answer) ## Instruction: Update oracle module for UTF-8 ## Code After: import urllib def command_oraakkeli(bot, user, channel, args): """Asks a question from the oracle (http://www.lintukoto.net/viihde/oraakkeli/)""" if not args: return args = urllib.quote_plus(args) answer = getUrl("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys=%s&html=0" % args).getContent() answer = unicode(answer) answer = answer.encode("utf-8") bot.say(channel, "Oraakkeli vastaa: %s" % answer)
// ... existing code ... answer = getUrl("http://www.lintukoto.net/viihde/oraakkeli/index.php?kysymys=%s&html=0" % args).getContent() answer = unicode(answer) answer = answer.encode("utf-8") bot.say(channel, "Oraakkeli vastaa: %s" % answer) // ... rest of the code ...
bd23a87d28a1d0a1f82b0fd17abfababafba0dc7
viaduct/api/page.py
viaduct/api/page.py
from flask.ext.login import current_user from viaduct.models.page import Page, PagePermission, PageRevision from viaduct import db from flask import request, url_for, render_template from viaduct.models.group import Group class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter(Page.path==path).first() if not page: return False for rev in page.revisions.all(): db.session.delete(rev) for perm in page.permissions.all(): db.session.delete(perm) db.session.commit() db.session.delete(page) db.session.commit() return True @staticmethod def get_footer(): footer = Page.query.filter(Page.path == 'footer').first() if not footer: footer = Page('footer') if footer.revisions.count() > 0: revision = footer.revisions.order_by(PageRevision.id.desc()).first() exists = True else: revision = PageRevision(footer, current_user, '', '<b> No footer found </b>' '', True) exists = False print vars(footer) return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists)
from flask.ext.login import current_user from viaduct.models.page import Page, PageRevision from viaduct import db from flask import render_template class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter(Page.path == path).first() if not page: return False for rev in page.revisions.all(): db.session.delete(rev) for perm in page.permissions.all(): db.session.delete(perm) db.session.commit() db.session.delete(page) db.session.commit() return True @staticmethod def get_footer(): footer = Page.query.filter(Page.path == 'footer').first() if not footer: footer = Page('footer') if footer.revisions.count() > 0: revision = footer.revisions.order_by(PageRevision.id.desc()).\ first() exists = True else: revision = PageRevision(footer, current_user, '', '<b> No footer found </b>' '', True) exists = False return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists)
Remove footer print and make file PEP8 compliant
Remove footer print and make file PEP8 compliant
Python
mit
viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct
from flask.ext.login import current_user - from viaduct.models.page import Page, PagePermission, PageRevision + from viaduct.models.page import Page, PageRevision from viaduct import db - from flask import request, url_for, render_template + from flask import render_template - from viaduct.models.group import Group class PageAPI: @staticmethod def remove_page(path): - page = Page.query.filter(Page.path==path).first() + page = Page.query.filter(Page.path == path).first() if not page: return False for rev in page.revisions.all(): db.session.delete(rev) for perm in page.permissions.all(): db.session.delete(perm) db.session.commit() db.session.delete(page) db.session.commit() return True @staticmethod def get_footer(): footer = Page.query.filter(Page.path == 'footer').first() if not footer: footer = Page('footer') if footer.revisions.count() > 0: - revision = footer.revisions.order_by(PageRevision.id.desc()).first() + revision = footer.revisions.order_by(PageRevision.id.desc()).\ + first() exists = True else: - revision = PageRevision(footer, current_user, + revision = PageRevision(footer, current_user, '', - '', '<b> No footer found </b>' + '<b> No footer found </b>' '', True) - '', True) exists = False - print vars(footer) + return render_template('page/get_footer.htm', footer_revision=revision, + footer=footer, exists=exists) - return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists)
Remove footer print and make file PEP8 compliant
## Code Before: from flask.ext.login import current_user from viaduct.models.page import Page, PagePermission, PageRevision from viaduct import db from flask import request, url_for, render_template from viaduct.models.group import Group class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter(Page.path==path).first() if not page: return False for rev in page.revisions.all(): db.session.delete(rev) for perm in page.permissions.all(): db.session.delete(perm) db.session.commit() db.session.delete(page) db.session.commit() return True @staticmethod def get_footer(): footer = Page.query.filter(Page.path == 'footer').first() if not footer: footer = Page('footer') if footer.revisions.count() > 0: revision = footer.revisions.order_by(PageRevision.id.desc()).first() exists = True else: revision = PageRevision(footer, current_user, '', '<b> No footer found </b>' '', True) exists = False print vars(footer) return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists) ## Instruction: Remove footer print and make file PEP8 compliant ## Code After: from flask.ext.login import current_user from viaduct.models.page import Page, PageRevision from viaduct import db from flask import render_template class PageAPI: @staticmethod def remove_page(path): page = Page.query.filter(Page.path == path).first() if not page: return False for rev in page.revisions.all(): db.session.delete(rev) for perm in page.permissions.all(): db.session.delete(perm) db.session.commit() db.session.delete(page) db.session.commit() return True @staticmethod def get_footer(): footer = Page.query.filter(Page.path == 'footer').first() if not footer: footer = Page('footer') if footer.revisions.count() > 0: revision = footer.revisions.order_by(PageRevision.id.desc()).\ first() exists = True else: revision = PageRevision(footer, current_user, '', '<b> No footer found </b>' '', True) exists = False return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists)
// ... existing code ... from flask.ext.login import current_user from viaduct.models.page import Page, PageRevision from viaduct import db from flask import render_template class PageAPI: // ... modified code ... @staticmethod def remove_page(path): page = Page.query.filter(Page.path == path).first() if not page: ... if footer.revisions.count() > 0: revision = footer.revisions.order_by(PageRevision.id.desc()).\ first() exists = True else: revision = PageRevision(footer, current_user, '', '<b> No footer found </b>' '', True) exists = False return render_template('page/get_footer.htm', footer_revision=revision, footer=footer, exists=exists) // ... rest of the code ...
f3974375e2c71c9c9bfba6fde356014a07e0b704
ee_plugin/ee_auth.py
ee_plugin/ee_auth.py
import webbrowser from qgis.PyQt.QtWidgets import QInputDialog import ee def init(): try: ee.Initialize() except ee.ee_exception.EEException: authenticate() ee.Initialize() # retry initialization once the user logs in def authenticate(): auth_url = ee.oauth.get_authorization_url() webbrowser.open_new(auth_url) print('\nEarth Engine Authentication:\n' 'If the web browser does not start automatically, ' 'please manually browse the URL below:\n"{}"'.format(auth_url)) token, ok = QInputDialog.getText(None, 'Earth Engine Authentication', 'To authorize access needed by Earth Engine, follow the\n' 'instructions and paste the token here:\n\n' '(If the web browser does not start automatically\n' 'see the python shell).') if ok and token: ee.oauth._obtain_and_write_token(token.strip())
import webbrowser from qgis.PyQt.QtWidgets import QInputDialog import ee import logging # fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client' # https://github.com/googleapis/google-api-python-client/issues/299 logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) def init(): try: ee.Initialize() except ee.ee_exception.EEException: authenticate() ee.Initialize() # retry initialization once the user logs in def authenticate(): auth_url = ee.oauth.get_authorization_url() webbrowser.open_new(auth_url) print('\nEarth Engine Authentication:\n' 'If the web browser does not start automatically, ' 'please manually browse the URL below:\n"{}"'.format(auth_url)) token, ok = QInputDialog.getText(None, 'Earth Engine Authentication', 'To authorize access needed by Earth Engine, follow the\n' 'instructions and paste the token here:\n\n' '(If the web browser does not start automatically\n' 'see the python shell).') if ok and token: ee.oauth._obtain_and_write_token(token.strip())
Fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client'
Fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client'
Python
mit
gena/qgis-earthengine-plugin,gena/qgis-earthengine-plugin
import webbrowser from qgis.PyQt.QtWidgets import QInputDialog import ee + import logging + + # fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client' + # https://github.com/googleapis/google-api-python-client/issues/299 + logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) def init(): try: ee.Initialize() except ee.ee_exception.EEException: authenticate() ee.Initialize() # retry initialization once the user logs in def authenticate(): auth_url = ee.oauth.get_authorization_url() webbrowser.open_new(auth_url) print('\nEarth Engine Authentication:\n' 'If the web browser does not start automatically, ' 'please manually browse the URL below:\n"{}"'.format(auth_url)) token, ok = QInputDialog.getText(None, 'Earth Engine Authentication', 'To authorize access needed by Earth Engine, follow the\n' 'instructions and paste the token here:\n\n' '(If the web browser does not start automatically\n' 'see the python shell).') if ok and token: ee.oauth._obtain_and_write_token(token.strip())
Fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client'
## Code Before: import webbrowser from qgis.PyQt.QtWidgets import QInputDialog import ee def init(): try: ee.Initialize() except ee.ee_exception.EEException: authenticate() ee.Initialize() # retry initialization once the user logs in def authenticate(): auth_url = ee.oauth.get_authorization_url() webbrowser.open_new(auth_url) print('\nEarth Engine Authentication:\n' 'If the web browser does not start automatically, ' 'please manually browse the URL below:\n"{}"'.format(auth_url)) token, ok = QInputDialog.getText(None, 'Earth Engine Authentication', 'To authorize access needed by Earth Engine, follow the\n' 'instructions and paste the token here:\n\n' '(If the web browser does not start automatically\n' 'see the python shell).') if ok and token: ee.oauth._obtain_and_write_token(token.strip()) ## Instruction: Fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client' ## Code After: import webbrowser from qgis.PyQt.QtWidgets import QInputDialog import ee import logging # fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client' # https://github.com/googleapis/google-api-python-client/issues/299 logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) def init(): try: ee.Initialize() except ee.ee_exception.EEException: authenticate() ee.Initialize() # retry initialization once the user logs in def authenticate(): auth_url = ee.oauth.get_authorization_url() webbrowser.open_new(auth_url) print('\nEarth Engine Authentication:\n' 'If the web browser does not start automatically, ' 'please manually browse the URL below:\n"{}"'.format(auth_url)) token, ok = QInputDialog.getText(None, 'Earth Engine Authentication', 'To authorize access needed by Earth Engine, follow the\n' 'instructions and paste the token here:\n\n' '(If the web browser does not start automatically\n' 'see the python shell).') if ok and token: ee.oauth._obtain_and_write_token(token.strip())
// ... existing code ... import ee import logging # fix the warnings/errors messages from 'file_cache is unavailable when using oauth2client' # https://github.com/googleapis/google-api-python-client/issues/299 logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR) // ... rest of the code ...
e8bcd56727199de75a0dcefe7590d3866a14f39d
django_mailbox/tests/test_mailbox.py
django_mailbox/tests/test_mailbox.py
from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, )
import os from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, ) def test_last_polling_field_exists(self): mailbox = Mailbox() self.assertTrue(hasattr(mailbox, 'last_polling')) def test_get_new_mail_update_last_polling(self): mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join( os.path.dirname(__file__), 'messages', 'generic_message.eml', )) self.assertEqual(mailbox.last_polling, None) mailbox.get_new_mail() self.assertNotEqual(mailbox.last_polling, None)
Add tests to update Mailbox.last_polling
Add tests to update Mailbox.last_polling
Python
mit
coddingtonbear/django-mailbox,ad-m/django-mailbox
+ import os + from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, ) + def test_last_polling_field_exists(self): + mailbox = Mailbox() + self.assertTrue(hasattr(mailbox, 'last_polling')) + + def test_get_new_mail_update_last_polling(self): + mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join( + os.path.dirname(__file__), + 'messages', + 'generic_message.eml', + )) + self.assertEqual(mailbox.last_polling, None) + mailbox.get_new_mail() + self.assertNotEqual(mailbox.last_polling, None) +
Add tests to update Mailbox.last_polling
## Code Before: from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, ) ## Instruction: Add tests to update Mailbox.last_polling ## Code After: import os from django.test import TestCase from django_mailbox.models import Mailbox __all__ = ['TestMailbox'] class TestMailbox(TestCase): def test_protocol_info(self): mailbox = Mailbox() mailbox.uri = 'alpha://test.com' expected_protocol = 'alpha' actual_protocol = mailbox._protocol_info.scheme self.assertEqual( expected_protocol, actual_protocol, ) def test_last_polling_field_exists(self): mailbox = Mailbox() self.assertTrue(hasattr(mailbox, 'last_polling')) def test_get_new_mail_update_last_polling(self): mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join( os.path.dirname(__file__), 'messages', 'generic_message.eml', )) self.assertEqual(mailbox.last_polling, None) mailbox.get_new_mail() self.assertNotEqual(mailbox.last_polling, None)
# ... existing code ... import os from django.test import TestCase # ... modified code ... actual_protocol, ) def test_last_polling_field_exists(self): mailbox = Mailbox() self.assertTrue(hasattr(mailbox, 'last_polling')) def test_get_new_mail_update_last_polling(self): mailbox = Mailbox.objects.create(uri="mbox://" + os.path.join( os.path.dirname(__file__), 'messages', 'generic_message.eml', )) self.assertEqual(mailbox.last_polling, None) mailbox.get_new_mail() self.assertNotEqual(mailbox.last_polling, None) # ... rest of the code ...
7c88ecf10c3197c337990c7f92c7ace6a85d316e
setup.py
setup.py
from distutils.core import setup from distutils.core import Extension setup(name = 'wrapt', version = '0.9.0', description = 'Module for decorators, wrappers and monkey patching.', author = 'Graham Dumpleton', author_email = '[email protected]', license = 'BSD', url = 'https://github.com/GrahamDumpleton/wrapt', packages = ['wrapt'], package_dir={'wrapt': 'src'}, ext_modules = [Extension("wrapt._wrappers", ["src/_wrappers.c"])], )
import os from distutils.core import setup from distutils.core import Extension with_extensions = os.environ.get('WRAPT_EXTENSIONS', 'true') with_extensions = (with_extensions.lower() != 'false') setup_kwargs = dict( name = 'wrapt', version = '0.9.0', description = 'Module for decorators, wrappers and monkey patching.', author = 'Graham Dumpleton', author_email = '[email protected]', license = 'BSD', url = 'https://github.com/GrahamDumpleton/wrapt', packages = ['wrapt'], package_dir={'wrapt': 'src'}, ) setup_extension_kwargs = dict( ext_modules = [Extension("wrapt._wrappers", ["src/_wrappers.c"])], ) if with_extensions: setup_kwargs.update(setup_extension_kwargs) setup(**setup_kwargs)
Make compilation of extensions optional through an environment variable.
Make compilation of extensions optional through an environment variable.
Python
bsd-2-clause
akash1808/wrapt,github4ry/wrapt,wujuguang/wrapt,akash1808/wrapt,wujuguang/wrapt,pombredanne/wrapt,pombredanne/wrapt,GrahamDumpleton/wrapt,pombredanne/python-lazy-object-proxy,ionelmc/python-lazy-object-proxy,linglaiyao1314/wrapt,GrahamDumpleton/wrapt,linglaiyao1314/wrapt,pombredanne/python-lazy-object-proxy,ionelmc/python-lazy-object-proxy,github4ry/wrapt
+ import os + from distutils.core import setup from distutils.core import Extension - setup(name = 'wrapt', + with_extensions = os.environ.get('WRAPT_EXTENSIONS', 'true') + with_extensions = (with_extensions.lower() != 'false') + + setup_kwargs = dict( + name = 'wrapt', version = '0.9.0', description = 'Module for decorators, wrappers and monkey patching.', author = 'Graham Dumpleton', author_email = '[email protected]', license = 'BSD', url = 'https://github.com/GrahamDumpleton/wrapt', packages = ['wrapt'], package_dir={'wrapt': 'src'}, - ext_modules = [Extension("wrapt._wrappers", ["src/_wrappers.c"])], ) + setup_extension_kwargs = dict( + ext_modules = [Extension("wrapt._wrappers", ["src/_wrappers.c"])], + ) + + if with_extensions: + setup_kwargs.update(setup_extension_kwargs) + + setup(**setup_kwargs) +
Make compilation of extensions optional through an environment variable.
## Code Before: from distutils.core import setup from distutils.core import Extension setup(name = 'wrapt', version = '0.9.0', description = 'Module for decorators, wrappers and monkey patching.', author = 'Graham Dumpleton', author_email = '[email protected]', license = 'BSD', url = 'https://github.com/GrahamDumpleton/wrapt', packages = ['wrapt'], package_dir={'wrapt': 'src'}, ext_modules = [Extension("wrapt._wrappers", ["src/_wrappers.c"])], ) ## Instruction: Make compilation of extensions optional through an environment variable. ## Code After: import os from distutils.core import setup from distutils.core import Extension with_extensions = os.environ.get('WRAPT_EXTENSIONS', 'true') with_extensions = (with_extensions.lower() != 'false') setup_kwargs = dict( name = 'wrapt', version = '0.9.0', description = 'Module for decorators, wrappers and monkey patching.', author = 'Graham Dumpleton', author_email = '[email protected]', license = 'BSD', url = 'https://github.com/GrahamDumpleton/wrapt', packages = ['wrapt'], package_dir={'wrapt': 'src'}, ) setup_extension_kwargs = dict( ext_modules = [Extension("wrapt._wrappers", ["src/_wrappers.c"])], ) if with_extensions: setup_kwargs.update(setup_extension_kwargs) setup(**setup_kwargs)
... import os from distutils.core import setup from distutils.core import Extension with_extensions = os.environ.get('WRAPT_EXTENSIONS', 'true') with_extensions = (with_extensions.lower() != 'false') setup_kwargs = dict( name = 'wrapt', version = '0.9.0', description = 'Module for decorators, wrappers and monkey patching.', ... packages = ['wrapt'], package_dir={'wrapt': 'src'}, ) setup_extension_kwargs = dict( ext_modules = [Extension("wrapt._wrappers", ["src/_wrappers.c"])], ) if with_extensions: setup_kwargs.update(setup_extension_kwargs) setup(**setup_kwargs) ...
26d2e13945f4780ff74dfe99695be7045fb9ed39
piper/prop.py
piper/prop.py
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dictionary of them """ raise NotImplementedError() @property def namespace(self): return '.'.join((self.__module__, self.__class__.__name__)) # http://stackoverflow.com/questions/6027558 def flatten(self, d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) else: items.append((new_key, v)) return dict(items) class FacterProp(PropBase): """ Collect properties from facter via facterpy It should be noted that the current version does not have any typecasting, so everything is always strings. See https://github.com/knorby/facterpy/issues/5 """ @property def properties(self): if self._props is None: facts = facter.Facter().all self._props = self.flatten(facts) return self._props
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dictionary of them """ raise NotImplementedError() @property def namespace(self): return '.'.join((self.__module__, self.__class__.__name__)) # http://stackoverflow.com/questions/6027558 def flatten(self, d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) elif isinstance(v, list): # Make lists have keys like 'foo.bar.x' for x, item in enumerate(v): key = '{2}{0}{1}'.format(sep, x, new_key) items.append((key, item)) else: items.append((new_key, v)) return dict(items) class FacterProp(PropBase): """ Collect properties from facter via facterpy It should be noted that the current version does not have any typecasting, so everything is always strings. See https://github.com/knorby/facterpy/issues/5 """ @property def properties(self): if self._props is None: facts = facter.Facter().all self._props = self.flatten(facts) return self._props
Add PropBase.flatten() support for flattening lists
Add PropBase.flatten() support for flattening lists
Python
mit
thiderman/piper
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dictionary of them """ raise NotImplementedError() @property def namespace(self): return '.'.join((self.__module__, self.__class__.__name__)) # http://stackoverflow.com/questions/6027558 def flatten(self, d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) + elif isinstance(v, list): + # Make lists have keys like 'foo.bar.x' + for x, item in enumerate(v): + key = '{2}{0}{1}'.format(sep, x, new_key) + items.append((key, item)) else: items.append((new_key, v)) return dict(items) class FacterProp(PropBase): """ Collect properties from facter via facterpy It should be noted that the current version does not have any typecasting, so everything is always strings. See https://github.com/knorby/facterpy/issues/5 """ @property def properties(self): if self._props is None: facts = facter.Facter().all self._props = self.flatten(facts) return self._props
Add PropBase.flatten() support for flattening lists
## Code Before: import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dictionary of them """ raise NotImplementedError() @property def namespace(self): return '.'.join((self.__module__, self.__class__.__name__)) # http://stackoverflow.com/questions/6027558 def flatten(self, d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) else: items.append((new_key, v)) return dict(items) class FacterProp(PropBase): """ Collect properties from facter via facterpy It should be noted that the current version does not have any typecasting, so everything is always strings. See https://github.com/knorby/facterpy/issues/5 """ @property def properties(self): if self._props is None: facts = facter.Facter().all self._props = self.flatten(facts) return self._props ## Instruction: Add PropBase.flatten() support for flattening lists ## Code After: import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dictionary of them """ raise NotImplementedError() @property def namespace(self): return '.'.join((self.__module__, self.__class__.__name__)) # http://stackoverflow.com/questions/6027558 def flatten(self, d, parent_key='', sep='.'): items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) elif isinstance(v, list): # Make lists have keys like 'foo.bar.x' for x, item in enumerate(v): key = '{2}{0}{1}'.format(sep, x, new_key) items.append((key, item)) else: items.append((new_key, v)) return dict(items) class FacterProp(PropBase): """ Collect properties from facter via facterpy It should be noted that the current version does not have any typecasting, so everything is always strings. See https://github.com/knorby/facterpy/issues/5 """ @property def properties(self): if self._props is None: facts = facter.Facter().all self._props = self.flatten(facts) return self._props
// ... existing code ... if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) elif isinstance(v, list): # Make lists have keys like 'foo.bar.x' for x, item in enumerate(v): key = '{2}{0}{1}'.format(sep, x, new_key) items.append((key, item)) else: items.append((new_key, v)) // ... rest of the code ...
fbe4761d2d679a983d2625c4969dab53500634b7
fases/rodar_fase_exemplo.py
fases/rodar_fase_exemplo.py
from __future__ import unicode_literals from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase from placa_grafica_tkinter import rodar_fase if __name__=='__main__': fase = Fase(intervalo_de_colisao=10) # Adicionar Pássaros Vermelhos for i in range(5): fase.adicionar_passaro(PassaroVermelho(30, 30)) # Adicionar Pássaros Amarelos for i in range(30): fase.adicionar_passaro(PassaroAmarelo(30, 30)) # Obstaculos for i in range(30, 480, 32): fase.adicionar_obstaculo(Obstaculo(300, i)) # Porcos for i in range(30, 300, 32): fase.adicionar_porco(Porco(600, i)) rodar_fase(fase)
from os import path import sys project_dir = path.dirname(__file__) project_dir = path.join('..') sys.path.append(project_dir) from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase from placa_grafica_tkinter import rodar_fase if __name__ == '__main__': fase = Fase(intervalo_de_colisao=10) # Adicionar Pássaros Vermelhos for i in range(5): fase.adicionar_passaro(PassaroVermelho(30, 30)) # Adicionar Pássaros Amarelos for i in range(30): fase.adicionar_passaro(PassaroAmarelo(30, 30)) # Obstaculos for i in range(30, 480, 32): fase.adicionar_obstaculo(Obstaculo(300, i)) # Porcos for i in range(30, 300, 32): fase.adicionar_porco(Porco(600, i)) rodar_fase(fase)
Refactor para funfar via linha de comando
Refactor para funfar via linha de comando
Python
mit
guoliveer/pythonbirds,deniscampos/pythonbirds,renzon/pythonbirds-fatec,giovaneliberato/python_birds_fp,pythonprobr/pythonbirds,jvitorlb/pythonbirds,evertongoncalves/pythonbirds,renzon/python-birds-t5,Cleitoon1/pythonbirds,gomesfelipe/pythonbirds,igorlimasan/pythonbirds
+ from os import path + import sys - from __future__ import unicode_literals + project_dir = path.dirname(__file__) + project_dir = path.join('..') + sys.path.append(project_dir) + from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase from placa_grafica_tkinter import rodar_fase - if __name__=='__main__': + if __name__ == '__main__': fase = Fase(intervalo_de_colisao=10) # Adicionar Pássaros Vermelhos for i in range(5): fase.adicionar_passaro(PassaroVermelho(30, 30)) # Adicionar Pássaros Amarelos for i in range(30): fase.adicionar_passaro(PassaroAmarelo(30, 30)) # Obstaculos for i in range(30, 480, 32): fase.adicionar_obstaculo(Obstaculo(300, i)) # Porcos for i in range(30, 300, 32): fase.adicionar_porco(Porco(600, i)) rodar_fase(fase)
Refactor para funfar via linha de comando
## Code Before: from __future__ import unicode_literals from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase from placa_grafica_tkinter import rodar_fase if __name__=='__main__': fase = Fase(intervalo_de_colisao=10) # Adicionar Pássaros Vermelhos for i in range(5): fase.adicionar_passaro(PassaroVermelho(30, 30)) # Adicionar Pássaros Amarelos for i in range(30): fase.adicionar_passaro(PassaroAmarelo(30, 30)) # Obstaculos for i in range(30, 480, 32): fase.adicionar_obstaculo(Obstaculo(300, i)) # Porcos for i in range(30, 300, 32): fase.adicionar_porco(Porco(600, i)) rodar_fase(fase) ## Instruction: Refactor para funfar via linha de comando ## Code After: from os import path import sys project_dir = path.dirname(__file__) project_dir = path.join('..') sys.path.append(project_dir) from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase from placa_grafica_tkinter import rodar_fase if __name__ == '__main__': fase = Fase(intervalo_de_colisao=10) # Adicionar Pássaros Vermelhos for i in range(5): fase.adicionar_passaro(PassaroVermelho(30, 30)) # Adicionar Pássaros Amarelos for i in range(30): fase.adicionar_passaro(PassaroAmarelo(30, 30)) # Obstaculos for i in range(30, 480, 32): fase.adicionar_obstaculo(Obstaculo(300, i)) # Porcos for i in range(30, 300, 32): fase.adicionar_porco(Porco(600, i)) rodar_fase(fase)
... from os import path import sys project_dir = path.dirname(__file__) project_dir = path.join('..') sys.path.append(project_dir) from atores import PassaroAmarelo, PassaroVermelho, Obstaculo, Porco from fase import Fase ... from placa_grafica_tkinter import rodar_fase if __name__ == '__main__': fase = Fase(intervalo_de_colisao=10) ...
cc80f90a4f003c0967c31d5177971061350ee683
pycall/call.py
pycall/call.py
"""A simple wrapper for Asterisk calls.""" class Call(object): """Stores and manipulates Asterisk calls.""" def __init__(self, channel, callerid=None, account=None, wait_time=None, max_retries=None): """Create a new `Call` object. :param str channel: The Asterisk channel to call. Should be in standard Asterisk format. :param str callerid: CallerID to use. :param str account: Account code to associate with this call. :param int wait_time: Amount of time to wait (in seconds) between retry attempts. :param int max_retries: Maximum amount of retry attempts. """ self.channel = channel self.callerid = callerid self.account = account self.wait_time = int(wait_time) self.max_retries = int(max_retries)
"""A simple wrapper for Asterisk calls.""" class Call(object): """Stores and manipulates Asterisk calls.""" def __init__(self, channel, callerid=None, account=None, wait_time=None, max_retries=None): """Create a new `Call` object. :param str channel: The Asterisk channel to call. Should be in standard Asterisk format. :param str callerid: CallerID to use. :param str account: Account code to associate with this call. :param int wait_time: Amount of time to wait (in seconds) between retry attempts. :param int max_retries: Maximum amount of retry attempts. """ self.channel = channel self.callerid = callerid self.account = account self.wait_time = wait_time self.max_retries = max_retries
Revert "Forcing type coersion for int params."
Revert "Forcing type coersion for int params." This is a pointless bit of code. Since we lazy-evaluate them anyhow, it's a duplicate effort. This reverts commit 1ca6b96d492f8f33ac3b3a520937378effb66744.
Python
unlicense
rdegges/pycall
"""A simple wrapper for Asterisk calls.""" class Call(object): """Stores and manipulates Asterisk calls.""" def __init__(self, channel, callerid=None, account=None, wait_time=None, max_retries=None): """Create a new `Call` object. :param str channel: The Asterisk channel to call. Should be in standard Asterisk format. :param str callerid: CallerID to use. :param str account: Account code to associate with this call. :param int wait_time: Amount of time to wait (in seconds) between retry attempts. :param int max_retries: Maximum amount of retry attempts. """ self.channel = channel self.callerid = callerid self.account = account - self.wait_time = int(wait_time) + self.wait_time = wait_time - self.max_retries = int(max_retries) + self.max_retries = max_retries
Revert "Forcing type coersion for int params."
## Code Before: """A simple wrapper for Asterisk calls.""" class Call(object): """Stores and manipulates Asterisk calls.""" def __init__(self, channel, callerid=None, account=None, wait_time=None, max_retries=None): """Create a new `Call` object. :param str channel: The Asterisk channel to call. Should be in standard Asterisk format. :param str callerid: CallerID to use. :param str account: Account code to associate with this call. :param int wait_time: Amount of time to wait (in seconds) between retry attempts. :param int max_retries: Maximum amount of retry attempts. """ self.channel = channel self.callerid = callerid self.account = account self.wait_time = int(wait_time) self.max_retries = int(max_retries) ## Instruction: Revert "Forcing type coersion for int params." ## Code After: """A simple wrapper for Asterisk calls.""" class Call(object): """Stores and manipulates Asterisk calls.""" def __init__(self, channel, callerid=None, account=None, wait_time=None, max_retries=None): """Create a new `Call` object. :param str channel: The Asterisk channel to call. Should be in standard Asterisk format. :param str callerid: CallerID to use. :param str account: Account code to associate with this call. :param int wait_time: Amount of time to wait (in seconds) between retry attempts. :param int max_retries: Maximum amount of retry attempts. """ self.channel = channel self.callerid = callerid self.account = account self.wait_time = wait_time self.max_retries = max_retries
... self.callerid = callerid self.account = account self.wait_time = wait_time self.max_retries = max_retries ...
6f20554c2a7b0223b2291227b67fb3ede003f525
setup.py
setup.py
import os import sys from distutils.core import setup from fedwatch import __version__ setup( name = 'fedwatch', description = 'Module for creating simple scripts reacting to fedmsg messages', version = __version__, license = 'LGPLv2+', py_modules = ['fedwatch'], maintainer = 'Stanislav Ochotnicky', maintainer_email = '[email protected]' )
import os import sys from distutils.core import setup from fedwatch import __version__ setup( name = 'fedwatch', description = 'Module for creating simple scripts reacting to fedmsg messages', version = __version__, license = 'LGPLv2+', py_modules = ['fedwatch'], scripts = ['fedwatch-cli'], maintainer = 'Stanislav Ochotnicky', maintainer_email = '[email protected]' )
Add fedwatch-cli as installed script
Add fedwatch-cli as installed script
Python
lgpl-2.1
pombredanne/fedwatch,sochotnicky/fedwatch,pombredanne/fedwatch,mizdebsk/fedwatch,sochotnicky/fedwatch,mizdebsk/fedwatch
import os import sys from distutils.core import setup from fedwatch import __version__ setup( name = 'fedwatch', description = 'Module for creating simple scripts reacting to fedmsg messages', version = __version__, license = 'LGPLv2+', py_modules = ['fedwatch'], + scripts = ['fedwatch-cli'], maintainer = 'Stanislav Ochotnicky', maintainer_email = '[email protected]' )
Add fedwatch-cli as installed script
## Code Before: import os import sys from distutils.core import setup from fedwatch import __version__ setup( name = 'fedwatch', description = 'Module for creating simple scripts reacting to fedmsg messages', version = __version__, license = 'LGPLv2+', py_modules = ['fedwatch'], maintainer = 'Stanislav Ochotnicky', maintainer_email = '[email protected]' ) ## Instruction: Add fedwatch-cli as installed script ## Code After: import os import sys from distutils.core import setup from fedwatch import __version__ setup( name = 'fedwatch', description = 'Module for creating simple scripts reacting to fedmsg messages', version = __version__, license = 'LGPLv2+', py_modules = ['fedwatch'], scripts = ['fedwatch-cli'], maintainer = 'Stanislav Ochotnicky', maintainer_email = '[email protected]' )
... license = 'LGPLv2+', py_modules = ['fedwatch'], scripts = ['fedwatch-cli'], maintainer = 'Stanislav Ochotnicky', maintainer_email = '[email protected]' ...
5dc63d9c544f0335cd037bc2f6c0ce613e7783ea
gerrit/documentation.py
gerrit/documentation.py
URLS = { } class Documentation(object): """ This class provide documentation-related methods Documentation related REST endpoints: https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html """ def __init__(self, gerrit): self.gerrit = gerrit self.gerrit.URLS.update(URLS)
URLS = { 'SEARCH': 'Documentation/?q=%(keyword)s', } class Documentation(object): """ This class provide documentation-related methods Documentation related REST endpoints: https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html """ def __init__(self, gerrit): self.gerrit = gerrit self.gerrit.URLS.update(URLS) def search(self, keyword): url = self.gerrit.url('SEARCH', keyword=keyword) r = Request(method='GET', url=url, auth=self.gerrit.auth) return self.gerrit.dispatch(r)
Add methods for Documentation Endpoints
Add methods for Documentation Endpoints Signed-off-by: Huang Yaming <[email protected]>
Python
apache-2.0
yumminhuang/gerrit.py
URLS = { + 'SEARCH': 'Documentation/?q=%(keyword)s', } class Documentation(object): """ This class provide documentation-related methods Documentation related REST endpoints: https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html """ def __init__(self, gerrit): self.gerrit = gerrit self.gerrit.URLS.update(URLS) + def search(self, keyword): + url = self.gerrit.url('SEARCH', keyword=keyword) + r = Request(method='GET', url=url, auth=self.gerrit.auth) + return self.gerrit.dispatch(r) +
Add methods for Documentation Endpoints
## Code Before: URLS = { } class Documentation(object): """ This class provide documentation-related methods Documentation related REST endpoints: https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html """ def __init__(self, gerrit): self.gerrit = gerrit self.gerrit.URLS.update(URLS) ## Instruction: Add methods for Documentation Endpoints ## Code After: URLS = { 'SEARCH': 'Documentation/?q=%(keyword)s', } class Documentation(object): """ This class provide documentation-related methods Documentation related REST endpoints: https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html """ def __init__(self, gerrit): self.gerrit = gerrit self.gerrit.URLS.update(URLS) def search(self, keyword): url = self.gerrit.url('SEARCH', keyword=keyword) r = Request(method='GET', url=url, auth=self.gerrit.auth) return self.gerrit.dispatch(r)
// ... existing code ... URLS = { 'SEARCH': 'Documentation/?q=%(keyword)s', } // ... modified code ... self.gerrit = gerrit self.gerrit.URLS.update(URLS) def search(self, keyword): url = self.gerrit.url('SEARCH', keyword=keyword) r = Request(method='GET', url=url, auth=self.gerrit.auth) return self.gerrit.dispatch(r) // ... rest of the code ...
f34a5d682832749dbf0011d162bf4c7c18892b45
zerver/apps.py
zerver/apps.py
import logging from typing import Any, Dict from django.apps import AppConfig from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_migrate def flush_cache(sender: AppConfig, **kwargs: Any) -> None: logging.info("Clearing memcached cache after migrations") cache.clear() class ZerverConfig(AppConfig): name = "zerver" # type: str def ready(self) -> None: import zerver.signals if settings.POST_MIGRATION_CACHE_FLUSHING: post_migrate.connect(flush_cache, sender=self)
import logging from typing import Any, Dict from django.apps import AppConfig from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_migrate def flush_cache(sender: AppConfig, **kwargs: Any) -> None: logging.info("Clearing memcached cache after migrations") cache.clear() class ZerverConfig(AppConfig): name = "zerver" # type: str def ready(self) -> None: # We import zerver.signals here for the side effect of # registering the user_logged_in signal receiver. This import # needs to be here (rather than e.g. at top-of-file) to avoid # running that code too early in Django's setup process, but # in any case, this is an intentionally unused import. import zerver.signals if settings.POST_MIGRATION_CACHE_FLUSHING: post_migrate.connect(flush_cache, sender=self)
Document the weird unused import for signal registration.
signals: Document the weird unused import for signal registration.
Python
apache-2.0
timabbott/zulip,tommyip/zulip,zulip/zulip,andersk/zulip,andersk/zulip,eeshangarg/zulip,kou/zulip,eeshangarg/zulip,eeshangarg/zulip,showell/zulip,brainwane/zulip,andersk/zulip,rishig/zulip,synicalsyntax/zulip,andersk/zulip,tommyip/zulip,hackerkid/zulip,kou/zulip,zulip/zulip,showell/zulip,eeshangarg/zulip,shubhamdhama/zulip,rishig/zulip,brainwane/zulip,rht/zulip,timabbott/zulip,timabbott/zulip,shubhamdhama/zulip,andersk/zulip,rht/zulip,brainwane/zulip,punchagan/zulip,hackerkid/zulip,zulip/zulip,brainwane/zulip,hackerkid/zulip,showell/zulip,kou/zulip,kou/zulip,andersk/zulip,brainwane/zulip,rht/zulip,zulip/zulip,kou/zulip,zulip/zulip,shubhamdhama/zulip,punchagan/zulip,timabbott/zulip,brainwane/zulip,tommyip/zulip,punchagan/zulip,shubhamdhama/zulip,hackerkid/zulip,punchagan/zulip,synicalsyntax/zulip,synicalsyntax/zulip,hackerkid/zulip,synicalsyntax/zulip,showell/zulip,rht/zulip,rishig/zulip,rishig/zulip,showell/zulip,kou/zulip,synicalsyntax/zulip,punchagan/zulip,rht/zulip,eeshangarg/zulip,eeshangarg/zulip,rishig/zulip,timabbott/zulip,tommyip/zulip,shubhamdhama/zulip,zulip/zulip,timabbott/zulip,eeshangarg/zulip,hackerkid/zulip,rishig/zulip,rishig/zulip,tommyip/zulip,tommyip/zulip,shubhamdhama/zulip,zulip/zulip,hackerkid/zulip,kou/zulip,shubhamdhama/zulip,andersk/zulip,showell/zulip,timabbott/zulip,rht/zulip,rht/zulip,synicalsyntax/zulip,synicalsyntax/zulip,brainwane/zulip,tommyip/zulip,punchagan/zulip,showell/zulip,punchagan/zulip
import logging from typing import Any, Dict from django.apps import AppConfig from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_migrate def flush_cache(sender: AppConfig, **kwargs: Any) -> None: logging.info("Clearing memcached cache after migrations") cache.clear() class ZerverConfig(AppConfig): name = "zerver" # type: str def ready(self) -> None: + # We import zerver.signals here for the side effect of + # registering the user_logged_in signal receiver. This import + # needs to be here (rather than e.g. at top-of-file) to avoid + # running that code too early in Django's setup process, but + # in any case, this is an intentionally unused import. import zerver.signals if settings.POST_MIGRATION_CACHE_FLUSHING: post_migrate.connect(flush_cache, sender=self)
Document the weird unused import for signal registration.
## Code Before: import logging from typing import Any, Dict from django.apps import AppConfig from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_migrate def flush_cache(sender: AppConfig, **kwargs: Any) -> None: logging.info("Clearing memcached cache after migrations") cache.clear() class ZerverConfig(AppConfig): name = "zerver" # type: str def ready(self) -> None: import zerver.signals if settings.POST_MIGRATION_CACHE_FLUSHING: post_migrate.connect(flush_cache, sender=self) ## Instruction: Document the weird unused import for signal registration. ## Code After: import logging from typing import Any, Dict from django.apps import AppConfig from django.conf import settings from django.core.cache import cache from django.db.models.signals import post_migrate def flush_cache(sender: AppConfig, **kwargs: Any) -> None: logging.info("Clearing memcached cache after migrations") cache.clear() class ZerverConfig(AppConfig): name = "zerver" # type: str def ready(self) -> None: # We import zerver.signals here for the side effect of # registering the user_logged_in signal receiver. This import # needs to be here (rather than e.g. at top-of-file) to avoid # running that code too early in Django's setup process, but # in any case, this is an intentionally unused import. import zerver.signals if settings.POST_MIGRATION_CACHE_FLUSHING: post_migrate.connect(flush_cache, sender=self)
// ... existing code ... def ready(self) -> None: # We import zerver.signals here for the side effect of # registering the user_logged_in signal receiver. This import # needs to be here (rather than e.g. at top-of-file) to avoid # running that code too early in Django's setup process, but # in any case, this is an intentionally unused import. import zerver.signals // ... rest of the code ...
ae4519a26e372f8a27a7e460fc08d409c5bafe55
networkx/algorithms/flow/__init__.py
networkx/algorithms/flow/__init__.py
from networkx.algorithms.flow.maxflow import * from networkx.algorithms.flow.mincost import * from networkx.algorithms.flow.preflow_push import * from networkx.algorithms.flow.shortest_augmenting_path import * del utils
from . import maxflow, mincost, preflow_push, shortest_augmenting_path __all__ = sum([maxflow.__all__, mincost.__all__, preflow_push.__all__, shortest_augmenting_path.__all__], []) from .maxflow import * from .mincost import * from .preflow_push import * from .shortest_augmenting_path import *
Modify handling of module conflict in shortest augmenting path maxflow
Modify handling of module conflict in shortest augmenting path maxflow
Python
bsd-3-clause
nathania/networkx,ionanrozenfeld/networkx,dmoliveira/networkx,aureooms/networkx,kernc/networkx,dmoliveira/networkx,aureooms/networkx,kernc/networkx,harlowja/networkx,jni/networkx,jakevdp/networkx,jni/networkx,jakevdp/networkx,Sixshaman/networkx,RMKD/networkx,RMKD/networkx,ionanrozenfeld/networkx,sharifulgeo/networkx,debsankha/networkx,dmoliveira/networkx,harlowja/networkx,blublud/networkx,goulu/networkx,beni55/networkx,bzero/networkx,jni/networkx,RMKD/networkx,nathania/networkx,bzero/networkx,jcurbelo/networkx,cmtm/networkx,harlowja/networkx,jfinkels/networkx,debsankha/networkx,ghdk/networkx,chrisnatali/networkx,SanketDG/networkx,sharifulgeo/networkx,michaelpacer/networkx,dhimmel/networkx,chrisnatali/networkx,andnovar/networkx,ghdk/networkx,dhimmel/networkx,dhimmel/networkx,farhaanbukhsh/networkx,aureooms/networkx,ionanrozenfeld/networkx,chrisnatali/networkx,debsankha/networkx,farhaanbukhsh/networkx,ltiao/networkx,yashu-seth/networkx,kernc/networkx,sharifulgeo/networkx,ghdk/networkx,blublud/networkx,farhaanbukhsh/networkx,JamesClough/networkx,OrkoHunter/networkx,wasade/networkx,jakevdp/networkx,bzero/networkx,blublud/networkx,NvanAdrichem/networkx,tmilicic/networkx,nathania/networkx
+ from . import maxflow, mincost, preflow_push, shortest_augmenting_path - from networkx.algorithms.flow.maxflow import * - from networkx.algorithms.flow.mincost import * - from networkx.algorithms.flow.preflow_push import * - from networkx.algorithms.flow.shortest_augmenting_path import * - del utils + __all__ = sum([maxflow.__all__, mincost.__all__, preflow_push.__all__, + shortest_augmenting_path.__all__], []) + from .maxflow import * + from .mincost import * + from .preflow_push import * + from .shortest_augmenting_path import * +
Modify handling of module conflict in shortest augmenting path maxflow
## Code Before: from networkx.algorithms.flow.maxflow import * from networkx.algorithms.flow.mincost import * from networkx.algorithms.flow.preflow_push import * from networkx.algorithms.flow.shortest_augmenting_path import * del utils ## Instruction: Modify handling of module conflict in shortest augmenting path maxflow ## Code After: from . import maxflow, mincost, preflow_push, shortest_augmenting_path __all__ = sum([maxflow.__all__, mincost.__all__, preflow_push.__all__, shortest_augmenting_path.__all__], []) from .maxflow import * from .mincost import * from .preflow_push import * from .shortest_augmenting_path import *
... from . import maxflow, mincost, preflow_push, shortest_augmenting_path __all__ = sum([maxflow.__all__, mincost.__all__, preflow_push.__all__, shortest_augmenting_path.__all__], []) from .maxflow import * from .mincost import * from .preflow_push import * from .shortest_augmenting_path import * ...
d08d78460d0f7143b90a5157c4f5450bb062ec75
im2sim.py
im2sim.py
import argparse import PIL from PIL import Image import subprocess import os import glob def get_image(filename): p = Image.open(filename) docker_image = p.info['im2sim_image'] return subprocess.call('docker pull {}'.format(docker_image), shell=True) print('Pulled docker image {}'.format(docker_image)) def tag_images(docker_image): subprocess.call(['mkdir', '-p', 'figures']) subprocess.call("docker run -v {}/figures:/home/pyro/pyro2/figures " "{} make figures".format(os.getcwd(), docker_image), shell=True) figures = glob.glob('{}/figures/*.png'.format(os.getcwd())) for filename in figures: p = Image.open(filename) info = PIL.PngImagePlugin.PngInfo() info.add_text('im2sim_image', docker_image) p.save(filename, pnginfo = info) return None parser = argparse.ArgumentParser() parser.add_argument("action", help="'pull', 'tag'") parser.add_argument("object", help="Figure file (if pulling)" " or docker container (if tagging)") args = parser.parse_args() print("Action {}, Object {}".format(args.action, args.object)) if args.action == 'pull': get_image(args.object) elif args.action == 'tag': tag_images(args.object) else: print("Action must be either 'pull' or 'tag'.")
import argparse import PIL from PIL import Image import subprocess import os import glob def get_image(filename): p = Image.open(filename) docker_image = p.info['im2sim_image'] return subprocess.call('docker pull {}'.format(docker_image), shell=True) print('Pulled docker image {}'.format(docker_image)) def tag_images(docker_image): subprocess.call(['mkdir', '-p', 'figures']) subprocess.call("docker run -v {}/figures:/figures " "{} make figures".format(os.getcwd(), docker_image), shell=True) figures = glob.glob('{}/figures/*.png'.format(os.getcwd())) for filename in figures: p = Image.open(filename) info = PIL.PngImagePlugin.PngInfo() info.add_text('im2sim_image', docker_image) p.save(filename, pnginfo = info) return None parser = argparse.ArgumentParser() parser.add_argument("action", help="'pull', 'tag'") parser.add_argument("object", help="Figure file (if pulling)" " or docker container (if tagging)") args = parser.parse_args() print("Action {}, Object {}".format(args.action, args.object)) if args.action == 'pull': get_image(args.object) elif args.action == 'tag': tag_images(args.object) else: print("Action must be either 'pull' or 'tag'.")
Make script consistent with instructions.
Make script consistent with instructions.
Python
mit
IanHawke/im2sim
import argparse import PIL from PIL import Image import subprocess import os import glob def get_image(filename): p = Image.open(filename) docker_image = p.info['im2sim_image'] return subprocess.call('docker pull {}'.format(docker_image), shell=True) print('Pulled docker image {}'.format(docker_image)) def tag_images(docker_image): subprocess.call(['mkdir', '-p', 'figures']) - subprocess.call("docker run -v {}/figures:/home/pyro/pyro2/figures " + subprocess.call("docker run -v {}/figures:/figures " "{} make figures".format(os.getcwd(), docker_image), shell=True) figures = glob.glob('{}/figures/*.png'.format(os.getcwd())) for filename in figures: p = Image.open(filename) info = PIL.PngImagePlugin.PngInfo() info.add_text('im2sim_image', docker_image) p.save(filename, pnginfo = info) return None parser = argparse.ArgumentParser() parser.add_argument("action", help="'pull', 'tag'") parser.add_argument("object", help="Figure file (if pulling)" " or docker container (if tagging)") args = parser.parse_args() print("Action {}, Object {}".format(args.action, args.object)) if args.action == 'pull': get_image(args.object) elif args.action == 'tag': tag_images(args.object) else: print("Action must be either 'pull' or 'tag'.")
Make script consistent with instructions.
## Code Before: import argparse import PIL from PIL import Image import subprocess import os import glob def get_image(filename): p = Image.open(filename) docker_image = p.info['im2sim_image'] return subprocess.call('docker pull {}'.format(docker_image), shell=True) print('Pulled docker image {}'.format(docker_image)) def tag_images(docker_image): subprocess.call(['mkdir', '-p', 'figures']) subprocess.call("docker run -v {}/figures:/home/pyro/pyro2/figures " "{} make figures".format(os.getcwd(), docker_image), shell=True) figures = glob.glob('{}/figures/*.png'.format(os.getcwd())) for filename in figures: p = Image.open(filename) info = PIL.PngImagePlugin.PngInfo() info.add_text('im2sim_image', docker_image) p.save(filename, pnginfo = info) return None parser = argparse.ArgumentParser() parser.add_argument("action", help="'pull', 'tag'") parser.add_argument("object", help="Figure file (if pulling)" " or docker container (if tagging)") args = parser.parse_args() print("Action {}, Object {}".format(args.action, args.object)) if args.action == 'pull': get_image(args.object) elif args.action == 'tag': tag_images(args.object) else: print("Action must be either 'pull' or 'tag'.") ## Instruction: Make script consistent with instructions. ## Code After: import argparse import PIL from PIL import Image import subprocess import os import glob def get_image(filename): p = Image.open(filename) docker_image = p.info['im2sim_image'] return subprocess.call('docker pull {}'.format(docker_image), shell=True) print('Pulled docker image {}'.format(docker_image)) def tag_images(docker_image): subprocess.call(['mkdir', '-p', 'figures']) subprocess.call("docker run -v {}/figures:/figures " "{} make figures".format(os.getcwd(), docker_image), shell=True) figures = glob.glob('{}/figures/*.png'.format(os.getcwd())) for filename in figures: p = Image.open(filename) info = PIL.PngImagePlugin.PngInfo() info.add_text('im2sim_image', docker_image) p.save(filename, pnginfo = info) return None parser = argparse.ArgumentParser() parser.add_argument("action", help="'pull', 'tag'") parser.add_argument("object", help="Figure file (if pulling)" " or docker container (if tagging)") args = parser.parse_args() print("Action {}, Object {}".format(args.action, args.object)) if args.action == 'pull': get_image(args.object) elif args.action == 'tag': tag_images(args.object) else: print("Action must be either 'pull' or 'tag'.")
# ... existing code ... def tag_images(docker_image): subprocess.call(['mkdir', '-p', 'figures']) subprocess.call("docker run -v {}/figures:/figures " "{} make figures".format(os.getcwd(), docker_image), shell=True) # ... rest of the code ...
e5f4627845a6874aa983d2d8ea02d5bea0fab8e2
meetings/osf_oauth2_adapter/provider.py
meetings/osf_oauth2_adapter/provider.py
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=data.get('id'), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
Change username to osf uid
Change username to osf uid
Python
apache-2.0
jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,leodomingo/osf-meetings
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now - username=data.get('id'), + username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
Change username to osf uid
## Code Before: from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=data.get('id'), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider) ## Instruction: Change username to osf uid ## Code After: from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
... # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ...
84acc00a3f6d09b4212b6728667af583b45e5a99
km_api/know_me/tests/serializers/test_profile_list_serializer.py
km_api/know_me/tests/serializers/test_profile_list_serializer.py
from know_me import serializers def test_serialize(profile_factory): """ Test serializing a profile. """ profile = profile_factory() serializer = serializers.ProfileListSerializer(profile) expected = { 'id': profile.id, 'name': profile.name, 'quote': profile.quote, 'welcome_message': profile.welcome_message, } assert serializer.data == expected
from know_me import serializers def test_create(user_factory): """ Saving a serializer containing valid data should create a new profile. """ user = user_factory() data = { 'name': 'John', 'quote': "Hi, I'm John", 'welcome_message': 'This is my profile.', } serializer = serializers.ProfileListSerializer(data=data) assert serializer.is_valid() serializer.save(user=user) profile = user.profile assert profile.name == data['name'] assert profile.quote == data['quote'] assert profile.welcome_message == data['welcome_message'] assert profile.user == user def test_serialize(profile_factory): """ Test serializing a profile. """ profile = profile_factory() serializer = serializers.ProfileListSerializer(profile) expected = { 'id': profile.id, 'name': profile.name, 'quote': profile.quote, 'welcome_message': profile.welcome_message, } assert serializer.data == expected
Add test for creating profile from serializer.
Add test for creating profile from serializer.
Python
apache-2.0
knowmetools/km-api,knowmetools/km-api,knowmetools/km-api,knowmetools/km-api
from know_me import serializers + + + def test_create(user_factory): + """ + Saving a serializer containing valid data should create a new + profile. + """ + user = user_factory() + data = { + 'name': 'John', + 'quote': "Hi, I'm John", + 'welcome_message': 'This is my profile.', + } + + serializer = serializers.ProfileListSerializer(data=data) + assert serializer.is_valid() + + serializer.save(user=user) + profile = user.profile + + assert profile.name == data['name'] + assert profile.quote == data['quote'] + assert profile.welcome_message == data['welcome_message'] + assert profile.user == user def test_serialize(profile_factory): """ Test serializing a profile. """ profile = profile_factory() serializer = serializers.ProfileListSerializer(profile) expected = { 'id': profile.id, 'name': profile.name, 'quote': profile.quote, 'welcome_message': profile.welcome_message, } assert serializer.data == expected
Add test for creating profile from serializer.
## Code Before: from know_me import serializers def test_serialize(profile_factory): """ Test serializing a profile. """ profile = profile_factory() serializer = serializers.ProfileListSerializer(profile) expected = { 'id': profile.id, 'name': profile.name, 'quote': profile.quote, 'welcome_message': profile.welcome_message, } assert serializer.data == expected ## Instruction: Add test for creating profile from serializer. ## Code After: from know_me import serializers def test_create(user_factory): """ Saving a serializer containing valid data should create a new profile. """ user = user_factory() data = { 'name': 'John', 'quote': "Hi, I'm John", 'welcome_message': 'This is my profile.', } serializer = serializers.ProfileListSerializer(data=data) assert serializer.is_valid() serializer.save(user=user) profile = user.profile assert profile.name == data['name'] assert profile.quote == data['quote'] assert profile.welcome_message == data['welcome_message'] assert profile.user == user def test_serialize(profile_factory): """ Test serializing a profile. """ profile = profile_factory() serializer = serializers.ProfileListSerializer(profile) expected = { 'id': profile.id, 'name': profile.name, 'quote': profile.quote, 'welcome_message': profile.welcome_message, } assert serializer.data == expected
// ... existing code ... from know_me import serializers def test_create(user_factory): """ Saving a serializer containing valid data should create a new profile. """ user = user_factory() data = { 'name': 'John', 'quote': "Hi, I'm John", 'welcome_message': 'This is my profile.', } serializer = serializers.ProfileListSerializer(data=data) assert serializer.is_valid() serializer.save(user=user) profile = user.profile assert profile.name == data['name'] assert profile.quote == data['quote'] assert profile.welcome_message == data['welcome_message'] assert profile.user == user // ... rest of the code ...
4e438122b5715f6a8765f50173c1dca1e18c6f8f
tests/__init__.py
tests/__init__.py
from __future__ import unicode_literals import gc import platform import cffi cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): assert len(args) >= 2 buffer_, buffer_size = args[-2:] # -1 to keep a char free for \0 terminating the string length = min(len(string), buffer_size - 1) # Due to Python 3 treating bytes as an array of ints, we have to # encode and copy chars one by one. for i in range(length): buffer_[i] = string[i].encode('utf-8') return len(string) return func def gc_collect(): """Run enough GC collections to make object finalizers run.""" if platform.python_implementation() == 'PyPy': # Since PyPy use garbage collection instead of reference counting # objects are not finalized before the next major GC collection. # Currently, the best way we have to ensure a major GC collection has # run is to call gc.collect() a number of times. [gc.collect() for _ in range(10)] else: gc.collect()
from __future__ import unicode_literals import gc import platform import cffi # Import the module so that ffi.verify() is run before cffi.verifier is used import spotify # noqa cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): assert len(args) >= 2 buffer_, buffer_size = args[-2:] # -1 to keep a char free for \0 terminating the string length = min(len(string), buffer_size - 1) # Due to Python 3 treating bytes as an array of ints, we have to # encode and copy chars one by one. for i in range(length): buffer_[i] = string[i].encode('utf-8') return len(string) return func def gc_collect(): """Run enough GC collections to make object finalizers run.""" if platform.python_implementation() == 'PyPy': # Since PyPy use garbage collection instead of reference counting # objects are not finalized before the next major GC collection. # Currently, the best way we have to ensure a major GC collection has # run is to call gc.collect() a number of times. [gc.collect() for _ in range(10)] else: gc.collect()
Make specific test files runnable
tests: Make specific test files runnable
Python
apache-2.0
jodal/pyspotify,jodal/pyspotify,felix1m/pyspotify,mopidy/pyspotify,kotamat/pyspotify,mopidy/pyspotify,kotamat/pyspotify,felix1m/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify
from __future__ import unicode_literals import gc import platform import cffi + + # Import the module so that ffi.verify() is run before cffi.verifier is used + import spotify # noqa cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): assert len(args) >= 2 buffer_, buffer_size = args[-2:] # -1 to keep a char free for \0 terminating the string length = min(len(string), buffer_size - 1) # Due to Python 3 treating bytes as an array of ints, we have to # encode and copy chars one by one. for i in range(length): buffer_[i] = string[i].encode('utf-8') return len(string) return func def gc_collect(): """Run enough GC collections to make object finalizers run.""" if platform.python_implementation() == 'PyPy': # Since PyPy use garbage collection instead of reference counting # objects are not finalized before the next major GC collection. # Currently, the best way we have to ensure a major GC collection has # run is to call gc.collect() a number of times. [gc.collect() for _ in range(10)] else: gc.collect()
Make specific test files runnable
## Code Before: from __future__ import unicode_literals import gc import platform import cffi cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): assert len(args) >= 2 buffer_, buffer_size = args[-2:] # -1 to keep a char free for \0 terminating the string length = min(len(string), buffer_size - 1) # Due to Python 3 treating bytes as an array of ints, we have to # encode and copy chars one by one. for i in range(length): buffer_[i] = string[i].encode('utf-8') return len(string) return func def gc_collect(): """Run enough GC collections to make object finalizers run.""" if platform.python_implementation() == 'PyPy': # Since PyPy use garbage collection instead of reference counting # objects are not finalized before the next major GC collection. # Currently, the best way we have to ensure a major GC collection has # run is to call gc.collect() a number of times. [gc.collect() for _ in range(10)] else: gc.collect() ## Instruction: Make specific test files runnable ## Code After: from __future__ import unicode_literals import gc import platform import cffi # Import the module so that ffi.verify() is run before cffi.verifier is used import spotify # noqa cffi.verifier.cleanup_tmpdir() def buffer_writer(string): """Creates a function that takes a ``buffer`` and ``buffer_size`` as the two last arguments and writes the given ``string`` to ``buffer``. """ def func(*args): assert len(args) >= 2 buffer_, buffer_size = args[-2:] # -1 to keep a char free for \0 terminating the string length = min(len(string), buffer_size - 1) # Due to Python 3 treating bytes as an array of ints, we have to # encode and copy chars one by one. for i in range(length): buffer_[i] = string[i].encode('utf-8') return len(string) return func def gc_collect(): """Run enough GC collections to make object finalizers run.""" if platform.python_implementation() == 'PyPy': # Since PyPy use garbage collection instead of reference counting # objects are not finalized before the next major GC collection. # Currently, the best way we have to ensure a major GC collection has # run is to call gc.collect() a number of times. [gc.collect() for _ in range(10)] else: gc.collect()
// ... existing code ... import cffi # Import the module so that ffi.verify() is run before cffi.verifier is used import spotify # noqa cffi.verifier.cleanup_tmpdir() // ... rest of the code ...
125dfa47e5656c3f9b1e8846be03010ed02c6f91
tests/rules_tests/isValid_tests/InvalidSyntaxTest.py
tests/rules_tests/isValid_tests/InvalidSyntaxTest.py
from unittest import main, TestCase from grammpy import Rule class InvalidSyntaxTest(TestCase): pass if __name__ == '__main__': main()
from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions import RuleSyntaxException from .grammar import * class InvalidSyntaxTest(TestCase): def test_rulesMissingEncloseList(self): class tmp(Rule): rules = ([0], [1]) with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingTuple(self): class tmp(Rule): rules = [[0], [1]] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingInnerLeftList(self): class tmp(Rule): rules = [(0, [1])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingInnerRightList(self): class tmp(Rule): rules = [([0], 1)] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_multipleRulesMissingInnerLeftList(self): class tmp(Rule): rules = [(NFirst, TSecond), (0, [1])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_multipleRulesMissingInnerRightList(self): class tmp(Rule): rules = [(NFifth, TFirst), ([0], 1)] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_emptyRule(self): class tmp(Rule): rules = [([], [])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_emptyOneOfRules(self): class tmp(Rule): rules = [(NFifth, TFirst), ([], [])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_onlyOuterArray(self): class tmp(Rule): rules = [NFifth, TFirst] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_outerIsTuple(self): class tmp(Rule): rules = (([NFirst], [TSecond]), ([0], [1])) with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) if __name__ == '__main__': main()
Add base set of rule's invalid syntax tests
Add base set of rule's invalid syntax tests
Python
mit
PatrikValkovic/grammpy
from unittest import main, TestCase from grammpy import Rule + from grammpy.exceptions import RuleSyntaxException + from .grammar import * class InvalidSyntaxTest(TestCase): - pass + def test_rulesMissingEncloseList(self): + class tmp(Rule): + rules = ([0], [1]) + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_rulesMissingTuple(self): + class tmp(Rule): + rules = [[0], [1]] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_rulesMissingInnerLeftList(self): + class tmp(Rule): + rules = [(0, [1])] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_rulesMissingInnerRightList(self): + class tmp(Rule): + rules = [([0], 1)] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_multipleRulesMissingInnerLeftList(self): + class tmp(Rule): + rules = [(NFirst, TSecond), (0, [1])] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_multipleRulesMissingInnerRightList(self): + class tmp(Rule): + rules = [(NFifth, TFirst), ([0], 1)] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_emptyRule(self): + class tmp(Rule): + rules = [([], [])] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_emptyOneOfRules(self): + class tmp(Rule): + rules = [(NFifth, TFirst), ([], [])] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_onlyOuterArray(self): + class tmp(Rule): + rules = [NFifth, TFirst] + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) + + def test_outerIsTuple(self): + class tmp(Rule): + rules = (([NFirst], [TSecond]), ([0], [1])) + with self.assertRaises(RuleSyntaxException): + tmp.validate(grammar) if __name__ == '__main__': main() +
Add base set of rule's invalid syntax tests
## Code Before: from unittest import main, TestCase from grammpy import Rule class InvalidSyntaxTest(TestCase): pass if __name__ == '__main__': main() ## Instruction: Add base set of rule's invalid syntax tests ## Code After: from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions import RuleSyntaxException from .grammar import * class InvalidSyntaxTest(TestCase): def test_rulesMissingEncloseList(self): class tmp(Rule): rules = ([0], [1]) with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingTuple(self): class tmp(Rule): rules = [[0], [1]] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingInnerLeftList(self): class tmp(Rule): rules = [(0, [1])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingInnerRightList(self): class tmp(Rule): rules = [([0], 1)] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_multipleRulesMissingInnerLeftList(self): class tmp(Rule): rules = [(NFirst, TSecond), (0, [1])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_multipleRulesMissingInnerRightList(self): class tmp(Rule): rules = [(NFifth, TFirst), ([0], 1)] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_emptyRule(self): class tmp(Rule): rules = [([], [])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_emptyOneOfRules(self): class tmp(Rule): rules = [(NFifth, TFirst), ([], [])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_onlyOuterArray(self): class tmp(Rule): rules = [NFifth, TFirst] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_outerIsTuple(self): class tmp(Rule): rules = (([NFirst], [TSecond]), ([0], [1])) with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) if __name__ == '__main__': main()
# ... existing code ... from unittest import main, TestCase from grammpy import Rule from grammpy.exceptions import RuleSyntaxException from .grammar import * class InvalidSyntaxTest(TestCase): def test_rulesMissingEncloseList(self): class tmp(Rule): rules = ([0], [1]) with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingTuple(self): class tmp(Rule): rules = [[0], [1]] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingInnerLeftList(self): class tmp(Rule): rules = [(0, [1])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_rulesMissingInnerRightList(self): class tmp(Rule): rules = [([0], 1)] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_multipleRulesMissingInnerLeftList(self): class tmp(Rule): rules = [(NFirst, TSecond), (0, [1])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_multipleRulesMissingInnerRightList(self): class tmp(Rule): rules = [(NFifth, TFirst), ([0], 1)] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_emptyRule(self): class tmp(Rule): rules = [([], [])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_emptyOneOfRules(self): class tmp(Rule): rules = [(NFifth, TFirst), ([], [])] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_onlyOuterArray(self): class tmp(Rule): rules = [NFifth, TFirst] with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) def test_outerIsTuple(self): class tmp(Rule): rules = (([NFirst], [TSecond]), ([0], [1])) with self.assertRaises(RuleSyntaxException): tmp.validate(grammar) # ... rest of the code ...
d36e17e3823af74b5a6f75191f141ec98fdf281f
plugins/irc/irc.py
plugins/irc/irc.py
from p1tr.helpers import clean_string from p1tr.plugin import * @meta_plugin class Irc(Plugin): """Provides commands for basic IRC operations.""" @command @require_master def nick(self, server, channel, nick, params): """Usage: nick NEW_NICKNAME - changes the bot's nickname.""" if len(params) < 1: return clean_string(self.nick.__doc__) self.bot.client.send('NICK', params[0]) @command @require_master def join(self, server, channel, nick, params): """ Usage: join #CHANNEL [PASSWORD] - the bot will enter the specified channel. A password may be provided optionally, if it is required. """ if len(params) < 1: return clean_string(self.join.__doc__) password = '' if len(params) > 1: password = params[0] self.bot.client.send('JOIN', params[0], password) @command @require_op def part(self, server, channel, nick, params): """ Usage: part [#CHANNEL] - asks the bot to leave the current channel. Optionally, a channel may be specified if it should be left instead of the current one. """ if len(params) > 0: channel = params[0] self.bot.client.send('PART', channel) @command @require_master def quit(self, server, channel, nick, params): self.blot.intended_disconnect = True
from p1tr.helpers import clean_string from p1tr.plugin import * @meta_plugin class Irc(Plugin): """Provides commands for basic IRC operations.""" @command @require_master def nick(self, server, channel, nick, params): """Usage: nick NEW_NICKNAME - changes the bot's nickname.""" if len(params) < 1: return clean_string(self.nick.__doc__) self.bot.client.send('NICK', params[0]) @command @require_master def join(self, server, channel, nick, params): """ Usage: join #CHANNEL [PASSWORD] - the bot will enter the specified channel. A password may be provided optionally, if it is required. """ if len(params) < 1: return clean_string(self.join.__doc__) password = '' if len(params) > 1: password = params[0] self.bot.client.send('JOIN', params[0], password) @command @require_op def part(self, server, channel, nick, params): """ Usage: part [#CHANNEL] - asks the bot to leave the current channel. Optionally, a channel may be specified if it should be left instead of the current one. """ if len(params) > 0: channel = params[0] self.bot.client.send('PART', channel) @command @require_master def quit(self, server, channel, nick, params): """ Usage: quit - Tell the bot to disconnect from the server. """ self.bot.intended_disconnect = True self.bot.exit()
Fix failing reconnects; add quit IRC command
Fix failing reconnects; add quit IRC command
Python
mit
howard/p1tr-tng,howard/p1tr-tng
from p1tr.helpers import clean_string from p1tr.plugin import * @meta_plugin class Irc(Plugin): """Provides commands for basic IRC operations.""" @command @require_master def nick(self, server, channel, nick, params): """Usage: nick NEW_NICKNAME - changes the bot's nickname.""" if len(params) < 1: return clean_string(self.nick.__doc__) self.bot.client.send('NICK', params[0]) @command @require_master def join(self, server, channel, nick, params): """ Usage: join #CHANNEL [PASSWORD] - the bot will enter the specified channel. A password may be provided optionally, if it is required. """ if len(params) < 1: return clean_string(self.join.__doc__) password = '' if len(params) > 1: password = params[0] self.bot.client.send('JOIN', params[0], password) @command @require_op def part(self, server, channel, nick, params): """ Usage: part [#CHANNEL] - asks the bot to leave the current channel. Optionally, a channel may be specified if it should be left instead of the current one. """ if len(params) > 0: channel = params[0] self.bot.client.send('PART', channel) - + @command @require_master def quit(self, server, channel, nick, params): + """ + Usage: quit - Tell the bot to disconnect from the server. + """ - self.blot.intended_disconnect = True + self.bot.intended_disconnect = True + self.bot.exit()
Fix failing reconnects; add quit IRC command
## Code Before: from p1tr.helpers import clean_string from p1tr.plugin import * @meta_plugin class Irc(Plugin): """Provides commands for basic IRC operations.""" @command @require_master def nick(self, server, channel, nick, params): """Usage: nick NEW_NICKNAME - changes the bot's nickname.""" if len(params) < 1: return clean_string(self.nick.__doc__) self.bot.client.send('NICK', params[0]) @command @require_master def join(self, server, channel, nick, params): """ Usage: join #CHANNEL [PASSWORD] - the bot will enter the specified channel. A password may be provided optionally, if it is required. """ if len(params) < 1: return clean_string(self.join.__doc__) password = '' if len(params) > 1: password = params[0] self.bot.client.send('JOIN', params[0], password) @command @require_op def part(self, server, channel, nick, params): """ Usage: part [#CHANNEL] - asks the bot to leave the current channel. Optionally, a channel may be specified if it should be left instead of the current one. """ if len(params) > 0: channel = params[0] self.bot.client.send('PART', channel) @command @require_master def quit(self, server, channel, nick, params): self.blot.intended_disconnect = True ## Instruction: Fix failing reconnects; add quit IRC command ## Code After: from p1tr.helpers import clean_string from p1tr.plugin import * @meta_plugin class Irc(Plugin): """Provides commands for basic IRC operations.""" @command @require_master def nick(self, server, channel, nick, params): """Usage: nick NEW_NICKNAME - changes the bot's nickname.""" if len(params) < 1: return clean_string(self.nick.__doc__) self.bot.client.send('NICK', params[0]) @command @require_master def join(self, server, channel, nick, params): """ Usage: join #CHANNEL [PASSWORD] - the bot will enter the specified channel. A password may be provided optionally, if it is required. """ if len(params) < 1: return clean_string(self.join.__doc__) password = '' if len(params) > 1: password = params[0] self.bot.client.send('JOIN', params[0], password) @command @require_op def part(self, server, channel, nick, params): """ Usage: part [#CHANNEL] - asks the bot to leave the current channel. Optionally, a channel may be specified if it should be left instead of the current one. """ if len(params) > 0: channel = params[0] self.bot.client.send('PART', channel) @command @require_master def quit(self, server, channel, nick, params): """ Usage: quit - Tell the bot to disconnect from the server. """ self.bot.intended_disconnect = True self.bot.exit()
# ... existing code ... channel = params[0] self.bot.client.send('PART', channel) @command @require_master def quit(self, server, channel, nick, params): """ Usage: quit - Tell the bot to disconnect from the server. """ self.bot.intended_disconnect = True self.bot.exit() # ... rest of the code ...
1629d6d369bce079c33986aa62a12a1ad3a8a47d
test/test_grequest.py
test/test_grequest.py
from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def cancel(self, completed): if completed is not self.completed: #raise AssertionError() raise MPI.Exception(MPI.ERR_PENDING) class TestGrequest(unittest.TestCase): def testAll(self): ctx = GReqCtx() greq = MPI.Grequest.Start(ctx.query, ctx.free, ctx.cancel) self.assertFalse(greq.Test()) self.assertFalse(ctx.free_called) greq.Cancel() greq.Complete() ctx.completed = True greq.Cancel() status = MPI.Status() self.assertTrue(greq.Test(status)) self.assertEqual(status.Get_source(), ctx.source) self.assertEqual(status.Get_tag(), ctx.tag) greq.Wait() self.assertTrue(ctx.free_called) if MPI.Get_version() < (2, 0): del GReqCtx del TestGrequest if __name__ == '__main__': unittest.main()
from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def cancel(self, completed): if completed is not self.completed: raise MPI.Exception(MPI.ERR_PENDING) class TestGrequest(unittest.TestCase): def testAll(self): ctx = GReqCtx() greq = MPI.Grequest.Start(ctx.query, ctx.free, ctx.cancel) self.assertFalse(greq.Test()) self.assertFalse(ctx.free_called) greq.Cancel() greq.Complete() ctx.completed = True greq.Cancel() status = MPI.Status() self.assertTrue(greq.Test(status)) self.assertEqual(status.Get_source(), ctx.source) self.assertEqual(status.Get_tag(), ctx.tag) greq.Wait() self.assertTrue(ctx.free_called) if MPI.Get_version() < (2, 0): del GReqCtx del TestGrequest if __name__ == '__main__': unittest.main()
Remove commented-out line in testcase
Remove commented-out line in testcase
Python
bsd-2-clause
pressel/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,pressel/mpi4py,pressel/mpi4py,pressel/mpi4py
from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def cancel(self, completed): if completed is not self.completed: - #raise AssertionError() raise MPI.Exception(MPI.ERR_PENDING) class TestGrequest(unittest.TestCase): def testAll(self): ctx = GReqCtx() greq = MPI.Grequest.Start(ctx.query, ctx.free, ctx.cancel) self.assertFalse(greq.Test()) self.assertFalse(ctx.free_called) greq.Cancel() greq.Complete() ctx.completed = True greq.Cancel() status = MPI.Status() self.assertTrue(greq.Test(status)) self.assertEqual(status.Get_source(), ctx.source) self.assertEqual(status.Get_tag(), ctx.tag) greq.Wait() self.assertTrue(ctx.free_called) if MPI.Get_version() < (2, 0): del GReqCtx del TestGrequest if __name__ == '__main__': unittest.main()
Remove commented-out line in testcase
## Code Before: from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def cancel(self, completed): if completed is not self.completed: #raise AssertionError() raise MPI.Exception(MPI.ERR_PENDING) class TestGrequest(unittest.TestCase): def testAll(self): ctx = GReqCtx() greq = MPI.Grequest.Start(ctx.query, ctx.free, ctx.cancel) self.assertFalse(greq.Test()) self.assertFalse(ctx.free_called) greq.Cancel() greq.Complete() ctx.completed = True greq.Cancel() status = MPI.Status() self.assertTrue(greq.Test(status)) self.assertEqual(status.Get_source(), ctx.source) self.assertEqual(status.Get_tag(), ctx.tag) greq.Wait() self.assertTrue(ctx.free_called) if MPI.Get_version() < (2, 0): del GReqCtx del TestGrequest if __name__ == '__main__': unittest.main() ## Instruction: Remove commented-out line in testcase ## Code After: from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def cancel(self, completed): if completed is not self.completed: raise MPI.Exception(MPI.ERR_PENDING) class TestGrequest(unittest.TestCase): def testAll(self): ctx = GReqCtx() greq = MPI.Grequest.Start(ctx.query, ctx.free, ctx.cancel) self.assertFalse(greq.Test()) self.assertFalse(ctx.free_called) greq.Cancel() greq.Complete() ctx.completed = True greq.Cancel() status = MPI.Status() self.assertTrue(greq.Test(status)) self.assertEqual(status.Get_source(), ctx.source) self.assertEqual(status.Get_tag(), ctx.tag) greq.Wait() self.assertTrue(ctx.free_called) if MPI.Get_version() < (2, 0): del GReqCtx del TestGrequest if __name__ == '__main__': unittest.main()
... def cancel(self, completed): if completed is not self.completed: raise MPI.Exception(MPI.ERR_PENDING) ...
84b4fc8fdc3808340293c076a1628bf0decd2d2c
setup.py
setup.py
from distutils.core import setup setup(name="minishift-python", version="0.1.2", description="Python interface for the minishift", author="Nick Johnson", author_email="[email protected]", url="https://github.com/arachnidlabs/minishift-python/", packages=["minishift"], requires=["mcp2210"])
from distutils.core import setup setup(name="minishift-python", version="0.1.3", description="Python interface for the minishift", author="Nick Johnson", author_email="[email protected]", url="https://github.com/arachnidlabs/minishift-python/", packages=["minishift"], install_requires=["mcp2210", "python-daemon"])
Add python-daemon as a dep
Add python-daemon as a dep
Python
bsd-3-clause
arachnidlabs/minishift-python
from distutils.core import setup setup(name="minishift-python", - version="0.1.2", + version="0.1.3", description="Python interface for the minishift", author="Nick Johnson", author_email="[email protected]", url="https://github.com/arachnidlabs/minishift-python/", packages=["minishift"], - requires=["mcp2210"]) + install_requires=["mcp2210", "python-daemon"])
Add python-daemon as a dep
## Code Before: from distutils.core import setup setup(name="minishift-python", version="0.1.2", description="Python interface for the minishift", author="Nick Johnson", author_email="[email protected]", url="https://github.com/arachnidlabs/minishift-python/", packages=["minishift"], requires=["mcp2210"]) ## Instruction: Add python-daemon as a dep ## Code After: from distutils.core import setup setup(name="minishift-python", version="0.1.3", description="Python interface for the minishift", author="Nick Johnson", author_email="[email protected]", url="https://github.com/arachnidlabs/minishift-python/", packages=["minishift"], install_requires=["mcp2210", "python-daemon"])
// ... existing code ... setup(name="minishift-python", version="0.1.3", description="Python interface for the minishift", author="Nick Johnson", // ... modified code ... url="https://github.com/arachnidlabs/minishift-python/", packages=["minishift"], install_requires=["mcp2210", "python-daemon"]) // ... rest of the code ...
eae4b06bd798eab3a46bdd5b7452411bb7fb02e1
dashcam.py
dashcam.py
import pygame import picamera import os os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
import pygame import picamera import os import sys import io os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') size = width, height = 320, 240 pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode(size) go_button = pygame.image.load("/home/pi/bike_dashcam/media/go.bmp")
Update dascham with pygame GO button load
Update dascham with pygame GO button load
Python
mit
the-raspberry-pi-guy/bike_dashcam,the-raspberry-pi-guy/bike_dashcam
import pygame import picamera import os + import sys + import io os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') + size = width, height = 320, 240 + pygame.init() pygame.mouse.set_visible(False) - screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) + screen = pygame.display.set_mode(size) + go_button = pygame.image.load("/home/pi/bike_dashcam/media/go.bmp") + + +
Update dascham with pygame GO button load
## Code Before: import pygame import picamera import os os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN) ## Instruction: Update dascham with pygame GO button load ## Code After: import pygame import picamera import os import sys import io os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , '/dev/fb1') os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') size = width, height = 320, 240 pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode(size) go_button = pygame.image.load("/home/pi/bike_dashcam/media/go.bmp")
... import picamera import os import sys import io os.putenv('SDL_VIDEODRIVER', 'fbcon') ... os.putenv('SDL_MOUSEDEV' , '/dev/input/touchscreen') size = width, height = 320, 240 pygame.init() pygame.mouse.set_visible(False) screen = pygame.display.set_mode(size) go_button = pygame.image.load("/home/pi/bike_dashcam/media/go.bmp") ...
020ffbe8436da2f7ee654fa6a12d50f9915db17f
examples/collection/views.py
examples/collection/views.py
from cruditor.contrib.collection import CollectionViewMixin from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView from django.urls import reverse, reverse_lazy from examples.mixins import ExamplesMixin from store.models import Person from .filters import PersonFilter from .forms import PersonForm from .tables import PersonTable class PersonViewMixin(ExamplesMixin, CollectionViewMixin): model = Person collection_list_title = 'Persons' collection_list_urlname = 'collection:list' collection_detail_urlname = 'collection:change' class PersonListView(PersonViewMixin, CruditorListView): title = 'Persons' table_class = PersonTable def get_titlebuttons(self): return [{'url': reverse('collection:add'), 'label': 'Add person'}] class PersonFilterView(PersonListView): filter_class = PersonFilter class PersonAddView(PersonViewMixin, CruditorAddView): success_url = reverse_lazy('collection:lits') form_class = PersonForm class PersonChangeView(PersonViewMixin, CruditorChangeView): form_class = PersonForm def get_delete_url(self): return reverse('collection:delete', args=(self.object.pk,)) class PersonDeleteView(PersonViewMixin, CruditorDeleteView): pass
from cruditor.contrib.collection import CollectionViewMixin from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView from django.urls import reverse, reverse_lazy from examples.mixins import ExamplesMixin from store.models import Person from .filters import PersonFilter from .forms import PersonForm from .tables import PersonTable class PersonViewMixin(ExamplesMixin, CollectionViewMixin): model = Person collection_list_title = 'Persons' collection_list_urlname = 'collection:list' collection_detail_urlname = 'collection:change' class PersonListView(PersonViewMixin, CruditorListView): title = 'Persons' def get_titlebuttons(self): return [{'url': reverse('collection:add'), 'label': 'Add person'}] class PersonFilterView(PersonListView): filter_class = PersonFilter table_class = PersonTable class PersonAddView(PersonViewMixin, CruditorAddView): success_url = reverse_lazy('collection:lits') form_class = PersonForm class PersonChangeView(PersonViewMixin, CruditorChangeView): form_class = PersonForm def get_delete_url(self): return reverse('collection:delete', args=(self.object.pk,)) class PersonDeleteView(PersonViewMixin, CruditorDeleteView): pass
Make use of auto generated table classes.
Make use of auto generated table classes.
Python
mit
moccu/django-cruditor,moccu/django-cruditor,moccu/django-cruditor
from cruditor.contrib.collection import CollectionViewMixin from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView from django.urls import reverse, reverse_lazy from examples.mixins import ExamplesMixin from store.models import Person from .filters import PersonFilter from .forms import PersonForm from .tables import PersonTable class PersonViewMixin(ExamplesMixin, CollectionViewMixin): model = Person collection_list_title = 'Persons' collection_list_urlname = 'collection:list' collection_detail_urlname = 'collection:change' class PersonListView(PersonViewMixin, CruditorListView): title = 'Persons' - table_class = PersonTable def get_titlebuttons(self): return [{'url': reverse('collection:add'), 'label': 'Add person'}] class PersonFilterView(PersonListView): filter_class = PersonFilter + table_class = PersonTable class PersonAddView(PersonViewMixin, CruditorAddView): success_url = reverse_lazy('collection:lits') form_class = PersonForm class PersonChangeView(PersonViewMixin, CruditorChangeView): form_class = PersonForm def get_delete_url(self): return reverse('collection:delete', args=(self.object.pk,)) class PersonDeleteView(PersonViewMixin, CruditorDeleteView): pass
Make use of auto generated table classes.
## Code Before: from cruditor.contrib.collection import CollectionViewMixin from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView from django.urls import reverse, reverse_lazy from examples.mixins import ExamplesMixin from store.models import Person from .filters import PersonFilter from .forms import PersonForm from .tables import PersonTable class PersonViewMixin(ExamplesMixin, CollectionViewMixin): model = Person collection_list_title = 'Persons' collection_list_urlname = 'collection:list' collection_detail_urlname = 'collection:change' class PersonListView(PersonViewMixin, CruditorListView): title = 'Persons' table_class = PersonTable def get_titlebuttons(self): return [{'url': reverse('collection:add'), 'label': 'Add person'}] class PersonFilterView(PersonListView): filter_class = PersonFilter class PersonAddView(PersonViewMixin, CruditorAddView): success_url = reverse_lazy('collection:lits') form_class = PersonForm class PersonChangeView(PersonViewMixin, CruditorChangeView): form_class = PersonForm def get_delete_url(self): return reverse('collection:delete', args=(self.object.pk,)) class PersonDeleteView(PersonViewMixin, CruditorDeleteView): pass ## Instruction: Make use of auto generated table classes. ## Code After: from cruditor.contrib.collection import CollectionViewMixin from cruditor.views import CruditorAddView, CruditorChangeView, CruditorDeleteView, CruditorListView from django.urls import reverse, reverse_lazy from examples.mixins import ExamplesMixin from store.models import Person from .filters import PersonFilter from .forms import PersonForm from .tables import PersonTable class PersonViewMixin(ExamplesMixin, CollectionViewMixin): model = Person collection_list_title = 'Persons' collection_list_urlname = 'collection:list' collection_detail_urlname = 'collection:change' class PersonListView(PersonViewMixin, CruditorListView): title = 'Persons' def get_titlebuttons(self): return [{'url': reverse('collection:add'), 'label': 'Add person'}] class PersonFilterView(PersonListView): filter_class = PersonFilter table_class = PersonTable class PersonAddView(PersonViewMixin, CruditorAddView): success_url = reverse_lazy('collection:lits') form_class = PersonForm class PersonChangeView(PersonViewMixin, CruditorChangeView): form_class = PersonForm def get_delete_url(self): return reverse('collection:delete', args=(self.object.pk,)) class PersonDeleteView(PersonViewMixin, CruditorDeleteView): pass
# ... existing code ... class PersonListView(PersonViewMixin, CruditorListView): title = 'Persons' def get_titlebuttons(self): # ... modified code ... class PersonFilterView(PersonListView): filter_class = PersonFilter table_class = PersonTable # ... rest of the code ...
ea20f912696974a2543a8fa15f63f0a3b64d7263
froide/helper/utils.py
froide/helper/utils.py
from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): return render_code(400, request) def render_405(request): return render_code(405, request) def render_403(request, message=''): return render_code(403, request, context={"message": message})
from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): return render_code(400, request) def render_405(request): return render_code(405, request) def render_403(request, message=''): return render_code(403, request, context={"message": message}) def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip
Add utility function to get client IP from request
Add utility function to get client IP from request
Python
mit
ryankanno/froide,fin/froide,CodeforHawaii/froide,fin/froide,catcosmo/froide,LilithWittmann/froide,okfse/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,stefanw/froide,fin/froide,stefanw/froide,catcosmo/froide,okfse/froide,CodeforHawaii/froide,ryankanno/froide,stefanw/froide,catcosmo/froide,LilithWittmann/froide,fin/froide,catcosmo/froide,okfse/froide,catcosmo/froide,ryankanno/froide,okfse/froide,stefanw/froide,CodeforHawaii/froide,CodeforHawaii/froide,LilithWittmann/froide,CodeforHawaii/froide,LilithWittmann/froide,ryankanno/froide,stefanw/froide
from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): return render_code(400, request) def render_405(request): return render_code(405, request) def render_403(request, message=''): return render_code(403, request, context={"message": message}) + + def get_client_ip(request): + x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') + if x_forwarded_for: + ip = x_forwarded_for.split(',')[-1].strip() + else: + ip = request.META.get('REMOTE_ADDR') + return ip +
Add utility function to get client IP from request
## Code Before: from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): return render_code(400, request) def render_405(request): return render_code(405, request) def render_403(request, message=''): return render_code(403, request, context={"message": message}) ## Instruction: Add utility function to get client IP from request ## Code After: from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): return render_code(400, request) def render_405(request): return render_code(405, request) def render_403(request, message=''): return render_code(403, request, context={"message": message}) def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip
# ... existing code ... return render_code(403, request, context={"message": message}) def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip # ... rest of the code ...
233e74abcc4a70f573e199074f5184b30bdfe1d2
seam/__init__.py
seam/__init__.py
__author__ = 'Scott Burns <[email protected]>' __copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved' __version__ = '0.0' import freesurfer
__author__ = 'Scott Burns <[email protected]>' __copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved' __version__ = '0.0' from . import freesurfer __all__ = ['freesurfer', ]
Fix py3k relative import error
Fix py3k relative import error
Python
mit
VUIIS/seam,VUIIS/seam
__author__ = 'Scott Burns <[email protected]>' __copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved' __version__ = '0.0' - import freesurfer + from . import freesurfer + + __all__ = ['freesurfer', ] +
Fix py3k relative import error
## Code Before: __author__ = 'Scott Burns <[email protected]>' __copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved' __version__ = '0.0' import freesurfer ## Instruction: Fix py3k relative import error ## Code After: __author__ = 'Scott Burns <[email protected]>' __copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved' __version__ = '0.0' from . import freesurfer __all__ = ['freesurfer', ]
// ... existing code ... __version__ = '0.0' from . import freesurfer __all__ = ['freesurfer', ] // ... rest of the code ...
c6cb543f35356769dcc0f7fedb099a160e267473
run_tests.py
run_tests.py
import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # Use psycopg2cffi for PyPy try: import psycopg2 # noqa except ImportError: # Fall back to psycopg2cffi from psycopg2cffi import compat compat.register() # Set up Django import django from django.core.management import call_command django.setup() # Derive test names names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if not names: names = 'tests' elif re.search(r'^\d+', names): names = 'tests.tests.IssueTests.test_' + names elif not names.startswith('tests.'): names = 'tests.tests.' + names # NOTE: we create migrations each time since they depend on type of database, # python and django versions try: shutil.rmtree('tests/migrations', True) call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0) call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1) finally: shutil.rmtree('tests/migrations')
import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # Use psycopg2cffi for PyPy try: import psycopg2 # noqa except ImportError: # Fall back to psycopg2cffi try: from psycopg2cffi import compat compat.register() except ImportError: # Hope we are not testing against PostgreSQL :) pass # Set up Django import django from django.core.management import call_command django.setup() # Derive test names names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if not names: names = 'tests' elif re.search(r'^\d+', names): names = 'tests.tests.IssueTests.test_' + names elif not names.startswith('tests.'): names = 'tests.tests.' + names # NOTE: we create migrations each time since they depend on type of database, # python and django versions try: shutil.rmtree('tests/migrations', True) call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0) call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1) finally: shutil.rmtree('tests/migrations')
Stop requiring psycopg2 to run tests
Stop requiring psycopg2 to run tests
Python
bsd-3-clause
LPgenerator/django-cacheops,Suor/django-cacheops
import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # Use psycopg2cffi for PyPy try: import psycopg2 # noqa except ImportError: # Fall back to psycopg2cffi + try: - from psycopg2cffi import compat + from psycopg2cffi import compat - compat.register() + compat.register() + except ImportError: + # Hope we are not testing against PostgreSQL :) + pass # Set up Django import django from django.core.management import call_command django.setup() # Derive test names names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if not names: names = 'tests' elif re.search(r'^\d+', names): names = 'tests.tests.IssueTests.test_' + names elif not names.startswith('tests.'): names = 'tests.tests.' + names # NOTE: we create migrations each time since they depend on type of database, # python and django versions try: shutil.rmtree('tests/migrations', True) call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0) call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1) finally: shutil.rmtree('tests/migrations')
Stop requiring psycopg2 to run tests
## Code Before: import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # Use psycopg2cffi for PyPy try: import psycopg2 # noqa except ImportError: # Fall back to psycopg2cffi from psycopg2cffi import compat compat.register() # Set up Django import django from django.core.management import call_command django.setup() # Derive test names names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if not names: names = 'tests' elif re.search(r'^\d+', names): names = 'tests.tests.IssueTests.test_' + names elif not names.startswith('tests.'): names = 'tests.tests.' + names # NOTE: we create migrations each time since they depend on type of database, # python and django versions try: shutil.rmtree('tests/migrations', True) call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0) call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1) finally: shutil.rmtree('tests/migrations') ## Instruction: Stop requiring psycopg2 to run tests ## Code After: import os, sys, re, shutil os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' # Use psycopg2cffi for PyPy try: import psycopg2 # noqa except ImportError: # Fall back to psycopg2cffi try: from psycopg2cffi import compat compat.register() except ImportError: # Hope we are not testing against PostgreSQL :) pass # Set up Django import django from django.core.management import call_command django.setup() # Derive test names names = next((a for a in sys.argv[1:] if not a.startswith('-')), None) if not names: names = 'tests' elif re.search(r'^\d+', names): names = 'tests.tests.IssueTests.test_' + names elif not names.startswith('tests.'): names = 'tests.tests.' + names # NOTE: we create migrations each time since they depend on type of database, # python and django versions try: shutil.rmtree('tests/migrations', True) call_command('makemigrations', 'tests', verbosity=2 if '-v' in sys.argv else 0) call_command('test', names, failfast='-x' in sys.argv, verbosity=2 if '-v' in sys.argv else 1) finally: shutil.rmtree('tests/migrations')
// ... existing code ... except ImportError: # Fall back to psycopg2cffi try: from psycopg2cffi import compat compat.register() except ImportError: # Hope we are not testing against PostgreSQL :) pass // ... rest of the code ...
391c1681eaeabfdbe65a64a1bb8b05beca30141e
wqflask/utility/db_tools.py
wqflask/utility/db_tools.py
from MySQLdb import escape_string as escape def create_in_clause(items): """Create an in clause for mysql""" in_clause = ', '.join("'{}'".format(x) for x in mescape(*items)) in_clause = '( {} )'.format(in_clause) return in_clause def mescape(*items): """Multiple escape""" escaped = [escape(str(item)) for item in items] #print("escaped is:", escaped) return escaped
from MySQLdb import escape_string as escape_ def create_in_clause(items): """Create an in clause for mysql""" in_clause = ', '.join("'{}'".format(x) for x in mescape(*items)) in_clause = '( {} )'.format(in_clause) return in_clause def mescape(*items): """Multiple escape""" return [escape_(str(item)).decode('utf8') for item in items] def escape(string_): return escape_(string_).decode('utf8')
Add global method to convert binary string to plain string
Add global method to convert binary string to plain string * wqflask/utility/db_tools.py: escape_string returns a binary string which introduces a bug when composing sql query string. The escaped strings have to be converted to plain text.
Python
agpl-3.0
pjotrp/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2
- from MySQLdb import escape_string as escape + from MySQLdb import escape_string as escape_ + def create_in_clause(items): """Create an in clause for mysql""" in_clause = ', '.join("'{}'".format(x) for x in mescape(*items)) in_clause = '( {} )'.format(in_clause) return in_clause + def mescape(*items): """Multiple escape""" + return [escape_(str(item)).decode('utf8') for item in items] - escaped = [escape(str(item)) for item in items] - #print("escaped is:", escaped) - return escaped + + def escape(string_): + return escape_(string_).decode('utf8') +
Add global method to convert binary string to plain string
## Code Before: from MySQLdb import escape_string as escape def create_in_clause(items): """Create an in clause for mysql""" in_clause = ', '.join("'{}'".format(x) for x in mescape(*items)) in_clause = '( {} )'.format(in_clause) return in_clause def mescape(*items): """Multiple escape""" escaped = [escape(str(item)) for item in items] #print("escaped is:", escaped) return escaped ## Instruction: Add global method to convert binary string to plain string ## Code After: from MySQLdb import escape_string as escape_ def create_in_clause(items): """Create an in clause for mysql""" in_clause = ', '.join("'{}'".format(x) for x in mescape(*items)) in_clause = '( {} )'.format(in_clause) return in_clause def mescape(*items): """Multiple escape""" return [escape_(str(item)).decode('utf8') for item in items] def escape(string_): return escape_(string_).decode('utf8')
... from MySQLdb import escape_string as escape_ def create_in_clause(items): ... return in_clause def mescape(*items): """Multiple escape""" return [escape_(str(item)).decode('utf8') for item in items] def escape(string_): return escape_(string_).decode('utf8') ...
7fb46ddf6bab9d32908c8fb9c859fd8151fbd089
qipr/registry/forms/facet_form.py
qipr/registry/forms/facet_form.py
from registry.models import * from operator import attrgetter related_by_projects_Models = [ BigAim, ClinicalArea, ClinicalSetting, Descriptor, ] class FacetForm: def __init__(self): self.facet_categories = [model.__name__ for model in related_by_projects_Models] for model in related_by_projects_Models: models = list(model.objects.all()) models.sort(key=lambda m : m.projects.count(), reverse=True) setattr(self, model.__name__, models) def get_display(self, facet_category): displays = { 'BigAim': 'Big Aim', 'ClinicalArea': 'Clinical Area', 'ClinicalSetting': 'Clinical Setting', 'Descriptor': 'MeSH Keyword', } return displays[facet_category]
from registry.models import * from operator import attrgetter related_by_projects_Models = [ BigAim, ClinicalArea, ClinicalSetting, Descriptor, ] class FacetForm: def __init__(self): self.facet_categories = [model.__name__ for model in related_by_projects_Models] for model in related_by_projects_Models: models = list(model.objects.all()) models.sort(key=lambda m : m.__str__(), reverse=False) setattr(self, model.__name__, models) def get_display(self, facet_category): displays = { 'BigAim': 'Big Aim', 'ClinicalArea': 'Clinical Area', 'ClinicalSetting': 'Clinical Setting', 'Descriptor': 'MeSH Keyword', } return displays[facet_category]
Change the facet to sort by name instead of project count
Change the facet to sort by name instead of project count
Python
apache-2.0
ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr
from registry.models import * from operator import attrgetter related_by_projects_Models = [ BigAim, ClinicalArea, ClinicalSetting, Descriptor, ] class FacetForm: def __init__(self): self.facet_categories = [model.__name__ for model in related_by_projects_Models] for model in related_by_projects_Models: models = list(model.objects.all()) - models.sort(key=lambda m : m.projects.count(), reverse=True) + models.sort(key=lambda m : m.__str__(), reverse=False) setattr(self, model.__name__, models) def get_display(self, facet_category): displays = { 'BigAim': 'Big Aim', 'ClinicalArea': 'Clinical Area', 'ClinicalSetting': 'Clinical Setting', 'Descriptor': 'MeSH Keyword', } return displays[facet_category]
Change the facet to sort by name instead of project count
## Code Before: from registry.models import * from operator import attrgetter related_by_projects_Models = [ BigAim, ClinicalArea, ClinicalSetting, Descriptor, ] class FacetForm: def __init__(self): self.facet_categories = [model.__name__ for model in related_by_projects_Models] for model in related_by_projects_Models: models = list(model.objects.all()) models.sort(key=lambda m : m.projects.count(), reverse=True) setattr(self, model.__name__, models) def get_display(self, facet_category): displays = { 'BigAim': 'Big Aim', 'ClinicalArea': 'Clinical Area', 'ClinicalSetting': 'Clinical Setting', 'Descriptor': 'MeSH Keyword', } return displays[facet_category] ## Instruction: Change the facet to sort by name instead of project count ## Code After: from registry.models import * from operator import attrgetter related_by_projects_Models = [ BigAim, ClinicalArea, ClinicalSetting, Descriptor, ] class FacetForm: def __init__(self): self.facet_categories = [model.__name__ for model in related_by_projects_Models] for model in related_by_projects_Models: models = list(model.objects.all()) models.sort(key=lambda m : m.__str__(), reverse=False) setattr(self, model.__name__, models) def get_display(self, facet_category): displays = { 'BigAim': 'Big Aim', 'ClinicalArea': 'Clinical Area', 'ClinicalSetting': 'Clinical Setting', 'Descriptor': 'MeSH Keyword', } return displays[facet_category]
# ... existing code ... for model in related_by_projects_Models: models = list(model.objects.all()) models.sort(key=lambda m : m.__str__(), reverse=False) setattr(self, model.__name__, models) # ... rest of the code ...
d89e43c649aba78ac9722ca39f9e0c67be0cc897
precision/accounts/models.py
precision/accounts/models.py
from django.db import models # Create your models here.
from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class SchoolAdministrator(AbstractUser): pass
Add an simple abstract user model for school administrators which will be used later
Add an simple abstract user model for school administrators which will be used later
Python
mit
FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management
+ from django.contrib.auth.models import AbstractUser from django.db import models + from django.utils.translation import ugettext_lazy as _ - # Create your models here. + class SchoolAdministrator(AbstractUser): + pass +
Add an simple abstract user model for school administrators which will be used later
## Code Before: from django.db import models # Create your models here. ## Instruction: Add an simple abstract user model for school administrators which will be used later ## Code After: from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class SchoolAdministrator(AbstractUser): pass
# ... existing code ... from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import ugettext_lazy as _ class SchoolAdministrator(AbstractUser): pass # ... rest of the code ...
12fbf40ce5ffaab44c7a602925230e0c2d96b9b0
cameo/strain_design/heuristic/observers.py
cameo/strain_design/heuristic/observers.py
from __future__ import absolute_import, print_function from cameo.visualization import ProgressBar class ProgressObserver(): """ Progress bar to in command line """ __name__ = "Progress Observer" def __init__(self): self.progress = None def __call__(self, population, num_generations, num_evaluations, args): if self.progress is None: self.max_evaluations = args.get('max_evaluations', 50000) self.progress = ProgressBar() self.progress.start() if num_evaluations % args.get('n', 1) == 0: if num_evaluations < self.max_evaluations: self.progress.update(self.max_evaluations) else: self.progress.update(num_evaluations) def reset(self): self.progress = None def end(self): self.progress.end()
from __future__ import absolute_import, print_function from cameo.visualization import ProgressBar class ProgressObserver(): """ Progress bar to in command line """ __name__ = "Progress Observer" def __init__(self): self.progress = None def __call__(self, population, num_generations, num_evaluations, args): if self.progress is None: self.max_evaluations = args.get('max_evaluations', 50000) self.progress = ProgressBar(self.max_evaluations) self.progress.start() if num_evaluations % args.get('n', 1) == 0: if num_evaluations > self.max_evaluations: self.progress.update(self.max_evaluations) else: self.progress.update(num_evaluations) def reset(self): self.progress = None def end(self): self.progress.end()
Fix the bug fix. Now is really fixed.
Fix the bug fix. Now is really fixed.
Python
apache-2.0
biosustain/cameo,biosustain/cameo,KristianJensen/cameo
from __future__ import absolute_import, print_function from cameo.visualization import ProgressBar class ProgressObserver(): """ Progress bar to in command line """ __name__ = "Progress Observer" def __init__(self): self.progress = None def __call__(self, population, num_generations, num_evaluations, args): if self.progress is None: self.max_evaluations = args.get('max_evaluations', 50000) - self.progress = ProgressBar() + self.progress = ProgressBar(self.max_evaluations) self.progress.start() if num_evaluations % args.get('n', 1) == 0: - if num_evaluations < self.max_evaluations: + if num_evaluations > self.max_evaluations: self.progress.update(self.max_evaluations) else: self.progress.update(num_evaluations) def reset(self): self.progress = None def end(self): self.progress.end()
Fix the bug fix. Now is really fixed.
## Code Before: from __future__ import absolute_import, print_function from cameo.visualization import ProgressBar class ProgressObserver(): """ Progress bar to in command line """ __name__ = "Progress Observer" def __init__(self): self.progress = None def __call__(self, population, num_generations, num_evaluations, args): if self.progress is None: self.max_evaluations = args.get('max_evaluations', 50000) self.progress = ProgressBar() self.progress.start() if num_evaluations % args.get('n', 1) == 0: if num_evaluations < self.max_evaluations: self.progress.update(self.max_evaluations) else: self.progress.update(num_evaluations) def reset(self): self.progress = None def end(self): self.progress.end() ## Instruction: Fix the bug fix. Now is really fixed. ## Code After: from __future__ import absolute_import, print_function from cameo.visualization import ProgressBar class ProgressObserver(): """ Progress bar to in command line """ __name__ = "Progress Observer" def __init__(self): self.progress = None def __call__(self, population, num_generations, num_evaluations, args): if self.progress is None: self.max_evaluations = args.get('max_evaluations', 50000) self.progress = ProgressBar(self.max_evaluations) self.progress.start() if num_evaluations % args.get('n', 1) == 0: if num_evaluations > self.max_evaluations: self.progress.update(self.max_evaluations) else: self.progress.update(num_evaluations) def reset(self): self.progress = None def end(self): self.progress.end()
# ... existing code ... if self.progress is None: self.max_evaluations = args.get('max_evaluations', 50000) self.progress = ProgressBar(self.max_evaluations) self.progress.start() if num_evaluations % args.get('n', 1) == 0: if num_evaluations > self.max_evaluations: self.progress.update(self.max_evaluations) else: # ... rest of the code ...
f5747773e05fc892883c852e495f9e166888d1ea
rapt/connection.py
rapt/connection.py
import os import getpass from urlparse import urlparse import keyring from vr.common.models import Velociraptor def auth_domain(url): hostname = urlparse(url).hostname _, _, default_domain = hostname.partition('.') return default_domain def set_password(url, username): hostname = auth_domain(url) or 'localhost' password = keyring.get_password(hostname, username) if not password: prompt_tmpl = "{username}@{hostname}'s password: " prompt = prompt_tmpl.format(username=username, hostname=hostname) password = getpass.getpass(prompt) keyring.set_password(hostname, username, password) def get_vr(username=None): username = os.environ['VELOCIRAPTOR_USERNAME'] base = os.environ['VELOCIRAPTOR_URL'] set_password(base, username) return Velociraptor(base=base, username=username)
import os import getpass from urlparse import urlparse import keyring from vr.common.models import Velociraptor def auth_domain(url): hostname = urlparse(url).hostname _, _, default_domain = hostname.partition('.') return default_domain def set_password(url, username): hostname = auth_domain(url) or 'localhost' os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname password = keyring.get_password(hostname, username) if not password: prompt_tmpl = "{username}@{hostname}'s password: " prompt = prompt_tmpl.format(username=username, hostname=hostname) password = getpass.getpass(prompt) keyring.set_password(hostname, username, password) def get_vr(username=None): username = os.environ['VELOCIRAPTOR_USERNAME'] base = os.environ['VELOCIRAPTOR_URL'] set_password(base, username) return Velociraptor(base=base, username=username)
Set the hostname when it localhost
Set the hostname when it localhost
Python
bsd-3-clause
yougov/rapt,yougov/rapt
import os import getpass from urlparse import urlparse import keyring from vr.common.models import Velociraptor def auth_domain(url): hostname = urlparse(url).hostname _, _, default_domain = hostname.partition('.') return default_domain def set_password(url, username): hostname = auth_domain(url) or 'localhost' + os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname password = keyring.get_password(hostname, username) if not password: prompt_tmpl = "{username}@{hostname}'s password: " prompt = prompt_tmpl.format(username=username, hostname=hostname) password = getpass.getpass(prompt) keyring.set_password(hostname, username, password) def get_vr(username=None): username = os.environ['VELOCIRAPTOR_USERNAME'] base = os.environ['VELOCIRAPTOR_URL'] set_password(base, username) return Velociraptor(base=base, username=username)
Set the hostname when it localhost
## Code Before: import os import getpass from urlparse import urlparse import keyring from vr.common.models import Velociraptor def auth_domain(url): hostname = urlparse(url).hostname _, _, default_domain = hostname.partition('.') return default_domain def set_password(url, username): hostname = auth_domain(url) or 'localhost' password = keyring.get_password(hostname, username) if not password: prompt_tmpl = "{username}@{hostname}'s password: " prompt = prompt_tmpl.format(username=username, hostname=hostname) password = getpass.getpass(prompt) keyring.set_password(hostname, username, password) def get_vr(username=None): username = os.environ['VELOCIRAPTOR_USERNAME'] base = os.environ['VELOCIRAPTOR_URL'] set_password(base, username) return Velociraptor(base=base, username=username) ## Instruction: Set the hostname when it localhost ## Code After: import os import getpass from urlparse import urlparse import keyring from vr.common.models import Velociraptor def auth_domain(url): hostname = urlparse(url).hostname _, _, default_domain = hostname.partition('.') return default_domain def set_password(url, username): hostname = auth_domain(url) or 'localhost' os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname password = keyring.get_password(hostname, username) if not password: prompt_tmpl = "{username}@{hostname}'s password: " prompt = prompt_tmpl.format(username=username, hostname=hostname) password = getpass.getpass(prompt) keyring.set_password(hostname, username, password) def get_vr(username=None): username = os.environ['VELOCIRAPTOR_USERNAME'] base = os.environ['VELOCIRAPTOR_URL'] set_password(base, username) return Velociraptor(base=base, username=username)
... def set_password(url, username): hostname = auth_domain(url) or 'localhost' os.environ['VELOCIRAPTOR_AUTH_DOMAIN'] = hostname password = keyring.get_password(hostname, username) ...
ab10f3d134065047a7260662d3c39295904795b8
migration/versions/001_initial_migration.py
migration/versions/001_initial_migration.py
from __future__ import print_function from getpass import getpass import readline import sys from sqlalchemy import * from migrate import * from migrate.changeset.constraint import ForeignKeyConstraint import annotateit from annotateit import db from annotateit.model import Consumer, User meta = MetaData() consumer = Table('consumer', meta, Column('id', Integer, primary_key=True, nullable=False), Column('key', String), Column('secret', String), Column('ttl', Integer), Column('created_at', DateTime), Column('updated_at', DateTime), Column('user_id', Integer), ) user = Table('user', meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String), Column('email', String), Column('password_hash', String), Column('created_at', DateTime), Column('updated_at', DateTime), ) consumer_user_id_fkey = ForeignKeyConstraint([consumer.c.user_id], [user.c.id]) def upgrade(migrate_engine): meta.bind = migrate_engine consumer.create() user.create() consumer_user_id_fkey.create() def downgrade(migrate_engine): meta.bind = migrate_engine consumer_user_id_fkey.create() user.drop() consumer.drop()
from sqlalchemy import * from migrate import * import annotateit from annotateit import db from annotateit.model import Consumer, User meta = MetaData() consumer = Table('consumer', meta, Column('id', Integer, primary_key=True, nullable=False), Column('key', String), Column('secret', String), Column('ttl', Integer), Column('created_at', DateTime), Column('updated_at', DateTime), Column('user_id', Integer, ForeignKey('user.id')), ) user = Table('user', meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String), Column('email', String), Column('password_hash', String), Column('created_at', DateTime), Column('updated_at', DateTime), ) def upgrade(migrate_engine): meta.bind = migrate_engine user.create() consumer.create() def downgrade(migrate_engine): meta.bind = migrate_engine consumer.drop() user.drop()
Add fkey constraints at the same time
Add fkey constraints at the same time
Python
agpl-3.0
openannotation/annotateit,openannotation/annotateit
- from __future__ import print_function - from getpass import getpass - import readline - import sys - from sqlalchemy import * from migrate import * - from migrate.changeset.constraint import ForeignKeyConstraint import annotateit from annotateit import db from annotateit.model import Consumer, User meta = MetaData() consumer = Table('consumer', meta, Column('id', Integer, primary_key=True, nullable=False), Column('key', String), Column('secret', String), Column('ttl', Integer), Column('created_at', DateTime), Column('updated_at', DateTime), - Column('user_id', Integer), + Column('user_id', Integer, ForeignKey('user.id')), ) user = Table('user', meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String), Column('email', String), Column('password_hash', String), Column('created_at', DateTime), Column('updated_at', DateTime), ) - consumer_user_id_fkey = ForeignKeyConstraint([consumer.c.user_id], [user.c.id]) - def upgrade(migrate_engine): meta.bind = migrate_engine + user.create() consumer.create() - user.create() - consumer_user_id_fkey.create() def downgrade(migrate_engine): meta.bind = migrate_engine - consumer_user_id_fkey.create() + consumer.drop() user.drop() - consumer.drop()
Add fkey constraints at the same time
## Code Before: from __future__ import print_function from getpass import getpass import readline import sys from sqlalchemy import * from migrate import * from migrate.changeset.constraint import ForeignKeyConstraint import annotateit from annotateit import db from annotateit.model import Consumer, User meta = MetaData() consumer = Table('consumer', meta, Column('id', Integer, primary_key=True, nullable=False), Column('key', String), Column('secret', String), Column('ttl', Integer), Column('created_at', DateTime), Column('updated_at', DateTime), Column('user_id', Integer), ) user = Table('user', meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String), Column('email', String), Column('password_hash', String), Column('created_at', DateTime), Column('updated_at', DateTime), ) consumer_user_id_fkey = ForeignKeyConstraint([consumer.c.user_id], [user.c.id]) def upgrade(migrate_engine): meta.bind = migrate_engine consumer.create() user.create() consumer_user_id_fkey.create() def downgrade(migrate_engine): meta.bind = migrate_engine consumer_user_id_fkey.create() user.drop() consumer.drop() ## Instruction: Add fkey constraints at the same time ## Code After: from sqlalchemy import * from migrate import * import annotateit from annotateit import db from annotateit.model import Consumer, User meta = MetaData() consumer = Table('consumer', meta, Column('id', Integer, primary_key=True, nullable=False), Column('key', String), Column('secret', String), Column('ttl', Integer), Column('created_at', DateTime), Column('updated_at', DateTime), Column('user_id', Integer, ForeignKey('user.id')), ) user = Table('user', meta, Column('id', Integer, primary_key=True, nullable=False), Column('username', String), Column('email', String), Column('password_hash', String), Column('created_at', DateTime), Column('updated_at', DateTime), ) def upgrade(migrate_engine): meta.bind = migrate_engine user.create() consumer.create() def downgrade(migrate_engine): meta.bind = migrate_engine consumer.drop() user.drop()
# ... existing code ... from sqlalchemy import * from migrate import * import annotateit # ... modified code ... Column('created_at', DateTime), Column('updated_at', DateTime), Column('user_id', Integer, ForeignKey('user.id')), ) ... ) def upgrade(migrate_engine): meta.bind = migrate_engine user.create() consumer.create() def downgrade(migrate_engine): meta.bind = migrate_engine consumer.drop() user.drop() # ... rest of the code ...
0c6a5c55df5680bd8589f1040f2f16cf6aac86b3
openprescribing/frontend/migrations/0030_add_ccg_centroids.py
openprescribing/frontend/migrations/0030_add_ccg_centroids.py
from __future__ import unicode_literals from django.db import migrations from frontend.management.commands.import_ccg_boundaries import set_centroids import django.contrib.gis.db.models.fields def set_centroids_without_args(*args): set_centroids() class Migration(migrations.Migration): dependencies = [ ('frontend', '0031_auto_20171004_1330'), ] operations = [ migrations.AddField( model_name='pct', name='centroid', field=django.contrib.gis.db.models.fields.PointField( blank=True, null=True, srid=4326), ), # This is now commented out because the SQL generated to execute # set_centroids_without_args includes a reference to fiels which aren't # created until migration 36. # migrations.RunPython(set_centroids_without_args), ]
from __future__ import unicode_literals from django.db import migrations from frontend.management.commands.import_ccg_boundaries import set_centroids import django.contrib.gis.db.models.fields def set_centroids_without_args(*args): set_centroids() class Migration(migrations.Migration): dependencies = [ ('frontend', '0031_auto_20171004_1330'), ] operations = [ migrations.AddField( model_name='pct', name='centroid', field=django.contrib.gis.db.models.fields.PointField( blank=True, null=True, srid=4326), ), ]
Remove commented-out RunPython from migration
Remove commented-out RunPython from migration
Python
mit
ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing
from __future__ import unicode_literals from django.db import migrations from frontend.management.commands.import_ccg_boundaries import set_centroids import django.contrib.gis.db.models.fields def set_centroids_without_args(*args): set_centroids() class Migration(migrations.Migration): dependencies = [ ('frontend', '0031_auto_20171004_1330'), ] operations = [ migrations.AddField( model_name='pct', name='centroid', field=django.contrib.gis.db.models.fields.PointField( blank=True, null=True, srid=4326), ), - - # This is now commented out because the SQL generated to execute - # set_centroids_without_args includes a reference to fiels which aren't - # created until migration 36. - - # migrations.RunPython(set_centroids_without_args), ]
Remove commented-out RunPython from migration
## Code Before: from __future__ import unicode_literals from django.db import migrations from frontend.management.commands.import_ccg_boundaries import set_centroids import django.contrib.gis.db.models.fields def set_centroids_without_args(*args): set_centroids() class Migration(migrations.Migration): dependencies = [ ('frontend', '0031_auto_20171004_1330'), ] operations = [ migrations.AddField( model_name='pct', name='centroid', field=django.contrib.gis.db.models.fields.PointField( blank=True, null=True, srid=4326), ), # This is now commented out because the SQL generated to execute # set_centroids_without_args includes a reference to fiels which aren't # created until migration 36. # migrations.RunPython(set_centroids_without_args), ] ## Instruction: Remove commented-out RunPython from migration ## Code After: from __future__ import unicode_literals from django.db import migrations from frontend.management.commands.import_ccg_boundaries import set_centroids import django.contrib.gis.db.models.fields def set_centroids_without_args(*args): set_centroids() class Migration(migrations.Migration): dependencies = [ ('frontend', '0031_auto_20171004_1330'), ] operations = [ migrations.AddField( model_name='pct', name='centroid', field=django.contrib.gis.db.models.fields.PointField( blank=True, null=True, srid=4326), ), ]
# ... existing code ... blank=True, null=True, srid=4326), ), ] # ... rest of the code ...
cd9b2e375587fdf0bc6b2d61a983ca40e6680218
osf/migrations/0139_rename_aspredicted_schema.py
osf/migrations/0139_rename_aspredicted_schema.py
from __future__ import unicode_literals from django.db import migrations from osf.models import RegistrationSchema OLD_NAME = 'AsPredicted Preregistration' NEW_NAME = 'Preregistration Template from AsPredicted.org' def rename_schema(from_name, to_name): try: schema = RegistrationSchema.objects.get(name=from_name) except RegistrationSchema.DoesNotExist: return schema.name = to_name schema.schema['name'] = to_name schema.schema['title'] = to_name schema.schema['pages'][0]['title'] = to_name return schema.save() def rename_aspredicted_schema(*args, **kwargs): return rename_schema(OLD_NAME, NEW_NAME) def undo_aspredicted_rename(*args, **kwargs): return rename_schema(NEW_NAME, OLD_NAME) class Migration(migrations.Migration): dependencies = [ ('osf', '0138_merge_20181012_1944'), ] operations = [ migrations.RunPython(rename_aspredicted_schema, undo_aspredicted_rename) ]
from __future__ import unicode_literals from django.db import migrations OLD_NAME = 'AsPredicted Preregistration' NEW_NAME = 'Preregistration Template from AsPredicted.org' def rename_schema(model, from_name, to_name): try: schema = model.objects.get(name=from_name) except model.DoesNotExist: return schema.name = to_name schema.schema['name'] = to_name schema.schema['title'] = to_name schema.schema['pages'][0]['title'] = to_name return schema.save() def rename_aspredicted_schema(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, OLD_NAME, NEW_NAME) def undo_aspredicted_rename(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, NEW_NAME, OLD_NAME) class Migration(migrations.Migration): dependencies = [ ('osf', '0138_merge_20181012_1944'), ] operations = [ migrations.RunPython(rename_aspredicted_schema, undo_aspredicted_rename) ]
Migrate with model from app state - Not from app code
Migrate with model from app state - Not from app code
Python
apache-2.0
adlius/osf.io,mattclark/osf.io,cslzchen/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,felliott/osf.io,pattisdr/osf.io,mfraezz/osf.io,adlius/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,felliott/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,saradbowman/osf.io,HalcyonChimera/osf.io,cslzchen/osf.io,cslzchen/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,felliott/osf.io,HalcyonChimera/osf.io,pattisdr/osf.io,CenterForOpenScience/osf.io,mattclark/osf.io,saradbowman/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,aaxelb/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,adlius/osf.io,HalcyonChimera/osf.io,mfraezz/osf.io,felliott/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,baylee-d/osf.io,Johnetordoff/osf.io
from __future__ import unicode_literals from django.db import migrations - from osf.models import RegistrationSchema OLD_NAME = 'AsPredicted Preregistration' NEW_NAME = 'Preregistration Template from AsPredicted.org' - def rename_schema(from_name, to_name): + def rename_schema(model, from_name, to_name): try: - schema = RegistrationSchema.objects.get(name=from_name) + schema = model.objects.get(name=from_name) - except RegistrationSchema.DoesNotExist: + except model.DoesNotExist: return schema.name = to_name schema.schema['name'] = to_name schema.schema['title'] = to_name schema.schema['pages'][0]['title'] = to_name return schema.save() - def rename_aspredicted_schema(*args, **kwargs): + def rename_aspredicted_schema(state, schema): + RegistrationSchema = state.get_model('osf.registrationschema') - return rename_schema(OLD_NAME, NEW_NAME) + return rename_schema(RegistrationSchema, OLD_NAME, NEW_NAME) - def undo_aspredicted_rename(*args, **kwargs): + def undo_aspredicted_rename(state, schema): + RegistrationSchema = state.get_model('osf.registrationschema') - return rename_schema(NEW_NAME, OLD_NAME) + return rename_schema(RegistrationSchema, NEW_NAME, OLD_NAME) class Migration(migrations.Migration): dependencies = [ ('osf', '0138_merge_20181012_1944'), ] operations = [ migrations.RunPython(rename_aspredicted_schema, undo_aspredicted_rename) ]
Migrate with model from app state - Not from app code
## Code Before: from __future__ import unicode_literals from django.db import migrations from osf.models import RegistrationSchema OLD_NAME = 'AsPredicted Preregistration' NEW_NAME = 'Preregistration Template from AsPredicted.org' def rename_schema(from_name, to_name): try: schema = RegistrationSchema.objects.get(name=from_name) except RegistrationSchema.DoesNotExist: return schema.name = to_name schema.schema['name'] = to_name schema.schema['title'] = to_name schema.schema['pages'][0]['title'] = to_name return schema.save() def rename_aspredicted_schema(*args, **kwargs): return rename_schema(OLD_NAME, NEW_NAME) def undo_aspredicted_rename(*args, **kwargs): return rename_schema(NEW_NAME, OLD_NAME) class Migration(migrations.Migration): dependencies = [ ('osf', '0138_merge_20181012_1944'), ] operations = [ migrations.RunPython(rename_aspredicted_schema, undo_aspredicted_rename) ] ## Instruction: Migrate with model from app state - Not from app code ## Code After: from __future__ import unicode_literals from django.db import migrations OLD_NAME = 'AsPredicted Preregistration' NEW_NAME = 'Preregistration Template from AsPredicted.org' def rename_schema(model, from_name, to_name): try: schema = model.objects.get(name=from_name) except model.DoesNotExist: return schema.name = to_name schema.schema['name'] = to_name schema.schema['title'] = to_name schema.schema['pages'][0]['title'] = to_name return schema.save() def rename_aspredicted_schema(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, OLD_NAME, NEW_NAME) def undo_aspredicted_rename(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, NEW_NAME, OLD_NAME) class Migration(migrations.Migration): dependencies = [ ('osf', '0138_merge_20181012_1944'), ] operations = [ migrations.RunPython(rename_aspredicted_schema, undo_aspredicted_rename) ]
# ... existing code ... from django.db import migrations OLD_NAME = 'AsPredicted Preregistration' # ... modified code ... NEW_NAME = 'Preregistration Template from AsPredicted.org' def rename_schema(model, from_name, to_name): try: schema = model.objects.get(name=from_name) except model.DoesNotExist: return ... return schema.save() def rename_aspredicted_schema(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, OLD_NAME, NEW_NAME) def undo_aspredicted_rename(state, schema): RegistrationSchema = state.get_model('osf.registrationschema') return rename_schema(RegistrationSchema, NEW_NAME, OLD_NAME) class Migration(migrations.Migration): # ... rest of the code ...
6ff6bdad9f7544be103e798838c12509411a2098
tests/__init__.py
tests/__init__.py
import logging from unittest import TestCase import datetime from redash import settings settings.DATABASE_CONFIG = { 'name': 'circle_test', 'threadlocals': True } settings.REDIS_URL = "redis://localhost:6379/5" from redash import models, redis_connection logging.getLogger('peewee').setLevel(logging.INFO) class BaseTestCase(TestCase): def setUp(self): models.create_db(True, True) models.init_db() def tearDown(self): models.db.close_db(None) models.create_db(False, True) redis_connection.flushdb() def assertResponseEqual(self, expected, actual): for k, v in expected.iteritems(): if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime): continue if isinstance(v, list): continue if isinstance(v, dict): self.assertResponseEqual(v, actual[k]) continue self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
import os os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5" import logging from unittest import TestCase import datetime from redash import settings settings.DATABASE_CONFIG = { 'name': 'circle_test', 'threadlocals': True } from redash import models, redis_connection logging.getLogger('peewee').setLevel(logging.INFO) class BaseTestCase(TestCase): def setUp(self): models.create_db(True, True) models.init_db() def tearDown(self): models.db.close_db(None) models.create_db(False, True) redis_connection.flushdb() def assertResponseEqual(self, expected, actual): for k, v in expected.iteritems(): if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime): continue if isinstance(v, list): continue if isinstance(v, dict): self.assertResponseEqual(v, actual[k]) continue self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
Use the correct redis connection in tests
Use the correct redis connection in tests
Python
bsd-2-clause
guaguadev/redash,vishesh92/redash,easytaxibr/redash,guaguadev/redash,pubnative/redash,M32Media/redash,vishesh92/redash,rockwotj/redash,amino-data/redash,pubnative/redash,chriszs/redash,alexanderlz/redash,stefanseifert/redash,vishesh92/redash,hudl/redash,ninneko/redash,easytaxibr/redash,akariv/redash,denisov-vlad/redash,denisov-vlad/redash,M32Media/redash,crowdworks/redash,imsally/redash,ninneko/redash,crowdworks/redash,getredash/redash,imsally/redash,chriszs/redash,guaguadev/redash,useabode/redash,imsally/redash,akariv/redash,44px/redash,easytaxibr/redash,useabode/redash,chriszs/redash,easytaxibr/redash,easytaxibr/redash,rockwotj/redash,moritz9/redash,vishesh92/redash,akariv/redash,getredash/redash,denisov-vlad/redash,useabode/redash,chriszs/redash,useabode/redash,stefanseifert/redash,getredash/redash,pubnative/redash,44px/redash,guaguadev/redash,getredash/redash,alexanderlz/redash,rockwotj/redash,stefanseifert/redash,crowdworks/redash,rockwotj/redash,denisov-vlad/redash,jmvasquez/redashtest,jmvasquez/redashtest,crowdworks/redash,EverlyWell/redash,amino-data/redash,amino-data/redash,44px/redash,pubnative/redash,hudl/redash,EverlyWell/redash,jmvasquez/redashtest,M32Media/redash,hudl/redash,alexanderlz/redash,pubnative/redash,stefanseifert/redash,ninneko/redash,akariv/redash,getredash/redash,stefanseifert/redash,imsally/redash,M32Media/redash,alexanderlz/redash,ninneko/redash,denisov-vlad/redash,akariv/redash,jmvasquez/redashtest,EverlyWell/redash,hudl/redash,ninneko/redash,moritz9/redash,moritz9/redash,guaguadev/redash,amino-data/redash,44px/redash,EverlyWell/redash,moritz9/redash,jmvasquez/redashtest
+ import os + os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5" + import logging from unittest import TestCase import datetime from redash import settings + settings.DATABASE_CONFIG = { 'name': 'circle_test', 'threadlocals': True } - - settings.REDIS_URL = "redis://localhost:6379/5" from redash import models, redis_connection logging.getLogger('peewee').setLevel(logging.INFO) class BaseTestCase(TestCase): def setUp(self): models.create_db(True, True) models.init_db() def tearDown(self): models.db.close_db(None) models.create_db(False, True) redis_connection.flushdb() def assertResponseEqual(self, expected, actual): for k, v in expected.iteritems(): if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime): continue if isinstance(v, list): continue if isinstance(v, dict): self.assertResponseEqual(v, actual[k]) continue self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
Use the correct redis connection in tests
## Code Before: import logging from unittest import TestCase import datetime from redash import settings settings.DATABASE_CONFIG = { 'name': 'circle_test', 'threadlocals': True } settings.REDIS_URL = "redis://localhost:6379/5" from redash import models, redis_connection logging.getLogger('peewee').setLevel(logging.INFO) class BaseTestCase(TestCase): def setUp(self): models.create_db(True, True) models.init_db() def tearDown(self): models.db.close_db(None) models.create_db(False, True) redis_connection.flushdb() def assertResponseEqual(self, expected, actual): for k, v in expected.iteritems(): if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime): continue if isinstance(v, list): continue if isinstance(v, dict): self.assertResponseEqual(v, actual[k]) continue self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k])) ## Instruction: Use the correct redis connection in tests ## Code After: import os os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5" import logging from unittest import TestCase import datetime from redash import settings settings.DATABASE_CONFIG = { 'name': 'circle_test', 'threadlocals': True } from redash import models, redis_connection logging.getLogger('peewee').setLevel(logging.INFO) class BaseTestCase(TestCase): def setUp(self): models.create_db(True, True) models.init_db() def tearDown(self): models.db.close_db(None) models.create_db(False, True) redis_connection.flushdb() def assertResponseEqual(self, expected, actual): for k, v in expected.iteritems(): if isinstance(v, datetime.datetime) or isinstance(actual[k], datetime.datetime): continue if isinstance(v, list): continue if isinstance(v, dict): self.assertResponseEqual(v, actual[k]) continue self.assertEqual(v, actual[k], "{} not equal (expected: {}, actual: {}).".format(k, v, actual[k]))
# ... existing code ... import os os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5" import logging from unittest import TestCase # ... modified code ... import datetime from redash import settings settings.DATABASE_CONFIG = { 'name': 'circle_test', ... 'threadlocals': True } from redash import models, redis_connection # ... rest of the code ...
bb347838ad78d61e6a81a1c14657323ad7eeb82b
analysis/smooth-data.py
analysis/smooth-data.py
import climate import database @climate.annotate( root='load data files from this directory tree', output='save smoothed data files to this directory tree', accuracy=('fit SVT with this accuracy', 'option', None, float), threshold=('SVT threshold', 'option', None, float), frames=('number of frames for SVT', 'option', None, int), ) def main(root, output, accuracy=0.005, threshold=1000, frames=5): for trial in database.Experiment(root).trials_matching('*'): t.reindex() t.svt(threshold, accuracy, frames) t.save(t.root.replace(root, output)) if __name__ == '__main__': climate.call(main)
import climate import database @climate.annotate( root='load data files from this directory tree', output='save smoothed data files to this directory tree', frame_rate=('reindex frames to this rate', 'option', None, float), accuracy=('fit SVT with this accuracy', 'option', None, float), threshold=('SVT threshold', 'option', None, float), frames=('number of frames for SVT', 'option', None, int), ) def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5): for t in database.Experiment(root).trials_matching('*'): t.reindex(frame_rate=frame_rate) t.svt(threshold, accuracy, frames) t.save(t.root.replace(root, output)) if __name__ == '__main__': climate.call(main)
Add parameter for frame rate.
Add parameter for frame rate.
Python
mit
lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment
import climate import database @climate.annotate( root='load data files from this directory tree', output='save smoothed data files to this directory tree', + frame_rate=('reindex frames to this rate', 'option', None, float), accuracy=('fit SVT with this accuracy', 'option', None, float), threshold=('SVT threshold', 'option', None, float), frames=('number of frames for SVT', 'option', None, int), ) - def main(root, output, accuracy=0.005, threshold=1000, frames=5): + def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5): - for trial in database.Experiment(root).trials_matching('*'): + for t in database.Experiment(root).trials_matching('*'): - t.reindex() + t.reindex(frame_rate=frame_rate) t.svt(threshold, accuracy, frames) t.save(t.root.replace(root, output)) if __name__ == '__main__': climate.call(main)
Add parameter for frame rate.
## Code Before: import climate import database @climate.annotate( root='load data files from this directory tree', output='save smoothed data files to this directory tree', accuracy=('fit SVT with this accuracy', 'option', None, float), threshold=('SVT threshold', 'option', None, float), frames=('number of frames for SVT', 'option', None, int), ) def main(root, output, accuracy=0.005, threshold=1000, frames=5): for trial in database.Experiment(root).trials_matching('*'): t.reindex() t.svt(threshold, accuracy, frames) t.save(t.root.replace(root, output)) if __name__ == '__main__': climate.call(main) ## Instruction: Add parameter for frame rate. ## Code After: import climate import database @climate.annotate( root='load data files from this directory tree', output='save smoothed data files to this directory tree', frame_rate=('reindex frames to this rate', 'option', None, float), accuracy=('fit SVT with this accuracy', 'option', None, float), threshold=('SVT threshold', 'option', None, float), frames=('number of frames for SVT', 'option', None, int), ) def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5): for t in database.Experiment(root).trials_matching('*'): t.reindex(frame_rate=frame_rate) t.svt(threshold, accuracy, frames) t.save(t.root.replace(root, output)) if __name__ == '__main__': climate.call(main)
# ... existing code ... root='load data files from this directory tree', output='save smoothed data files to this directory tree', frame_rate=('reindex frames to this rate', 'option', None, float), accuracy=('fit SVT with this accuracy', 'option', None, float), threshold=('SVT threshold', 'option', None, float), # ... modified code ... frames=('number of frames for SVT', 'option', None, int), ) def main(root, output, frame_rate=100., accuracy=0.002, threshold=100, frames=5): for t in database.Experiment(root).trials_matching('*'): t.reindex(frame_rate=frame_rate) t.svt(threshold, accuracy, frames) t.save(t.root.replace(root, output)) # ... rest of the code ...
a499f5fbe63f03a3c404a28e0c1286af74382e09
tests/utils.py
tests/utils.py
import os from django.core.files.base import ContentFile from imagekit.lib import Image, StringIO from .models import Photo import pickle def get_image_file(): """ See also: http://en.wikipedia.org/wiki/Lenna http://sipi.usc.edu/database/database.php?volume=misc&image=12 """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') tmp = StringIO() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp def create_image(): return Image.open(get_image_file()) def create_instance(model_class, image_name): instance = model_class() img = get_image_file() file = ContentFile(img.read()) instance.original_image = file instance.original_image.save(image_name, file) instance.save() img.close() return instance def create_photo(name): return create_instance(Photo, name) def pickleback(obj): pickled = StringIO() pickle.dump(obj, pickled) pickled.seek(0) return pickle.load(pickled)
import os from django.core.files.base import ContentFile from imagekit.lib import Image, StringIO from tempfile import NamedTemporaryFile from .models import Photo import pickle def _get_image_file(file_factory): """ See also: http://en.wikipedia.org/wiki/Lenna http://sipi.usc.edu/database/database.php?volume=misc&image=12 """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') tmp = file_factory() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp def get_image_file(): return _get_image_file(StringIO) def get_named_image_file(): return _get_image_file(NamedTemporaryFile) def create_image(): return Image.open(get_image_file()) def create_instance(model_class, image_name): instance = model_class() img = get_image_file() file = ContentFile(img.read()) instance.original_image = file instance.original_image.save(image_name, file) instance.save() img.close() return instance def create_photo(name): return create_instance(Photo, name) def pickleback(obj): pickled = StringIO() pickle.dump(obj, pickled) pickled.seek(0) return pickle.load(pickled)
Add util for generating named image file
Add util for generating named image file
Python
bsd-3-clause
FundedByMe/django-imagekit,tawanda/django-imagekit,tawanda/django-imagekit,FundedByMe/django-imagekit
import os from django.core.files.base import ContentFile from imagekit.lib import Image, StringIO + from tempfile import NamedTemporaryFile from .models import Photo import pickle - def get_image_file(): + def _get_image_file(file_factory): """ See also: http://en.wikipedia.org/wiki/Lenna http://sipi.usc.edu/database/database.php?volume=misc&image=12 """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') - tmp = StringIO() + tmp = file_factory() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp + + + def get_image_file(): + return _get_image_file(StringIO) + + + def get_named_image_file(): + return _get_image_file(NamedTemporaryFile) def create_image(): return Image.open(get_image_file()) def create_instance(model_class, image_name): instance = model_class() img = get_image_file() file = ContentFile(img.read()) instance.original_image = file instance.original_image.save(image_name, file) instance.save() img.close() return instance def create_photo(name): return create_instance(Photo, name) def pickleback(obj): pickled = StringIO() pickle.dump(obj, pickled) pickled.seek(0) return pickle.load(pickled)
Add util for generating named image file
## Code Before: import os from django.core.files.base import ContentFile from imagekit.lib import Image, StringIO from .models import Photo import pickle def get_image_file(): """ See also: http://en.wikipedia.org/wiki/Lenna http://sipi.usc.edu/database/database.php?volume=misc&image=12 """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') tmp = StringIO() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp def create_image(): return Image.open(get_image_file()) def create_instance(model_class, image_name): instance = model_class() img = get_image_file() file = ContentFile(img.read()) instance.original_image = file instance.original_image.save(image_name, file) instance.save() img.close() return instance def create_photo(name): return create_instance(Photo, name) def pickleback(obj): pickled = StringIO() pickle.dump(obj, pickled) pickled.seek(0) return pickle.load(pickled) ## Instruction: Add util for generating named image file ## Code After: import os from django.core.files.base import ContentFile from imagekit.lib import Image, StringIO from tempfile import NamedTemporaryFile from .models import Photo import pickle def _get_image_file(file_factory): """ See also: http://en.wikipedia.org/wiki/Lenna http://sipi.usc.edu/database/database.php?volume=misc&image=12 """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') tmp = file_factory() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp def get_image_file(): return _get_image_file(StringIO) def get_named_image_file(): return _get_image_file(NamedTemporaryFile) def create_image(): return Image.open(get_image_file()) def create_instance(model_class, image_name): instance = model_class() img = get_image_file() file = ContentFile(img.read()) instance.original_image = file instance.original_image.save(image_name, file) instance.save() img.close() return instance def create_photo(name): return create_instance(Photo, name) def pickleback(obj): pickled = StringIO() pickle.dump(obj, pickled) pickled.seek(0) return pickle.load(pickled)
... from imagekit.lib import Image, StringIO from tempfile import NamedTemporaryFile from .models import Photo import pickle ... def _get_image_file(file_factory): """ See also: ... """ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets', 'lenna-800x600-white-border.jpg') tmp = file_factory() tmp.write(open(path, 'r+b').read()) tmp.seek(0) return tmp def get_image_file(): return _get_image_file(StringIO) def get_named_image_file(): return _get_image_file(NamedTemporaryFile) ...
aec36263dac9037afa0343dcef87ae97530e1ad3
semanticizest/_semanticizer.py
semanticizest/_semanticizer.py
from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): targets.sort(key=operator.itemgetter(1)) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) targets = ((t, count / total) for t, count in targets) self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): # targets.sort(key=operator.itemgetter(1), reverse=True) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) commonness[anchor] = [(t, count / total) for t, count in targets] self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
Return commonness instead of raw counts
Return commonness instead of raw counts
Python
apache-2.0
semanticize/semanticizest
from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): - targets.sort(key=operator.itemgetter(1)) + # targets.sort(key=operator.itemgetter(1), reverse=True) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) - targets = ((t, count / total) for t, count in targets) + commonness[anchor] = [(t, count / total) for t, count in targets] self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
Return commonness instead of raw counts
## Code Before: from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): targets.sort(key=operator.itemgetter(1)) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) targets = ((t, count / total) for t, count in targets) self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob ## Instruction: Return commonness instead of raw counts ## Code After: from collections import defaultdict import operator import six from semanticizest._util import ngrams_with_pos, tosequence class Semanticizer(object): def __init__(self, link_count, N=7): commonness = defaultdict(list) for (target, anchor), count in six.iteritems(link_count): commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): # targets.sort(key=operator.itemgetter(1), reverse=True) # Turn counts into probabilities. # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) commonness[anchor] = [(t, count / total) for t, count in targets] self.commonness = commonness self.N = N def all_candidates(self, s): """Retrieve all candidate entities. Parameters ---------- s : {string, iterable over string} Tokens. If a string, it will be tokenized using a naive heuristic. Returns ------- candidates : iterable over (int, int, string, float) Candidate entities: 4-tuples of start index, end index (both in tokenized input), target entity and probability (commonness). """ if isinstance(s, six.string_types): # XXX need a smarter tokenizer! s = s.split() else: s = tosequence(s) for i, j, s in ngrams_with_pos(s, self.N): if s in self.commonness: for target, prob in self.commonness[s]: yield i, j, target, prob
# ... existing code ... commonness[anchor].append((target, count)) for anchor, targets in six.iteritems(commonness): # targets.sort(key=operator.itemgetter(1), reverse=True) # Turn counts into probabilities. # ... modified code ... # XXX should we preserve the counts as well? total = float(sum(count for _, count in targets)) commonness[anchor] = [(t, count / total) for t, count in targets] self.commonness = commonness # ... rest of the code ...
4db2d879cb8ee7d8ddd1543e6aed50f40e44ca66
src/pi/scanning_proxy.py
src/pi/scanning_proxy.py
"""Philips hue proxy code.""" import abc import logging import sys import threading from pi import proxy class ScanningProxy(proxy.Proxy): """A proxy object with a background scan thread.""" __metaclass__ = abc.ABCMeta def __init__(self, refresh_period): self._refresh_period = refresh_period self._exiting = False self._scan_thread_condition = threading.Condition() self._scan_thread = threading.Thread(target=self._scan) self._scan_thread.daemon = True self._scan_thread.start() @proxy.command def scan(self): with self._scan_thread_condition: self._scan_thread_condition.notify() def _scan(self): """Loop thread for scanning.""" while not self._exiting: # We always do a scan on start up. try: self._scan_once() except: logging.error('Error during %s scan', self.__class__.__name__, exc_info=sys.exc_info()) with self._scan_thread_condition: self._scan_thread_condition.wait(self._refresh_period) if self._exiting: break logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod def _scan_once(self): pass def stop(self): self._exiting = True self.scan() self._scan_thread.join()
"""Philips hue proxy code.""" import abc import logging import sys import threading from pi import proxy class ScanningProxy(proxy.Proxy): """A proxy object with a background scan thread.""" __metaclass__ = abc.ABCMeta def __init__(self, refresh_period): self._refresh_period = refresh_period self._exiting = False self._scan_thread_condition = threading.Condition() self._scan_thread = threading.Thread(target=self._scan) self._scan_thread.daemon = True self._scan_thread.start() @proxy.command def scan(self): with self._scan_thread_condition: self._scan_thread_condition.notify() def _scan(self): """Loop thread for scanning.""" while not self._exiting: # We always do a scan on start up. try: self._scan_once() except: logging.error('Error during %s scan', self.__class__.__name__, exc_info=sys.exc_info()) with self._scan_thread_condition: if not self._exiting: self._scan_thread_condition.wait(self._refresh_period) if self._exiting: break logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod def _scan_once(self): pass def stop(self): with self._scan_thread_condition: self._exiting = True self._scan_thread_condition.notify() self._scan_thread.join()
Fix race on exit in scanning proxy.
Fix race on exit in scanning proxy.
Python
mit
tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation,tomwilkie/awesomation
"""Philips hue proxy code.""" import abc import logging import sys import threading from pi import proxy class ScanningProxy(proxy.Proxy): """A proxy object with a background scan thread.""" __metaclass__ = abc.ABCMeta def __init__(self, refresh_period): self._refresh_period = refresh_period self._exiting = False self._scan_thread_condition = threading.Condition() self._scan_thread = threading.Thread(target=self._scan) self._scan_thread.daemon = True self._scan_thread.start() @proxy.command def scan(self): with self._scan_thread_condition: self._scan_thread_condition.notify() def _scan(self): """Loop thread for scanning.""" while not self._exiting: # We always do a scan on start up. try: self._scan_once() except: logging.error('Error during %s scan', self.__class__.__name__, exc_info=sys.exc_info()) with self._scan_thread_condition: + if not self._exiting: - self._scan_thread_condition.wait(self._refresh_period) + self._scan_thread_condition.wait(self._refresh_period) + if self._exiting: break + logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod def _scan_once(self): pass def stop(self): + with self._scan_thread_condition: - self._exiting = True + self._exiting = True - self.scan() + self._scan_thread_condition.notify() self._scan_thread.join()
Fix race on exit in scanning proxy.
## Code Before: """Philips hue proxy code.""" import abc import logging import sys import threading from pi import proxy class ScanningProxy(proxy.Proxy): """A proxy object with a background scan thread.""" __metaclass__ = abc.ABCMeta def __init__(self, refresh_period): self._refresh_period = refresh_period self._exiting = False self._scan_thread_condition = threading.Condition() self._scan_thread = threading.Thread(target=self._scan) self._scan_thread.daemon = True self._scan_thread.start() @proxy.command def scan(self): with self._scan_thread_condition: self._scan_thread_condition.notify() def _scan(self): """Loop thread for scanning.""" while not self._exiting: # We always do a scan on start up. try: self._scan_once() except: logging.error('Error during %s scan', self.__class__.__name__, exc_info=sys.exc_info()) with self._scan_thread_condition: self._scan_thread_condition.wait(self._refresh_period) if self._exiting: break logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod def _scan_once(self): pass def stop(self): self._exiting = True self.scan() self._scan_thread.join() ## Instruction: Fix race on exit in scanning proxy. ## Code After: """Philips hue proxy code.""" import abc import logging import sys import threading from pi import proxy class ScanningProxy(proxy.Proxy): """A proxy object with a background scan thread.""" __metaclass__ = abc.ABCMeta def __init__(self, refresh_period): self._refresh_period = refresh_period self._exiting = False self._scan_thread_condition = threading.Condition() self._scan_thread = threading.Thread(target=self._scan) self._scan_thread.daemon = True self._scan_thread.start() @proxy.command def scan(self): with self._scan_thread_condition: self._scan_thread_condition.notify() def _scan(self): """Loop thread for scanning.""" while not self._exiting: # We always do a scan on start up. try: self._scan_once() except: logging.error('Error during %s scan', self.__class__.__name__, exc_info=sys.exc_info()) with self._scan_thread_condition: if not self._exiting: self._scan_thread_condition.wait(self._refresh_period) if self._exiting: break logging.info('Exiting %s scan thread', self.__class__.__name__) @abc.abstractmethod def _scan_once(self): pass def stop(self): with self._scan_thread_condition: self._exiting = True self._scan_thread_condition.notify() self._scan_thread.join()
// ... existing code ... with self._scan_thread_condition: if not self._exiting: self._scan_thread_condition.wait(self._refresh_period) if self._exiting: break logging.info('Exiting %s scan thread', self.__class__.__name__) // ... modified code ... def stop(self): with self._scan_thread_condition: self._exiting = True self._scan_thread_condition.notify() self._scan_thread.join() // ... rest of the code ...
201d8d532b907d97823c2dbf61fdd6e75b8eb615
form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py
form_designer/contrib/cms_plugins/form_designer_form/cms_plugins.py
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
Disable caching for CMS plugin.
Disable caching for CMS plugin. CSRF tokens may get cached otherwise. This is for compatibility with Django CMS 3.0+.
Python
bsd-3-clause
andersinno/django-form-designer-ai,andersinno/django-form-designer,kcsry/django-form-designer,andersinno/django-form-designer,kcsry/django-form-designer,andersinno/django-form-designer-ai
from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False + cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
Disable caching for CMS plugin.
## Code Before: from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin) ## Instruction: Disable caching for CMS plugin. ## Code After: from form_designer.contrib.cms_plugins.form_designer_form.models import CMSFormDefinition from form_designer.views import process_form from form_designer import settings from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import ugettext as _ class FormDesignerPlugin(CMSPluginBase): model = CMSFormDefinition module = _('Form Designer') name = _('Form') admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): if instance.form_definition.form_template_name: self.render_template = instance.form_definition.form_template_name else: self.render_template = settings.DEFAULT_FORM_TEMPLATE # Redirection does not work with CMS plugin, hence disable: return process_form(context['request'], instance.form_definition, context, disable_redirection=True, push_messages=False) plugin_pool.register_plugin(FormDesignerPlugin)
// ... existing code ... admin_preview = False render_template = False cache = False # New in version 3.0. see http://django-cms.readthedocs.org/en/latest/advanced/caching.html def render(self, context, instance, placeholder): // ... rest of the code ...
5161d6c0023151d39fb56a85f739063205e676f4
nova/api/manager.py
nova/api/manager.py
from nova import manager from nova.network import driver class MetadataManager(manager.Manager): """Metadata Manager. This class manages the Metadata API service initialization. Currently, it just adds an iptables filter rule for the metadata service. """ def __init__(self, *args, **kwargs): super(MetadataManager, self).__init__(*args, **kwargs) self.network_driver = driver.load_network_driver() def init_host(self): """Perform any initialization. Currently, we only add an iptables filter rule for the metadata service. """ self.network_driver.metadata_accept()
from nova import manager from nova.network import driver class MetadataManager(manager.Manager): """Metadata Manager. This class manages the Metadata API service initialization. Currently, it just adds an iptables filter rule for the metadata service. """ def __init__(self, *args, **kwargs): super(MetadataManager, self).__init__(*args, **kwargs) self.network_driver = driver.load_network_driver() self.network_driver.metadata_accept()
Initialize iptables rules on initialization of MetadataManager
Initialize iptables rules on initialization of MetadataManager To avoid multiple initialization of iptables rules if there are a few workers for metadata service, perform iptables configuration in __init__() of MetadataManager. Change-Id: I674c04f973318f06cbb98693f0a884c824af8748 Closes-Bug: #1097999
Python
apache-2.0
noironetworks/nova,orbitfp7/nova,eayunstack/nova,badock/nova,JioCloud/nova,CEG-FYP-OpenStack/scheduler,badock/nova,mikalstill/nova,gooddata/openstack-nova,LoHChina/nova,rahulunair/nova,jeffrey4l/nova,shahar-stratoscale/nova,vmturbo/nova,scripnichenko/nova,mandeepdhami/nova,cyx1231st/nova,felixma/nova,luogangyi/bcec-nova,leilihh/nova,vmturbo/nova,devoid/nova,Tehsmash/nova,viggates/nova,blueboxgroup/nova,akash1808/nova,alexandrucoman/vbox-nova-driver,takeshineshiro/nova,kimjaejoong/nova,ruslanloman/nova,klmitch/nova,ewindisch/nova,orbitfp7/nova,alvarolopez/nova,openstack/nova,devendermishrajio/nova_test_latest,iuliat/nova,TwinkleChawla/nova,eharney/nova,mahak/nova,watonyweng/nova,mgagne/nova,edulramirez/nova,phenoxim/nova,alvarolopez/nova,akash1808/nova,double12gzh/nova,devendermishrajio/nova,CiscoSystems/nova,NeCTAR-RC/nova,eayunstack/nova,gooddata/openstack-nova,leilihh/novaha,joker946/nova,iuliat/nova,dawnpower/nova,takeshineshiro/nova,j-carpentier/nova,yosshy/nova,bgxavier/nova,angdraug/nova,maelnor/nova,silenceli/nova,Juniper/nova,jianghuaw/nova,cernops/nova,bigswitch/nova,BeyondTheClouds/nova,leilihh/nova,Francis-Liu/animated-broccoli,yatinkumbhare/openstack-nova,ewindisch/nova,blueboxgroup/nova,BeyondTheClouds/nova,nikesh-mahalka/nova,BeyondTheClouds/nova,mikalstill/nova,barnsnake351/nova,cloudbase/nova,petrutlucian94/nova,saleemjaveds/https-github.com-openstack-nova,shail2810/nova,yosshy/nova,CloudServer/nova,cloudbase/nova-virtualbox,rajalokan/nova,tianweizhang/nova,rrader/nova-docker-plugin,vmturbo/nova,rrader/nova-docker-plugin,adelina-t/nova,Juniper/nova,viggates/nova,LoHChina/nova,angdraug/nova,rajalokan/nova,Yusuke1987/openstack_template,redhat-openstack/nova,devoid/nova,apporc/nova,klmitch/nova,ted-gould/nova,cloudbase/nova,devendermishrajio/nova_test_latest,dawnpower/nova,jeffrey4l/nova,belmiromoreira/nova,rajalokan/nova,thomasem/nova,CCI-MOC/nova,gooddata/openstack-nova,vladikr/nova_drafts,virtualopensystems/nova,projectcalico/calico-nova,Stavitsky/nova,Tehsmash/nova,sacharya/nova,cernops/nova,affo/nova,adelina-t/nova,Juniper/nova,CloudServer/nova,silenceli/nova,varunarya10/nova_test_latest,berrange/nova,shahar-stratoscale/nova,bigswitch/nova,thomasem/nova,akash1808/nova_test_latest,fnordahl/nova,isyippee/nova,hanlind/nova,virtualopensystems/nova,alaski/nova,spring-week-topos/nova-week,MountainWei/nova,noironetworks/nova,Francis-Liu/animated-broccoli,hanlind/nova,alaski/nova,joker946/nova,vmturbo/nova,jianghuaw/nova,JianyuWang/nova,leilihh/novaha,nikesh-mahalka/nova,tangfeixiong/nova,devendermishrajio/nova,openstack/nova,akash1808/nova_test_latest,eonpatapon/nova,cloudbase/nova-virtualbox,luogangyi/bcec-nova,eharney/nova,zzicewind/nova,mahak/nova,spring-week-topos/nova-week,dims/nova,tangfeixiong/nova,tanglei528/nova,cernops/nova,Metaswitch/calico-nova,scripnichenko/nova,NeCTAR-RC/nova,vladikr/nova_drafts,varunarya10/nova_test_latest,zaina/nova,MountainWei/nova,klmitch/nova,double12gzh/nova,yatinkumbhare/openstack-nova,JioCloud/nova_test_latest,whitepages/nova,mikalstill/nova,dims/nova,mandeepdhami/nova,Juniper/nova,phenoxim/nova,zhimin711/nova,isyippee/nova,apporc/nova,alexandrucoman/vbox-nova-driver,watonyweng/nova,Metaswitch/calico-nova,OpenAcademy-OpenStack/nova-scheduler,raildo/nova,raildo/nova,fnordahl/nova,CCI-MOC/nova,TwinkleChawla/nova,barnsnake351/nova,cyx1231st/nova,ted-gould/nova,gooddata/openstack-nova,zhimin711/nova,petrutlucian94/nova_dev,kimjaejoong/nova,sebrandon1/nova,shail2810/nova,rajalokan/nova,tealover/nova,tudorvio/nova,mgagne/nova,felixma/nova,saleemjaveds/https-github.com-openstack-nova,jianghuaw/nova,projectcalico/calico-nova,maelnor/nova,sacharya/nova,mmnelemane/nova,JioCloud/nova,tianweizhang/nova,belmiromoreira/nova,sebrandon1/nova,openstack/nova,eonpatapon/nova,mahak/nova,JianyuWang/nova,CiscoSystems/nova,bgxavier/nova,OpenAcademy-OpenStack/nova-scheduler,redhat-openstack/nova,whitepages/nova,petrutlucian94/nova_dev,tealover/nova,zaina/nova,affo/nova,tudorvio/nova,rahulunair/nova,sebrandon1/nova,CEG-FYP-OpenStack/scheduler,Stavitsky/nova,klmitch/nova,edulramirez/nova,zzicewind/nova,ruslanloman/nova,jianghuaw/nova,berrange/nova,petrutlucian94/nova,JioCloud/nova_test_latest,rahulunair/nova,tanglei528/nova,hanlind/nova,j-carpentier/nova,Yusuke1987/openstack_template,cloudbase/nova,mmnelemane/nova
from nova import manager from nova.network import driver class MetadataManager(manager.Manager): """Metadata Manager. This class manages the Metadata API service initialization. Currently, it just adds an iptables filter rule for the metadata service. """ def __init__(self, *args, **kwargs): super(MetadataManager, self).__init__(*args, **kwargs) self.network_driver = driver.load_network_driver() - - def init_host(self): - """Perform any initialization. - - Currently, we only add an iptables filter rule for the metadata - service. - """ self.network_driver.metadata_accept()
Initialize iptables rules on initialization of MetadataManager
## Code Before: from nova import manager from nova.network import driver class MetadataManager(manager.Manager): """Metadata Manager. This class manages the Metadata API service initialization. Currently, it just adds an iptables filter rule for the metadata service. """ def __init__(self, *args, **kwargs): super(MetadataManager, self).__init__(*args, **kwargs) self.network_driver = driver.load_network_driver() def init_host(self): """Perform any initialization. Currently, we only add an iptables filter rule for the metadata service. """ self.network_driver.metadata_accept() ## Instruction: Initialize iptables rules on initialization of MetadataManager ## Code After: from nova import manager from nova.network import driver class MetadataManager(manager.Manager): """Metadata Manager. This class manages the Metadata API service initialization. Currently, it just adds an iptables filter rule for the metadata service. """ def __init__(self, *args, **kwargs): super(MetadataManager, self).__init__(*args, **kwargs) self.network_driver = driver.load_network_driver() self.network_driver.metadata_accept()
# ... existing code ... super(MetadataManager, self).__init__(*args, **kwargs) self.network_driver = driver.load_network_driver() self.network_driver.metadata_accept() # ... rest of the code ...
ce04fc96bf6653419acb81db0f1894934517f33b
fireplace/cards/blackrock/collectible.py
fireplace/cards/blackrock/collectible.py
from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] # Imp Gang Boss class BRM_006: events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] ## # Spells # Solemn Vigil class BRM_001: action = [Draw(CONTROLLER) * 2] def cost(self, value): return value - self.game.minionsKilledThisTurn # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn # Demonwrath class BRM_005: action = [Hit(ALL_MINIONS - DEMON, 2)]
from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] # Imp Gang Boss class BRM_006: events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] # Dark Iron Skulker class BRM_008: action = [Hit(ENEMY_MINIONS - DAMAGED, 2)] # Volcanic Lumberer class BRM_009: def cost(self, value): return value - self.game.minionsKilledThisTurn ## # Spells # Solemn Vigil class BRM_001: action = [Draw(CONTROLLER) * 2] def cost(self, value): return value - self.game.minionsKilledThisTurn # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn # Demonwrath class BRM_005: action = [Hit(ALL_MINIONS - DEMON, 2)]
Implement Dark Iron Skulker and Volcanic Lumberer
Implement Dark Iron Skulker and Volcanic Lumberer
Python
agpl-3.0
oftc-ftw/fireplace,NightKev/fireplace,Meerkov/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,liujimj/fireplace,oftc-ftw/fireplace,Ragowit/fireplace,Ragowit/fireplace,Meerkov/fireplace,amw2104/fireplace,amw2104/fireplace,jleclanche/fireplace,liujimj/fireplace,beheh/fireplace,butozerca/fireplace,butozerca/fireplace
from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] # Imp Gang Boss class BRM_006: events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] + + + # Dark Iron Skulker + class BRM_008: + action = [Hit(ENEMY_MINIONS - DAMAGED, 2)] + + + # Volcanic Lumberer + class BRM_009: + def cost(self, value): + return value - self.game.minionsKilledThisTurn ## # Spells # Solemn Vigil class BRM_001: action = [Draw(CONTROLLER) * 2] def cost(self, value): return value - self.game.minionsKilledThisTurn # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn # Demonwrath class BRM_005: action = [Hit(ALL_MINIONS - DEMON, 2)]
Implement Dark Iron Skulker and Volcanic Lumberer
## Code Before: from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] # Imp Gang Boss class BRM_006: events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] ## # Spells # Solemn Vigil class BRM_001: action = [Draw(CONTROLLER) * 2] def cost(self, value): return value - self.game.minionsKilledThisTurn # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn # Demonwrath class BRM_005: action = [Hit(ALL_MINIONS - DEMON, 2)] ## Instruction: Implement Dark Iron Skulker and Volcanic Lumberer ## Code After: from ..utils import * ## # Minions # Flamewaker class BRM_002: events = [ OWN_SPELL_PLAY.after(Hit(RANDOM_ENEMY_MINION, 1) * 2) ] # Imp Gang Boss class BRM_006: events = [ Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] # Dark Iron Skulker class BRM_008: action = [Hit(ENEMY_MINIONS - DAMAGED, 2)] # Volcanic Lumberer class BRM_009: def cost(self, value): return value - self.game.minionsKilledThisTurn ## # Spells # Solemn Vigil class BRM_001: action = [Draw(CONTROLLER) * 2] def cost(self, value): return value - self.game.minionsKilledThisTurn # Dragon's Breath class BRM_003: action = [Hit(TARGET, 4)] def cost(self, value): return value - self.game.minionsKilledThisTurn # Demonwrath class BRM_005: action = [Hit(ALL_MINIONS - DEMON, 2)]
// ... existing code ... Damage(SELF).on(Summon(CONTROLLER, "BRM_006t")) ] # Dark Iron Skulker class BRM_008: action = [Hit(ENEMY_MINIONS - DAMAGED, 2)] # Volcanic Lumberer class BRM_009: def cost(self, value): return value - self.game.minionsKilledThisTurn // ... rest of the code ...
47c2936e65d00a08896b4e60060ff737b7a2f675
app/tests/workstations_tests/test_migrations.py
app/tests/workstations_tests/test_migrations.py
import pytest from django.db import connection from django.db.migrations.executor import MigrationExecutor @pytest.mark.django_db(transaction=True) def test_workstation_group_migration(): executor = MigrationExecutor(connection) app = "workstations" migrate_from = [(app, "0001_initial")] migrate_to = [(app, "0004_auto_20190813_1302")] executor.migrate(migrate_from) old_apps = executor.loader.project_state(migrate_from).apps Workstation = old_apps.get_model(app, "Workstation") old_ws = Workstation.objects.create(title="foo") assert not hasattr(old_ws, "editors_group") assert not hasattr(old_ws, "users_group") # Reload executor.loader.build_graph() # Migrate forwards executor.migrate(migrate_to) new_apps = executor.loader.project_state(migrate_to).apps Workstation = new_apps.get_model(app, "Workstation") new_ws = Workstation.objects.get(title="foo") assert new_ws.editors_group assert new_ws.users_group assert new_ws.slug == old_ws.slug assert new_ws.title == old_ws.title
import pytest from django.db import connection from django.db.migrations.executor import MigrationExecutor from guardian.shortcuts import get_perms from grandchallenge.workstations.models import Workstation from tests.factories import UserFactory @pytest.mark.django_db(transaction=True) def test_workstation_group_migration(): executor = MigrationExecutor(connection) app = "workstations" migrate_from = [(app, "0001_initial")] migrate_to = [(app, "0004_auto_20190813_1302")] executor.migrate(migrate_from) old_apps = executor.loader.project_state(migrate_from).apps user = UserFactory() OldWorkstation = old_apps.get_model(app, "Workstation") old_ws = OldWorkstation.objects.create(title="foo") assert not hasattr(old_ws, "editors_group") assert not hasattr(old_ws, "users_group") # Reload executor.loader.build_graph() # Migrate forwards executor.migrate(migrate_to) new_ws = Workstation.objects.get(title="foo") new_ws.add_user(user=user) assert new_ws.editors_group assert new_ws.users_group assert new_ws.slug == old_ws.slug assert new_ws.title == old_ws.title assert "view_workstation" in get_perms(user, new_ws)
Check that the permission migrations work
Check that the permission migrations work
Python
apache-2.0
comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django
import pytest from django.db import connection from django.db.migrations.executor import MigrationExecutor + from guardian.shortcuts import get_perms + + from grandchallenge.workstations.models import Workstation + from tests.factories import UserFactory @pytest.mark.django_db(transaction=True) def test_workstation_group_migration(): executor = MigrationExecutor(connection) app = "workstations" migrate_from = [(app, "0001_initial")] migrate_to = [(app, "0004_auto_20190813_1302")] executor.migrate(migrate_from) old_apps = executor.loader.project_state(migrate_from).apps + user = UserFactory() - Workstation = old_apps.get_model(app, "Workstation") + OldWorkstation = old_apps.get_model(app, "Workstation") - old_ws = Workstation.objects.create(title="foo") + old_ws = OldWorkstation.objects.create(title="foo") assert not hasattr(old_ws, "editors_group") assert not hasattr(old_ws, "users_group") # Reload executor.loader.build_graph() # Migrate forwards executor.migrate(migrate_to) - new_apps = executor.loader.project_state(migrate_to).apps - - Workstation = new_apps.get_model(app, "Workstation") new_ws = Workstation.objects.get(title="foo") + new_ws.add_user(user=user) assert new_ws.editors_group assert new_ws.users_group assert new_ws.slug == old_ws.slug assert new_ws.title == old_ws.title + assert "view_workstation" in get_perms(user, new_ws)
Check that the permission migrations work
## Code Before: import pytest from django.db import connection from django.db.migrations.executor import MigrationExecutor @pytest.mark.django_db(transaction=True) def test_workstation_group_migration(): executor = MigrationExecutor(connection) app = "workstations" migrate_from = [(app, "0001_initial")] migrate_to = [(app, "0004_auto_20190813_1302")] executor.migrate(migrate_from) old_apps = executor.loader.project_state(migrate_from).apps Workstation = old_apps.get_model(app, "Workstation") old_ws = Workstation.objects.create(title="foo") assert not hasattr(old_ws, "editors_group") assert not hasattr(old_ws, "users_group") # Reload executor.loader.build_graph() # Migrate forwards executor.migrate(migrate_to) new_apps = executor.loader.project_state(migrate_to).apps Workstation = new_apps.get_model(app, "Workstation") new_ws = Workstation.objects.get(title="foo") assert new_ws.editors_group assert new_ws.users_group assert new_ws.slug == old_ws.slug assert new_ws.title == old_ws.title ## Instruction: Check that the permission migrations work ## Code After: import pytest from django.db import connection from django.db.migrations.executor import MigrationExecutor from guardian.shortcuts import get_perms from grandchallenge.workstations.models import Workstation from tests.factories import UserFactory @pytest.mark.django_db(transaction=True) def test_workstation_group_migration(): executor = MigrationExecutor(connection) app = "workstations" migrate_from = [(app, "0001_initial")] migrate_to = [(app, "0004_auto_20190813_1302")] executor.migrate(migrate_from) old_apps = executor.loader.project_state(migrate_from).apps user = UserFactory() OldWorkstation = old_apps.get_model(app, "Workstation") old_ws = OldWorkstation.objects.create(title="foo") assert not hasattr(old_ws, "editors_group") assert not hasattr(old_ws, "users_group") # Reload executor.loader.build_graph() # Migrate forwards executor.migrate(migrate_to) new_ws = Workstation.objects.get(title="foo") new_ws.add_user(user=user) assert new_ws.editors_group assert new_ws.users_group assert new_ws.slug == old_ws.slug assert new_ws.title == old_ws.title assert "view_workstation" in get_perms(user, new_ws)
// ... existing code ... from django.db import connection from django.db.migrations.executor import MigrationExecutor from guardian.shortcuts import get_perms from grandchallenge.workstations.models import Workstation from tests.factories import UserFactory // ... modified code ... old_apps = executor.loader.project_state(migrate_from).apps user = UserFactory() OldWorkstation = old_apps.get_model(app, "Workstation") old_ws = OldWorkstation.objects.create(title="foo") assert not hasattr(old_ws, "editors_group") ... executor.migrate(migrate_to) new_ws = Workstation.objects.get(title="foo") new_ws.add_user(user=user) assert new_ws.editors_group ... assert new_ws.slug == old_ws.slug assert new_ws.title == old_ws.title assert "view_workstation" in get_perms(user, new_ws) // ... rest of the code ...
5aa55190bae3657e09f6c2fbdedb9ab71210fad5
cocktails/drinks/models.py
cocktails/drinks/models.py
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
Remove 0.0 from ings line
Remove 0.0 from ings line
Python
mit
jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails,jake-jake-jake/cocktails
from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): + if self.amt == 0: + return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
Remove 0.0 from ings line
## Code Before: from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name ## Instruction: Remove 0.0 from ings line ## Code After: from django.db import models # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=100) abv = models.FloatField() type = models.CharField(max_length=25) def __str__(self): return self.name class Admin: list_display = ('name') class Meta: ordering = ['id'] class IngredientLine(models.Model): ing = models.ForeignKey(Ingredient, on_delete=models.CASCADE, default=1) amt = models.FloatField(default=0) def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) class Drink(models.Model): name = models.CharField(max_length=100) owner = models.ForeignKey('auth.User', related_name='drinks') ings = models.ManyToManyField(IngredientLine) instructions = models.TextField() def __str__(self): return self.name
// ... existing code ... def __str__(self): if self.amt == 0: return self.ing.name return "{} ounces of {}".format(str(self.amt), self.ing.name) // ... rest of the code ...
c2fe4483ba70f0ca37b4713a51baf0804a68accd
lms/djangoapps/course_wiki/plugins/markdownedx/wiki_plugin.py
lms/djangoapps/course_wiki/plugins/markdownedx/wiki_plugin.py
from wiki.core.plugins.base import BasePlugin from wiki.core.plugins import registry as plugin_registry from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video class ExtendMarkdownPlugin(BasePlugin): """ This plugin simply loads all of the markdown extensions we use in edX. """ markdown_extensions = [ mdx_mathjax.MathJaxExtension(configs={}), mdx_video.VideoExtension(configs={})] plugin_registry.register(ExtendMarkdownPlugin)
from wiki.core.plugins.base import BasePlugin from wiki.core.plugins import registry as plugin_registry from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video class ExtendMarkdownPlugin(BasePlugin): """ This plugin simply loads all of the markdown extensions we use in edX. """ markdown_extensions = [ mdx_mathjax.MathJaxExtension(configs={}), mdx_video.VideoExtension(configs={}), ] plugin_registry.register(ExtendMarkdownPlugin)
Fix PEP8: E126 continuation line over-indented
Fix PEP8: E126 continuation line over-indented for hanging indent
Python
agpl-3.0
IndonesiaX/edx-platform,mbareta/edx-platform-ft,proversity-org/edx-platform,IONISx/edx-platform,Edraak/edx-platform,doganov/edx-platform,shabab12/edx-platform,lduarte1991/edx-platform,deepsrijit1105/edx-platform,pomegranited/edx-platform,prarthitm/edxplatform,fintech-circle/edx-platform,prarthitm/edxplatform,waheedahmed/edx-platform,xingyepei/edx-platform,jbzdak/edx-platform,louyihua/edx-platform,TeachAtTUM/edx-platform,stvstnfrd/edx-platform,nttks/edx-platform,cognitiveclass/edx-platform,jjmiranda/edx-platform,Endika/edx-platform,antoviaque/edx-platform,JCBarahona/edX,ampax/edx-platform,zubair-arbi/edx-platform,wwj718/edx-platform,bigdatauniversity/edx-platform,zhenzhai/edx-platform,ahmadiga/min_edx,synergeticsedx/deployment-wipro,doganov/edx-platform,waheedahmed/edx-platform,itsjeyd/edx-platform,waheedahmed/edx-platform,solashirai/edx-platform,miptliot/edx-platform,inares/edx-platform,MakeHer/edx-platform,JCBarahona/edX,edx-solutions/edx-platform,bigdatauniversity/edx-platform,teltek/edx-platform,fintech-circle/edx-platform,amir-qayyum-khan/edx-platform,hamzehd/edx-platform,IONISx/edx-platform,caesar2164/edx-platform,Livit/Livit.Learn.EdX,cpennington/edx-platform,defance/edx-platform,stvstnfrd/edx-platform,amir-qayyum-khan/edx-platform,tanmaykm/edx-platform,eduNEXT/edunext-platform,ahmedaljazzar/edx-platform,UOMx/edx-platform,iivic/BoiseStateX,CourseTalk/edx-platform,ovnicraft/edx-platform,kmoocdev2/edx-platform,arbrandes/edx-platform,cpennington/edx-platform,edx-solutions/edx-platform,defance/edx-platform,franosincic/edx-platform,arbrandes/edx-platform,IONISx/edx-platform,arbrandes/edx-platform,halvertoluke/edx-platform,IONISx/edx-platform,Lektorium-LLC/edx-platform,halvertoluke/edx-platform,Edraak/edraak-platform,kmoocdev2/edx-platform,devs1991/test_edx_docmode,simbs/edx-platform,solashirai/edx-platform,Edraak/circleci-edx-platform,marcore/edx-platform,Stanford-Online/edx-platform,Endika/edx-platform,tanmaykm/edx-platform,hamzehd/edx-platform,pomegranited/edx-platform,procangroup/edx-platform,msegado/edx-platform,zubair-arbi/edx-platform,procangroup/edx-platform,deepsrijit1105/edx-platform,nttks/edx-platform,RPI-OPENEDX/edx-platform,appsembler/edx-platform,shurihell/testasia,kursitet/edx-platform,edx-solutions/edx-platform,ahmedaljazzar/edx-platform,zubair-arbi/edx-platform,longmen21/edx-platform,a-parhom/edx-platform,ahmedaljazzar/edx-platform,devs1991/test_edx_docmode,wwj718/edx-platform,jzoldak/edx-platform,cognitiveclass/edx-platform,antoviaque/edx-platform,naresh21/synergetics-edx-platform,edx/edx-platform,gsehub/edx-platform,MakeHer/edx-platform,alexthered/kienhoc-platform,jbzdak/edx-platform,Livit/Livit.Learn.EdX,ahmadiga/min_edx,Edraak/circleci-edx-platform,caesar2164/edx-platform,pabloborrego93/edx-platform,defance/edx-platform,IndonesiaX/edx-platform,cognitiveclass/edx-platform,waheedahmed/edx-platform,wwj718/edx-platform,synergeticsedx/deployment-wipro,stvstnfrd/edx-platform,Endika/edx-platform,alu042/edx-platform,Edraak/edraak-platform,ZLLab-Mooc/edx-platform,CourseTalk/edx-platform,IndonesiaX/edx-platform,longmen21/edx-platform,amir-qayyum-khan/edx-platform,appsembler/edx-platform,romain-li/edx-platform,chrisndodge/edx-platform,lduarte1991/edx-platform,jbzdak/edx-platform,cecep-edu/edx-platform,wwj718/edx-platform,naresh21/synergetics-edx-platform,EDUlib/edx-platform,Lektorium-LLC/edx-platform,ampax/edx-platform,jzoldak/edx-platform,Ayub-Khan/edx-platform,shurihell/testasia,philanthropy-u/edx-platform,antoviaque/edx-platform,alu042/edx-platform,nttks/edx-platform,philanthropy-u/edx-platform,ZLLab-Mooc/edx-platform,BehavioralInsightsTeam/edx-platform,solashirai/edx-platform,franosincic/edx-platform,caesar2164/edx-platform,CredoReference/edx-platform,10clouds/edx-platform,eduNEXT/edx-platform,RPI-OPENEDX/edx-platform,Lektorium-LLC/edx-platform,hastexo/edx-platform,itsjeyd/edx-platform,a-parhom/edx-platform,raccoongang/edx-platform,nttks/edx-platform,jzoldak/edx-platform,mbareta/edx-platform-ft,mcgachey/edx-platform,JCBarahona/edX,pomegranited/edx-platform,marcore/edx-platform,a-parhom/edx-platform,JioEducation/edx-platform,shurihell/testasia,ZLLab-Mooc/edx-platform,bigdatauniversity/edx-platform,teltek/edx-platform,inares/edx-platform,edx/edx-platform,lduarte1991/edx-platform,mcgachey/edx-platform,chrisndodge/edx-platform,synergeticsedx/deployment-wipro,pomegranited/edx-platform,JCBarahona/edX,RPI-OPENEDX/edx-platform,stvstnfrd/edx-platform,appsembler/edx-platform,alexthered/kienhoc-platform,CourseTalk/edx-platform,teltek/edx-platform,Stanford-Online/edx-platform,mbareta/edx-platform-ft,EDUlib/edx-platform,eduNEXT/edunext-platform,prarthitm/edxplatform,longmen21/edx-platform,xingyepei/edx-platform,romain-li/edx-platform,devs1991/test_edx_docmode,cecep-edu/edx-platform,simbs/edx-platform,BehavioralInsightsTeam/edx-platform,cognitiveclass/edx-platform,jolyonb/edx-platform,pepeportela/edx-platform,proversity-org/edx-platform,mbareta/edx-platform-ft,proversity-org/edx-platform,IndonesiaX/edx-platform,iivic/BoiseStateX,cpennington/edx-platform,ZLLab-Mooc/edx-platform,hamzehd/edx-platform,xingyepei/edx-platform,hamzehd/edx-platform,zhenzhai/edx-platform,ESOedX/edx-platform,miptliot/edx-platform,mitocw/edx-platform,eduNEXT/edx-platform,Edraak/circleci-edx-platform,RPI-OPENEDX/edx-platform,jbzdak/edx-platform,JCBarahona/edX,jjmiranda/edx-platform,kursitet/edx-platform,fintech-circle/edx-platform,ampax/edx-platform,edx-solutions/edx-platform,alu042/edx-platform,Edraak/circleci-edx-platform,raccoongang/edx-platform,TeachAtTUM/edx-platform,itsjeyd/edx-platform,ampax/edx-platform,JioEducation/edx-platform,jolyonb/edx-platform,UOMx/edx-platform,ESOedX/edx-platform,hastexo/edx-platform,iivic/BoiseStateX,Stanford-Online/edx-platform,mcgachey/edx-platform,gsehub/edx-platform,proversity-org/edx-platform,angelapper/edx-platform,CredoReference/edx-platform,CredoReference/edx-platform,zubair-arbi/edx-platform,solashirai/edx-platform,romain-li/edx-platform,cecep-edu/edx-platform,Ayub-Khan/edx-platform,franosincic/edx-platform,pepeportela/edx-platform,10clouds/edx-platform,Ayub-Khan/edx-platform,halvertoluke/edx-platform,tanmaykm/edx-platform,appsembler/edx-platform,ZLLab-Mooc/edx-platform,eduNEXT/edunext-platform,gsehub/edx-platform,Edraak/edx-platform,solashirai/edx-platform,inares/edx-platform,angelapper/edx-platform,msegado/edx-platform,RPI-OPENEDX/edx-platform,JioEducation/edx-platform,tanmaykm/edx-platform,kursitet/edx-platform,nttks/edx-platform,pabloborrego93/edx-platform,simbs/edx-platform,longmen21/edx-platform,MakeHer/edx-platform,gymnasium/edx-platform,MakeHer/edx-platform,ovnicraft/edx-platform,a-parhom/edx-platform,shabab12/edx-platform,xingyepei/edx-platform,EDUlib/edx-platform,kmoocdev2/edx-platform,jzoldak/edx-platform,defance/edx-platform,franosincic/edx-platform,philanthropy-u/edx-platform,longmen21/edx-platform,prarthitm/edxplatform,eduNEXT/edx-platform,gsehub/edx-platform,itsjeyd/edx-platform,angelapper/edx-platform,gymnasium/edx-platform,analyseuc3m/ANALYSE-v1,zhenzhai/edx-platform,analyseuc3m/ANALYSE-v1,edx/edx-platform,simbs/edx-platform,devs1991/test_edx_docmode,kmoocdev2/edx-platform,alexthered/kienhoc-platform,Stanford-Online/edx-platform,teltek/edx-platform,msegado/edx-platform,Edraak/edraak-platform,Ayub-Khan/edx-platform,alexthered/kienhoc-platform,pepeportela/edx-platform,bigdatauniversity/edx-platform,mitocw/edx-platform,romain-li/edx-platform,cognitiveclass/edx-platform,waheedahmed/edx-platform,BehavioralInsightsTeam/edx-platform,Edraak/edx-platform,synergeticsedx/deployment-wipro,cecep-edu/edx-platform,deepsrijit1105/edx-platform,Edraak/edx-platform,devs1991/test_edx_docmode,louyihua/edx-platform,Ayub-Khan/edx-platform,procangroup/edx-platform,jolyonb/edx-platform,shurihell/testasia,10clouds/edx-platform,pepeportela/edx-platform,jolyonb/edx-platform,eduNEXT/edx-platform,alexthered/kienhoc-platform,IONISx/edx-platform,TeachAtTUM/edx-platform,antoviaque/edx-platform,gymnasium/edx-platform,cpennington/edx-platform,hamzehd/edx-platform,simbs/edx-platform,MakeHer/edx-platform,jjmiranda/edx-platform,doganov/edx-platform,naresh21/synergetics-edx-platform,ahmedaljazzar/edx-platform,10clouds/edx-platform,chrisndodge/edx-platform,naresh21/synergetics-edx-platform,Livit/Livit.Learn.EdX,cecep-edu/edx-platform,zubair-arbi/edx-platform,deepsrijit1105/edx-platform,ovnicraft/edx-platform,mitocw/edx-platform,ovnicraft/edx-platform,marcore/edx-platform,gymnasium/edx-platform,Edraak/circleci-edx-platform,iivic/BoiseStateX,louyihua/edx-platform,Edraak/edraak-platform,xingyepei/edx-platform,ahmadiga/min_edx,inares/edx-platform,marcore/edx-platform,angelapper/edx-platform,alu042/edx-platform,zhenzhai/edx-platform,procangroup/edx-platform,Endika/edx-platform,TeachAtTUM/edx-platform,jjmiranda/edx-platform,mcgachey/edx-platform,jbzdak/edx-platform,CourseTalk/edx-platform,miptliot/edx-platform,wwj718/edx-platform,ESOedX/edx-platform,raccoongang/edx-platform,pabloborrego93/edx-platform,UOMx/edx-platform,iivic/BoiseStateX,mcgachey/edx-platform,raccoongang/edx-platform,kursitet/edx-platform,eduNEXT/edunext-platform,ahmadiga/min_edx,shabab12/edx-platform,chrisndodge/edx-platform,devs1991/test_edx_docmode,caesar2164/edx-platform,Livit/Livit.Learn.EdX,romain-li/edx-platform,shurihell/testasia,halvertoluke/edx-platform,BehavioralInsightsTeam/edx-platform,halvertoluke/edx-platform,devs1991/test_edx_docmode,JioEducation/edx-platform,pomegranited/edx-platform,msegado/edx-platform,inares/edx-platform,UOMx/edx-platform,hastexo/edx-platform,amir-qayyum-khan/edx-platform,msegado/edx-platform,ESOedX/edx-platform,kursitet/edx-platform,arbrandes/edx-platform,franosincic/edx-platform,ovnicraft/edx-platform,IndonesiaX/edx-platform,pabloborrego93/edx-platform,hastexo/edx-platform,mitocw/edx-platform,doganov/edx-platform,louyihua/edx-platform,bigdatauniversity/edx-platform,doganov/edx-platform,philanthropy-u/edx-platform,zhenzhai/edx-platform,lduarte1991/edx-platform,kmoocdev2/edx-platform,ahmadiga/min_edx,miptliot/edx-platform,Edraak/edx-platform,edx/edx-platform,analyseuc3m/ANALYSE-v1,CredoReference/edx-platform,analyseuc3m/ANALYSE-v1,devs1991/test_edx_docmode,shabab12/edx-platform,Lektorium-LLC/edx-platform,fintech-circle/edx-platform,EDUlib/edx-platform
from wiki.core.plugins.base import BasePlugin from wiki.core.plugins import registry as plugin_registry from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video class ExtendMarkdownPlugin(BasePlugin): """ This plugin simply loads all of the markdown extensions we use in edX. """ markdown_extensions = [ - mdx_mathjax.MathJaxExtension(configs={}), + mdx_mathjax.MathJaxExtension(configs={}), - mdx_video.VideoExtension(configs={})] + mdx_video.VideoExtension(configs={}), + ] plugin_registry.register(ExtendMarkdownPlugin)
Fix PEP8: E126 continuation line over-indented
## Code Before: from wiki.core.plugins.base import BasePlugin from wiki.core.plugins import registry as plugin_registry from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video class ExtendMarkdownPlugin(BasePlugin): """ This plugin simply loads all of the markdown extensions we use in edX. """ markdown_extensions = [ mdx_mathjax.MathJaxExtension(configs={}), mdx_video.VideoExtension(configs={})] plugin_registry.register(ExtendMarkdownPlugin) ## Instruction: Fix PEP8: E126 continuation line over-indented ## Code After: from wiki.core.plugins.base import BasePlugin from wiki.core.plugins import registry as plugin_registry from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video class ExtendMarkdownPlugin(BasePlugin): """ This plugin simply loads all of the markdown extensions we use in edX. """ markdown_extensions = [ mdx_mathjax.MathJaxExtension(configs={}), mdx_video.VideoExtension(configs={}), ] plugin_registry.register(ExtendMarkdownPlugin)
// ... existing code ... markdown_extensions = [ mdx_mathjax.MathJaxExtension(configs={}), mdx_video.VideoExtension(configs={}), ] plugin_registry.register(ExtendMarkdownPlugin) // ... rest of the code ...
f2d91d2c296e3662a1b656f0fdf5191665ff363b
skimage/transform/__init__.py
skimage/transform/__init__.py
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, homography, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian)
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian)
Remove deprecated import of hompgraphy
Remove deprecated import of hompgraphy
Python
bsd-3-clause
youprofit/scikit-image,almarklein/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,vighneshbirodkar/scikit-image,almarklein/scikit-image,almarklein/scikit-image,chriscrosscutler/scikit-image,ajaybhat/scikit-image,SamHames/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,SamHames/scikit-image,robintw/scikit-image,emon10005/scikit-image,emon10005/scikit-image,ClinicalGraphics/scikit-image,Midafi/scikit-image,warmspringwinds/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,michaelaye/scikit-image,ofgulban/scikit-image,Britefury/scikit-image,michaelaye/scikit-image,blink1073/scikit-image,paalge/scikit-image,Britefury/scikit-image,keflavich/scikit-image,rjeli/scikit-image,newville/scikit-image,bennlich/scikit-image,SamHames/scikit-image,ajaybhat/scikit-image,michaelpacer/scikit-image,chintak/scikit-image,jwiggins/scikit-image,warmspringwinds/scikit-image,chintak/scikit-image,oew1v07/scikit-image,ClinicalGraphics/scikit-image,dpshelio/scikit-image,SamHames/scikit-image,juliusbierk/scikit-image,Midafi/scikit-image,GaZ3ll3/scikit-image,ofgulban/scikit-image,paalge/scikit-image,chintak/scikit-image,robintw/scikit-image,bsipocz/scikit-image,bsipocz/scikit-image,rjeli/scikit-image,bennlich/scikit-image,juliusbierk/scikit-image,chriscrosscutler/scikit-image,jwiggins/scikit-image,michaelpacer/scikit-image,WarrenWeckesser/scikits-image,Hiyorimi/scikit-image,almarklein/scikit-image,pratapvardhan/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,chintak/scikit-image,dpshelio/scikit-image,rjeli/scikit-image,newville/scikit-image,GaZ3ll3/scikit-image,paalge/scikit-image,blink1073/scikit-image
from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) - from ._warps import swirl, homography, resize, rotate, rescale + from ._warps import swirl, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian)
Remove deprecated import of hompgraphy
## Code Before: from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, homography, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian) ## Instruction: Remove deprecated import of hompgraphy ## Code After: from .hough_transform import * from .radon_transform import * from .finite_radon_transform import * from .integral import * from ._geometric import (warp, warp_coords, estimate_transform, SimilarityTransform, AffineTransform, ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian)
// ... existing code ... ProjectiveTransform, PolynomialTransform, PiecewiseAffineTransform) from ._warps import swirl, resize, rotate, rescale from .pyramids import (pyramid_reduce, pyramid_expand, pyramid_gaussian, pyramid_laplacian) // ... rest of the code ...
a978d79bf1a7c9ec9b38841c3e809bd2dc52f3c0
corehq/apps/commtrack/admin.py
corehq/apps/commtrack/admin.py
from django.contrib import admin from .models import StockState class StockStateAdmin(admin.ModelAdmin): model = StockState list_display = [ 'section_id', 'case_id', 'product_id', 'stock_on_hand', 'daily_consumption', 'last_modified_date' ] list_filter = [ 'section_id', 'case_id', 'product_id', 'last_modified_date' ] admin.site.register(StockState, StockStateAdmin)
from django.contrib import admin from .models import StockState class StockStateAdmin(admin.ModelAdmin): model = StockState list_display = [ 'section_id', 'case_id', 'product_id', 'stock_on_hand', 'daily_consumption', 'last_modified_date' ] list_filter = [ 'section_id', 'last_modified_date' ] search_fields = ["case_id", "product_id"] admin.site.register(StockState, StockStateAdmin)
Use product/case id's in search rather than filter
Use product/case id's in search rather than filter
Python
bsd-3-clause
dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
from django.contrib import admin from .models import StockState class StockStateAdmin(admin.ModelAdmin): model = StockState list_display = [ 'section_id', 'case_id', 'product_id', 'stock_on_hand', 'daily_consumption', 'last_modified_date' ] list_filter = [ 'section_id', - 'case_id', - 'product_id', 'last_modified_date' ] + search_fields = ["case_id", "product_id"] + admin.site.register(StockState, StockStateAdmin)
Use product/case id's in search rather than filter
## Code Before: from django.contrib import admin from .models import StockState class StockStateAdmin(admin.ModelAdmin): model = StockState list_display = [ 'section_id', 'case_id', 'product_id', 'stock_on_hand', 'daily_consumption', 'last_modified_date' ] list_filter = [ 'section_id', 'case_id', 'product_id', 'last_modified_date' ] admin.site.register(StockState, StockStateAdmin) ## Instruction: Use product/case id's in search rather than filter ## Code After: from django.contrib import admin from .models import StockState class StockStateAdmin(admin.ModelAdmin): model = StockState list_display = [ 'section_id', 'case_id', 'product_id', 'stock_on_hand', 'daily_consumption', 'last_modified_date' ] list_filter = [ 'section_id', 'last_modified_date' ] search_fields = ["case_id", "product_id"] admin.site.register(StockState, StockStateAdmin)
# ... existing code ... list_filter = [ 'section_id', 'last_modified_date' ] search_fields = ["case_id", "product_id"] admin.site.register(StockState, StockStateAdmin) # ... rest of the code ...
bc199a9eaa2416b35d1d691f580e6c9ca0b1a2ae
website/discovery/views.py
website/discovery/views.py
from website import settings from website.project import Node from website.project import utils from modularodm.query.querydialect import DefaultQueryDialect as Q def activity(): node_data = utils.get_node_data() if node_data: hits = utils.hits(node_data) else: hits = {} # New Projects new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers] # Popular Projects popular_public_projects = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE)).nodes_pointer # Popular Registrations popular_public_registrations = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE_REGISTRATIONS)).nodes_pointer return { 'new_and_noteworthy_projects': new_and_noteworthy_projects, 'recent_public_registrations': utils.recent_public_registrations(), 'popular_public_projects': popular_public_projects, 'popular_public_registrations': popular_public_registrations, 'hits': hits, }
from website import settings from website.project import Node from website.project import utils from modularodm.query.querydialect import DefaultQueryDialect as Q def activity(): """Reads node activity from pre-generated popular projects and registrations. New and Noteworthy projects are set manually or through `scripts/populate_new_and_noteworthy_projects.py` Popular projects and registrations are generated by `scripts/populate_popular_projects_and_registrations.py` """ # New and Noreworthy Projects new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers] # Popular Projects popular_public_projects = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE)).nodes_pointer # Popular Registrations popular_public_registrations = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE_REGISTRATIONS)).nodes_pointer return { 'new_and_noteworthy_projects': new_and_noteworthy_projects, 'recent_public_registrations': utils.recent_public_registrations(), 'popular_public_projects': popular_public_projects, 'popular_public_registrations': popular_public_registrations, }
Remove node counts and update docstrings on new view for activity
Remove node counts and update docstrings on new view for activity
Python
apache-2.0
monikagrabowska/osf.io,binoculars/osf.io,monikagrabowska/osf.io,acshi/osf.io,laurenrevere/osf.io,cslzchen/osf.io,laurenrevere/osf.io,alexschiller/osf.io,monikagrabowska/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,mluo613/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,mfraezz/osf.io,aaxelb/osf.io,alexschiller/osf.io,Nesiehr/osf.io,mluo613/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,mluo613/osf.io,acshi/osf.io,erinspace/osf.io,monikagrabowska/osf.io,rdhyee/osf.io,caneruguz/osf.io,adlius/osf.io,binoculars/osf.io,aaxelb/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,acshi/osf.io,adlius/osf.io,icereval/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,adlius/osf.io,leb2dg/osf.io,icereval/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,laurenrevere/osf.io,mfraezz/osf.io,mattclark/osf.io,crcresearch/osf.io,rdhyee/osf.io,aaxelb/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,TomBaxter/osf.io,cslzchen/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,icereval/osf.io,mattclark/osf.io,crcresearch/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,pattisdr/osf.io,sloria/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,sloria/osf.io,mluo613/osf.io,felliott/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,pattisdr/osf.io,leb2dg/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,aaxelb/osf.io,caneruguz/osf.io,adlius/osf.io,cwisecarver/osf.io,hmoco/osf.io,TomBaxter/osf.io,erinspace/osf.io,acshi/osf.io,leb2dg/osf.io,mattclark/osf.io,alexschiller/osf.io,TomBaxter/osf.io,Nesiehr/osf.io,binoculars/osf.io,acshi/osf.io,chennan47/osf.io,cwisecarver/osf.io,caneruguz/osf.io,chrisseto/osf.io,baylee-d/osf.io,felliott/osf.io,felliott/osf.io,caseyrollins/osf.io,chrisseto/osf.io,saradbowman/osf.io,cwisecarver/osf.io,hmoco/osf.io,erinspace/osf.io,crcresearch/osf.io,rdhyee/osf.io,chrisseto/osf.io,rdhyee/osf.io,hmoco/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,cslzchen/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,chrisseto/osf.io,felliott/osf.io,alexschiller/osf.io,Nesiehr/osf.io,hmoco/osf.io,mluo613/osf.io
from website import settings from website.project import Node from website.project import utils from modularodm.query.querydialect import DefaultQueryDialect as Q def activity(): + """Reads node activity from pre-generated popular projects and registrations. + New and Noteworthy projects are set manually or through `scripts/populate_new_and_noteworthy_projects.py` + Popular projects and registrations are generated by `scripts/populate_popular_projects_and_registrations.py` + """ + # New and Noreworthy Projects - node_data = utils.get_node_data() - if node_data: - hits = utils.hits(node_data) - else: - hits = {} - - # New Projects new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers] # Popular Projects popular_public_projects = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE)).nodes_pointer # Popular Registrations popular_public_registrations = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE_REGISTRATIONS)).nodes_pointer return { 'new_and_noteworthy_projects': new_and_noteworthy_projects, 'recent_public_registrations': utils.recent_public_registrations(), 'popular_public_projects': popular_public_projects, 'popular_public_registrations': popular_public_registrations, - 'hits': hits, }
Remove node counts and update docstrings on new view for activity
## Code Before: from website import settings from website.project import Node from website.project import utils from modularodm.query.querydialect import DefaultQueryDialect as Q def activity(): node_data = utils.get_node_data() if node_data: hits = utils.hits(node_data) else: hits = {} # New Projects new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers] # Popular Projects popular_public_projects = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE)).nodes_pointer # Popular Registrations popular_public_registrations = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE_REGISTRATIONS)).nodes_pointer return { 'new_and_noteworthy_projects': new_and_noteworthy_projects, 'recent_public_registrations': utils.recent_public_registrations(), 'popular_public_projects': popular_public_projects, 'popular_public_registrations': popular_public_registrations, 'hits': hits, } ## Instruction: Remove node counts and update docstrings on new view for activity ## Code After: from website import settings from website.project import Node from website.project import utils from modularodm.query.querydialect import DefaultQueryDialect as Q def activity(): """Reads node activity from pre-generated popular projects and registrations. New and Noteworthy projects are set manually or through `scripts/populate_new_and_noteworthy_projects.py` Popular projects and registrations are generated by `scripts/populate_popular_projects_and_registrations.py` """ # New and Noreworthy Projects new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers] # Popular Projects popular_public_projects = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE)).nodes_pointer # Popular Registrations popular_public_registrations = Node.find_one(Q('_id', 'eq', settings.POPULAR_LINKS_NODE_REGISTRATIONS)).nodes_pointer return { 'new_and_noteworthy_projects': new_and_noteworthy_projects, 'recent_public_registrations': utils.recent_public_registrations(), 'popular_public_projects': popular_public_projects, 'popular_public_registrations': popular_public_registrations, }
... def activity(): """Reads node activity from pre-generated popular projects and registrations. New and Noteworthy projects are set manually or through `scripts/populate_new_and_noteworthy_projects.py` Popular projects and registrations are generated by `scripts/populate_popular_projects_and_registrations.py` """ # New and Noreworthy Projects new_and_noteworthy_pointers = Node.find_one(Q('_id', 'eq', settings.NEW_AND_NOTEWORTHY_LINKS_NODE)).nodes_pointer new_and_noteworthy_projects = [pointer.node for pointer in new_and_noteworthy_pointers] ... 'popular_public_projects': popular_public_projects, 'popular_public_registrations': popular_public_registrations, } ...
249a49d2f174571db22860ebfffc37637cacd9be
xmantissa/plugins/hyperbolaoff.py
xmantissa/plugins/hyperbolaoff.py
from axiom import iaxiom, userbase from xmantissa import website, offering, provisioning import hyperbola from hyperbola import hyperbola_model from hyperbola.hyperbola_theme import HyperbolaTheme hyperbolaer = provisioning.BenefactorFactory( name = u'hyperbolaer', description = u'A wonderful ready to use application named Hyperbola', benefactorClass = hyperbola_model.HyperbolaBenefactor) plugin = offering.Offering( name = u"Hyperbola", description = u""" This is the wonderful Hyperbola application. Click me to install. """, siteRequirements = ( (userbase.IRealm, userbase.LoginSystem), (None, website.WebSite)), appPowerups = ( ), benefactorFactories = (hyperbolaer,), loginInterfaces = (), themes = (HyperbolaTheme('base', 0),) )
from axiom import iaxiom, userbase from xmantissa import website, offering, provisioning import hyperbola from hyperbola import hyperbola_model from hyperbola.hyperbola_theme import HyperbolaTheme hyperbolaer = provisioning.BenefactorFactory( name = u'hyperbolaer', description = u'A wonderful ready to use application named Hyperbola', benefactorClass = hyperbola_model.HyperbolaBenefactor) plugin = offering.Offering( name = u"Hyperbola", description = u""" This is the wonderful Hyperbola application. Click me to install. """, siteRequirements = ( (userbase.IRealm, userbase.LoginSystem), (None, website.WebSite)), appPowerups = ( ), benefactorFactories = (hyperbolaer,), themes = (HyperbolaTheme('base', 0),) )
Revert 5505 - introduced numerous regressions into the test suite
Revert 5505 - introduced numerous regressions into the test suite
Python
mit
twisted/hyperbola,twisted/hyperbola
from axiom import iaxiom, userbase from xmantissa import website, offering, provisioning import hyperbola from hyperbola import hyperbola_model from hyperbola.hyperbola_theme import HyperbolaTheme hyperbolaer = provisioning.BenefactorFactory( name = u'hyperbolaer', description = u'A wonderful ready to use application named Hyperbola', benefactorClass = hyperbola_model.HyperbolaBenefactor) plugin = offering.Offering( name = u"Hyperbola", description = u""" This is the wonderful Hyperbola application. Click me to install. """, siteRequirements = ( (userbase.IRealm, userbase.LoginSystem), (None, website.WebSite)), appPowerups = ( ), benefactorFactories = (hyperbolaer,), - loginInterfaces = (), + themes = (HyperbolaTheme('base', 0),) )
Revert 5505 - introduced numerous regressions into the test suite
## Code Before: from axiom import iaxiom, userbase from xmantissa import website, offering, provisioning import hyperbola from hyperbola import hyperbola_model from hyperbola.hyperbola_theme import HyperbolaTheme hyperbolaer = provisioning.BenefactorFactory( name = u'hyperbolaer', description = u'A wonderful ready to use application named Hyperbola', benefactorClass = hyperbola_model.HyperbolaBenefactor) plugin = offering.Offering( name = u"Hyperbola", description = u""" This is the wonderful Hyperbola application. Click me to install. """, siteRequirements = ( (userbase.IRealm, userbase.LoginSystem), (None, website.WebSite)), appPowerups = ( ), benefactorFactories = (hyperbolaer,), loginInterfaces = (), themes = (HyperbolaTheme('base', 0),) ) ## Instruction: Revert 5505 - introduced numerous regressions into the test suite ## Code After: from axiom import iaxiom, userbase from xmantissa import website, offering, provisioning import hyperbola from hyperbola import hyperbola_model from hyperbola.hyperbola_theme import HyperbolaTheme hyperbolaer = provisioning.BenefactorFactory( name = u'hyperbolaer', description = u'A wonderful ready to use application named Hyperbola', benefactorClass = hyperbola_model.HyperbolaBenefactor) plugin = offering.Offering( name = u"Hyperbola", description = u""" This is the wonderful Hyperbola application. Click me to install. """, siteRequirements = ( (userbase.IRealm, userbase.LoginSystem), (None, website.WebSite)), appPowerups = ( ), benefactorFactories = (hyperbolaer,), themes = (HyperbolaTheme('base', 0),) )
# ... existing code ... benefactorFactories = (hyperbolaer,), themes = (HyperbolaTheme('base', 0),) ) # ... rest of the code ...
6c4343837fb3b92e0cc5db83f124a31658359c47
pymake/builtins.py
pymake/builtins.py
variables = { 'RM': 'rm -f', '.LIBPATTERNS': 'lib%.so lib%.a', }
variables = { 'RM': 'rm -f', '.LIBPATTERNS': 'lib%.so lib%.a', '.PYMAKE': '1', }
Set .PYMAKE so we can distinguish pymake from gmake
Set .PYMAKE so we can distinguish pymake from gmake
Python
mit
indygreg/pymake,mozilla/pymake,mozilla/pymake,mozilla/pymake
variables = { 'RM': 'rm -f', '.LIBPATTERNS': 'lib%.so lib%.a', + '.PYMAKE': '1', }
Set .PYMAKE so we can distinguish pymake from gmake
## Code Before: variables = { 'RM': 'rm -f', '.LIBPATTERNS': 'lib%.so lib%.a', } ## Instruction: Set .PYMAKE so we can distinguish pymake from gmake ## Code After: variables = { 'RM': 'rm -f', '.LIBPATTERNS': 'lib%.so lib%.a', '.PYMAKE': '1', }
... 'RM': 'rm -f', '.LIBPATTERNS': 'lib%.so lib%.a', '.PYMAKE': '1', } ...
93fa014ea7a34834ae6bb85ea802879ae0026941
keystone/common/policies/revoke_event.py
keystone/common/policies/revoke_event.py
from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, # NOTE(lbragstad): This API was originally introduced so that services # could invalidate tokens based on revocation events. This is system # specific so it make sense to associate `system` as the scope type # required for this policy. scope_types=['system'], description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
Add scope_types for revoke event policies
Add scope_types for revoke event policies This commit associates `system` to revoke event policies, since these policies were developed to assist the system in offline token validation. From now on, a warning will be logged when a project-scoped token is used to get revocation events. Operators can opt into requiring system-scoped tokens for these policies by enabling oslo.policy's `enforce_scope` configuration option, which will result in an HTTP Forbidden exception when mismatching scope is used. Change-Id: I1dddeb216b2523b8471e5f2d5370921bb7a45e7f
Python
apache-2.0
mahak/keystone,openstack/keystone,mahak/keystone,mahak/keystone,openstack/keystone,openstack/keystone
from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, + # NOTE(lbragstad): This API was originally introduced so that services + # could invalidate tokens based on revocation events. This is system + # specific so it make sense to associate `system` as the scope type + # required for this policy. + scope_types=['system'], description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
Add scope_types for revoke event policies
## Code Before: from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies ## Instruction: Add scope_types for revoke event policies ## Code After: from oslo_policy import policy from keystone.common.policies import base revoke_event_policies = [ policy.DocumentedRuleDefault( name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, # NOTE(lbragstad): This API was originally introduced so that services # could invalidate tokens based on revocation events. This is system # specific so it make sense to associate `system` as the scope type # required for this policy. scope_types=['system'], description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', 'method': 'GET'}]) ] def list_rules(): return revoke_event_policies
... name=base.IDENTITY % 'list_revoke_events', check_str=base.RULE_SERVICE_OR_ADMIN, # NOTE(lbragstad): This API was originally introduced so that services # could invalidate tokens based on revocation events. This is system # specific so it make sense to associate `system` as the scope type # required for this policy. scope_types=['system'], description='List revocation events.', operations=[{'path': '/v3/OS-REVOKE/events', ...
a1318a5ced6efc4ae88abc0b23190daea5899704
open_humans/serializers.py
open_humans/serializers.py
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from rest_framework import serializers class ProfileSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField('get_profile_url') class Meta: model = User fields = ('id', 'url', 'username') def get_profile_url(self, obj): return reverse('member_profile', args=(obj.id,))
from django.contrib.auth.models import User # from django.core.urlresolvers import reverse from rest_framework import serializers class ProfileSerializer(serializers.ModelSerializer): # url = serializers.SerializerMethodField('get_profile_url') message = serializers.SerializerMethodField('get_message') class Meta: model = User # fields = ('id', 'url', 'username') fields = ('message',) # def get_profile_url(self, obj): # return reverse('member_profile', args=(obj.id,)) def get_message(self, obj): return 'profiles are not yet implemented'
Make /api/profile return no private data
Make /api/profile return no private data
Python
mit
OpenHumans/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans
from django.contrib.auth.models import User - from django.core.urlresolvers import reverse + # from django.core.urlresolvers import reverse from rest_framework import serializers class ProfileSerializer(serializers.ModelSerializer): - url = serializers.SerializerMethodField('get_profile_url') + # url = serializers.SerializerMethodField('get_profile_url') + message = serializers.SerializerMethodField('get_message') class Meta: model = User - fields = ('id', 'url', 'username') + # fields = ('id', 'url', 'username') + fields = ('message',) - def get_profile_url(self, obj): + # def get_profile_url(self, obj): - return reverse('member_profile', args=(obj.id,)) + # return reverse('member_profile', args=(obj.id,)) + def get_message(self, obj): + return 'profiles are not yet implemented' +
Make /api/profile return no private data
## Code Before: from django.contrib.auth.models import User from django.core.urlresolvers import reverse from rest_framework import serializers class ProfileSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField('get_profile_url') class Meta: model = User fields = ('id', 'url', 'username') def get_profile_url(self, obj): return reverse('member_profile', args=(obj.id,)) ## Instruction: Make /api/profile return no private data ## Code After: from django.contrib.auth.models import User # from django.core.urlresolvers import reverse from rest_framework import serializers class ProfileSerializer(serializers.ModelSerializer): # url = serializers.SerializerMethodField('get_profile_url') message = serializers.SerializerMethodField('get_message') class Meta: model = User # fields = ('id', 'url', 'username') fields = ('message',) # def get_profile_url(self, obj): # return reverse('member_profile', args=(obj.id,)) def get_message(self, obj): return 'profiles are not yet implemented'
// ... existing code ... from django.contrib.auth.models import User # from django.core.urlresolvers import reverse from rest_framework import serializers // ... modified code ... class ProfileSerializer(serializers.ModelSerializer): # url = serializers.SerializerMethodField('get_profile_url') message = serializers.SerializerMethodField('get_message') class Meta: model = User # fields = ('id', 'url', 'username') fields = ('message',) # def get_profile_url(self, obj): # return reverse('member_profile', args=(obj.id,)) def get_message(self, obj): return 'profiles are not yet implemented' // ... rest of the code ...
34aa4a19ac1fc7ff52ea0d9ac13df944f1e9754d
src/tn/plonebehavior/template/html_page_html.py
src/tn/plonebehavior/template/html_page_html.py
try: from tn.plonehtmlpage import html_page HAS_HTML_PAGE = True except ImportError: HAS_HTML_PAGE = False if HAS_HTML_PAGE: from five import grok from tn.plonebehavior.template import interfaces from tn.plonebehavior.template.html import ContextlessHTML class HTMLPageHTML(grok.Adapter): grok.context(html_page.IHTMLPageSchema) grok.implements(interfaces.IHTML) contextless_factory = ContextlessHTML def __unicode__(self): base_url = self.context.absolute_url() return unicode(self.contextless_factory(base_url, self.context.html))
try: from tn.plonehtmlpage import html_page HAS_HTML_PAGE = True except ImportError: HAS_HTML_PAGE = False if HAS_HTML_PAGE: from five import grok from tn.plonebehavior.template import _ from tn.plonebehavior.template import ITemplateConfiguration from tn.plonebehavior.template import interfaces from tn.plonebehavior.template.html import ContextlessHTML from z3c.form import validator import collections import lxml.cssselect import lxml.html import zope.interface isiterable = lambda o: isinstance(o, collections.Iterable) class HTMLPageHTML(grok.Adapter): grok.context(html_page.IHTMLPageSchema) grok.implements(interfaces.IHTML) contextless_factory = ContextlessHTML def __unicode__(self): base_url = self.context.absolute_url() return unicode(self.contextless_factory(base_url, self.context.html)) class CSSSelectorValidator(validator.SimpleFieldValidator): def validate(self, value): super(CSSSelectorValidator, self).validate(value) tree = lxml.html.document_fromstring(self.context.html) xpath = lxml.cssselect.CSSSelector(value).path selection = tree.xpath(xpath) if not isiterable(selection) or len(selection) != 1: raise zope.interface.Invalid(_( "Expression doesn't select a single element " "in the HTML page." )) validator.WidgetValidatorDiscriminators( CSSSelectorValidator, context=html_page.IHTMLPageSchema, field=ITemplateConfiguration['css'] ) grok.global_adapter(CSSSelectorValidator)
Add a validation to ensure that CSS selector actually works
Add a validation to ensure that CSS selector actually works
Python
bsd-3-clause
tecnologiaenegocios/tn.plonebehavior.template,tecnologiaenegocios/tn.plonebehavior.template
try: from tn.plonehtmlpage import html_page HAS_HTML_PAGE = True except ImportError: HAS_HTML_PAGE = False if HAS_HTML_PAGE: from five import grok + from tn.plonebehavior.template import _ + from tn.plonebehavior.template import ITemplateConfiguration from tn.plonebehavior.template import interfaces from tn.plonebehavior.template.html import ContextlessHTML + from z3c.form import validator + + import collections + import lxml.cssselect + import lxml.html + import zope.interface + + isiterable = lambda o: isinstance(o, collections.Iterable) class HTMLPageHTML(grok.Adapter): grok.context(html_page.IHTMLPageSchema) grok.implements(interfaces.IHTML) contextless_factory = ContextlessHTML def __unicode__(self): base_url = self.context.absolute_url() return unicode(self.contextless_factory(base_url, self.context.html)) + class CSSSelectorValidator(validator.SimpleFieldValidator): + def validate(self, value): + super(CSSSelectorValidator, self).validate(value) + + tree = lxml.html.document_fromstring(self.context.html) + xpath = lxml.cssselect.CSSSelector(value).path + selection = tree.xpath(xpath) + if not isiterable(selection) or len(selection) != 1: + raise zope.interface.Invalid(_( + "Expression doesn't select a single element " + "in the HTML page." + )) + + validator.WidgetValidatorDiscriminators( + CSSSelectorValidator, + context=html_page.IHTMLPageSchema, + field=ITemplateConfiguration['css'] + ) + + grok.global_adapter(CSSSelectorValidator) +
Add a validation to ensure that CSS selector actually works
## Code Before: try: from tn.plonehtmlpage import html_page HAS_HTML_PAGE = True except ImportError: HAS_HTML_PAGE = False if HAS_HTML_PAGE: from five import grok from tn.plonebehavior.template import interfaces from tn.plonebehavior.template.html import ContextlessHTML class HTMLPageHTML(grok.Adapter): grok.context(html_page.IHTMLPageSchema) grok.implements(interfaces.IHTML) contextless_factory = ContextlessHTML def __unicode__(self): base_url = self.context.absolute_url() return unicode(self.contextless_factory(base_url, self.context.html)) ## Instruction: Add a validation to ensure that CSS selector actually works ## Code After: try: from tn.plonehtmlpage import html_page HAS_HTML_PAGE = True except ImportError: HAS_HTML_PAGE = False if HAS_HTML_PAGE: from five import grok from tn.plonebehavior.template import _ from tn.plonebehavior.template import ITemplateConfiguration from tn.plonebehavior.template import interfaces from tn.plonebehavior.template.html import ContextlessHTML from z3c.form import validator import collections import lxml.cssselect import lxml.html import zope.interface isiterable = lambda o: isinstance(o, collections.Iterable) class HTMLPageHTML(grok.Adapter): grok.context(html_page.IHTMLPageSchema) grok.implements(interfaces.IHTML) contextless_factory = ContextlessHTML def __unicode__(self): base_url = self.context.absolute_url() return unicode(self.contextless_factory(base_url, self.context.html)) class CSSSelectorValidator(validator.SimpleFieldValidator): def validate(self, value): super(CSSSelectorValidator, self).validate(value) tree = lxml.html.document_fromstring(self.context.html) xpath = lxml.cssselect.CSSSelector(value).path selection = tree.xpath(xpath) if not isiterable(selection) or len(selection) != 1: raise zope.interface.Invalid(_( "Expression doesn't select a single element " "in the HTML page." )) validator.WidgetValidatorDiscriminators( CSSSelectorValidator, context=html_page.IHTMLPageSchema, field=ITemplateConfiguration['css'] ) grok.global_adapter(CSSSelectorValidator)
// ... existing code ... if HAS_HTML_PAGE: from five import grok from tn.plonebehavior.template import _ from tn.plonebehavior.template import ITemplateConfiguration from tn.plonebehavior.template import interfaces from tn.plonebehavior.template.html import ContextlessHTML from z3c.form import validator import collections import lxml.cssselect import lxml.html import zope.interface isiterable = lambda o: isinstance(o, collections.Iterable) class HTMLPageHTML(grok.Adapter): // ... modified code ... return unicode(self.contextless_factory(base_url, self.context.html)) class CSSSelectorValidator(validator.SimpleFieldValidator): def validate(self, value): super(CSSSelectorValidator, self).validate(value) tree = lxml.html.document_fromstring(self.context.html) xpath = lxml.cssselect.CSSSelector(value).path selection = tree.xpath(xpath) if not isiterable(selection) or len(selection) != 1: raise zope.interface.Invalid(_( "Expression doesn't select a single element " "in the HTML page." )) validator.WidgetValidatorDiscriminators( CSSSelectorValidator, context=html_page.IHTMLPageSchema, field=ITemplateConfiguration['css'] ) grok.global_adapter(CSSSelectorValidator) // ... rest of the code ...
b3befb47d4b48e83b42fc6b10a10269d32cafb4e
src-backend/api/urls.py
src-backend/api/urls.py
from django.conf.urls import url, include from views import ProcedureViewSet from rest_framework import routers router = routers.SimpleRouter() router.register(r'procedures', ProcedureViewSet) urlpatterns = [ url(r'^', include(router.urls)) ]
from django.conf.urls import url, include from views import ProcedureViewSet from rest_framework import routers router = routers.SimpleRouter(trailing_slash=False) router.register(r'procedures', ProcedureViewSet) urlpatterns = [ url(r'^', include(router.urls)) ]
Remove trailing slash from the router
Remove trailing slash from the router
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.conf.urls import url, include from views import ProcedureViewSet from rest_framework import routers - router = routers.SimpleRouter() + router = routers.SimpleRouter(trailing_slash=False) router.register(r'procedures', ProcedureViewSet) urlpatterns = [ url(r'^', include(router.urls)) ]
Remove trailing slash from the router
## Code Before: from django.conf.urls import url, include from views import ProcedureViewSet from rest_framework import routers router = routers.SimpleRouter() router.register(r'procedures', ProcedureViewSet) urlpatterns = [ url(r'^', include(router.urls)) ] ## Instruction: Remove trailing slash from the router ## Code After: from django.conf.urls import url, include from views import ProcedureViewSet from rest_framework import routers router = routers.SimpleRouter(trailing_slash=False) router.register(r'procedures', ProcedureViewSet) urlpatterns = [ url(r'^', include(router.urls)) ]
# ... existing code ... from rest_framework import routers router = routers.SimpleRouter(trailing_slash=False) router.register(r'procedures', ProcedureViewSet) # ... rest of the code ...
e87fc9172b9d56fe9d64cfda2fb36a3f71e69e70
tests/test_utils.py
tests/test_utils.py
import re from jenkins_autojobs import main def test_filter_jobs(): class Job: def __init__(self, name): self.name = name class jenkins: pass names = ['feature-one', 'feature-two', 'release-one', 'release-two'] jenkins.jobs = [Job(i) for i in names] filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)} #------------------------------------------------------------------------- assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'} res = filter_jobs(by_name_regex=[re.compile('feature-')]) assert res == {'feature-one', 'feature-two'} res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')]) assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'} #------------------------------------------------------------------------- view_jobs = { 'v1': [Job('scratch-one'), Job('scratch-two')], 'v2': [Job('release-one'), Job('maintenance-three')] } jenkins.view_jobs = lambda x: view_jobs[x] res = filter_jobs(by_views=['v1']) assert res == {'scratch-one', 'scratch-two'} res = filter_jobs(by_views=['v1', 'v2']) assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'}
import re from jenkins_autojobs import main def test_filter_jobs(): class Job: def __init__(self, name): self.name = name class jenkins: @staticmethod def view_jobs(x): return { 'v1': [Job('scratch-one'), Job('scratch-two')], 'v2': [Job('release-one'), Job('maintenance-three')] }[x] names = ['feature-one', 'feature-two', 'release-one', 'release-two'] jenkins.jobs = [Job(i) for i in names] filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)} #------------------------------------------------------------------------- assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'} res = filter_jobs(by_name_regex=[re.compile('feature-')]) assert res == {'feature-one', 'feature-two'} res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')]) assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'} #------------------------------------------------------------------------- res = filter_jobs(by_views=['v1']) assert res == {'scratch-one', 'scratch-two'} res = filter_jobs(by_views=['v1', 'v2']) assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'}
Fix tests on Python 2
Fix tests on Python 2
Python
bsd-3-clause
gvalkov/jenkins-autojobs,gvalkov/jenkins-autojobs
import re from jenkins_autojobs import main def test_filter_jobs(): class Job: def __init__(self, name): self.name = name class jenkins: - pass + @staticmethod + def view_jobs(x): + return { + 'v1': [Job('scratch-one'), Job('scratch-two')], + 'v2': [Job('release-one'), Job('maintenance-three')] + }[x] names = ['feature-one', 'feature-two', 'release-one', 'release-two'] jenkins.jobs = [Job(i) for i in names] filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)} #------------------------------------------------------------------------- assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'} res = filter_jobs(by_name_regex=[re.compile('feature-')]) assert res == {'feature-one', 'feature-two'} res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')]) assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'} #------------------------------------------------------------------------- - view_jobs = { - 'v1': [Job('scratch-one'), Job('scratch-two')], - 'v2': [Job('release-one'), Job('maintenance-three')] - } - jenkins.view_jobs = lambda x: view_jobs[x] - res = filter_jobs(by_views=['v1']) assert res == {'scratch-one', 'scratch-two'} res = filter_jobs(by_views=['v1', 'v2']) assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'}
Fix tests on Python 2
## Code Before: import re from jenkins_autojobs import main def test_filter_jobs(): class Job: def __init__(self, name): self.name = name class jenkins: pass names = ['feature-one', 'feature-two', 'release-one', 'release-two'] jenkins.jobs = [Job(i) for i in names] filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)} #------------------------------------------------------------------------- assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'} res = filter_jobs(by_name_regex=[re.compile('feature-')]) assert res == {'feature-one', 'feature-two'} res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')]) assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'} #------------------------------------------------------------------------- view_jobs = { 'v1': [Job('scratch-one'), Job('scratch-two')], 'v2': [Job('release-one'), Job('maintenance-three')] } jenkins.view_jobs = lambda x: view_jobs[x] res = filter_jobs(by_views=['v1']) assert res == {'scratch-one', 'scratch-two'} res = filter_jobs(by_views=['v1', 'v2']) assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'} ## Instruction: Fix tests on Python 2 ## Code After: import re from jenkins_autojobs import main def test_filter_jobs(): class Job: def __init__(self, name): self.name = name class jenkins: @staticmethod def view_jobs(x): return { 'v1': [Job('scratch-one'), Job('scratch-two')], 'v2': [Job('release-one'), Job('maintenance-three')] }[x] names = ['feature-one', 'feature-two', 'release-one', 'release-two'] jenkins.jobs = [Job(i) for i in names] filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)} #------------------------------------------------------------------------- assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'} res = filter_jobs(by_name_regex=[re.compile('feature-')]) assert res == {'feature-one', 'feature-two'} res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')]) assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'} #------------------------------------------------------------------------- res = filter_jobs(by_views=['v1']) assert res == {'scratch-one', 'scratch-two'} res = filter_jobs(by_views=['v1', 'v2']) assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'}
// ... existing code ... class jenkins: @staticmethod def view_jobs(x): return { 'v1': [Job('scratch-one'), Job('scratch-two')], 'v2': [Job('release-one'), Job('maintenance-three')] }[x] names = ['feature-one', 'feature-two', 'release-one', 'release-two'] // ... modified code ... #------------------------------------------------------------------------- res = filter_jobs(by_views=['v1']) assert res == {'scratch-one', 'scratch-two'} // ... rest of the code ...
8fc274021a8c0813f3fc3568d1d7984112952b9c
pytilemap/qtsupport.py
pytilemap/qtsupport.py
import sys import sip import qtpy __all__ = [ 'getQVariantValue', 'wheelAngleDelta', ] try: if qtpy.PYQT5: QVARIANT_API = 2 else: QVARIANT_API = sip.getapi('QVariant') except ValueError: QVARIANT_API = 1 if QVARIANT_API == 1: def getQVariantValue(variant): return variant.toPyObject() else: def getQVariantValue(variant): return variant if qtpy.PYQT5: def wheelAngleDelta(wheelEvent): return wheelEvent.angleDelta().y() else: def wheelAngleDelta(wheelEvent): return wheelEvent.delta() if qtpy.PYQT5: from qtpy.QtCore import QStandardPaths def getTemporaryFolder(): return QStandardPaths.writableLocation(QStandardPaths.TempLocation) else: from qtpy.QtGui import QDesktopServices def getTemporaryFolder(): return QDesktopServices.storageLocation(QDesktopServices.TempLocation)
import sys import sip import qtpy __all__ = [ 'getQVariantValue', 'wheelAngleDelta', ] try: if qtpy.PYQT5: QVARIANT_API = 2 else: QVARIANT_API = sip.getapi('QVariant') except ValueError: QVARIANT_API = 1 if QVARIANT_API == 1: def getQVariantValue(variant): return variant.toPyObject() else: def getQVariantValue(variant): return variant if qtpy.PYQT5: def wheelAngleDelta(wheelEvent): return wheelEvent.angleDelta().y() else: def wheelAngleDelta(wheelEvent): return wheelEvent.delta() if qtpy.PYQT5: from qtpy.QtCore import QStandardPaths def getTemporaryFolder(): return QStandardPaths.writableLocation(QStandardPaths.CacheLocation) else: from qtpy.QtGui import QDesktopServices def getTemporaryFolder(): return QDesktopServices.storageLocation(QDesktopServices.CacheLocation)
Use Cache location instead of temp folder
Use Cache location instead of temp folder
Python
mit
allebacco/PyTileMap
import sys import sip import qtpy __all__ = [ 'getQVariantValue', 'wheelAngleDelta', ] try: if qtpy.PYQT5: QVARIANT_API = 2 else: QVARIANT_API = sip.getapi('QVariant') except ValueError: QVARIANT_API = 1 if QVARIANT_API == 1: def getQVariantValue(variant): return variant.toPyObject() else: def getQVariantValue(variant): return variant if qtpy.PYQT5: def wheelAngleDelta(wheelEvent): return wheelEvent.angleDelta().y() else: def wheelAngleDelta(wheelEvent): return wheelEvent.delta() if qtpy.PYQT5: from qtpy.QtCore import QStandardPaths def getTemporaryFolder(): - return QStandardPaths.writableLocation(QStandardPaths.TempLocation) + return QStandardPaths.writableLocation(QStandardPaths.CacheLocation) else: from qtpy.QtGui import QDesktopServices def getTemporaryFolder(): - return QDesktopServices.storageLocation(QDesktopServices.TempLocation) + return QDesktopServices.storageLocation(QDesktopServices.CacheLocation)
Use Cache location instead of temp folder
## Code Before: import sys import sip import qtpy __all__ = [ 'getQVariantValue', 'wheelAngleDelta', ] try: if qtpy.PYQT5: QVARIANT_API = 2 else: QVARIANT_API = sip.getapi('QVariant') except ValueError: QVARIANT_API = 1 if QVARIANT_API == 1: def getQVariantValue(variant): return variant.toPyObject() else: def getQVariantValue(variant): return variant if qtpy.PYQT5: def wheelAngleDelta(wheelEvent): return wheelEvent.angleDelta().y() else: def wheelAngleDelta(wheelEvent): return wheelEvent.delta() if qtpy.PYQT5: from qtpy.QtCore import QStandardPaths def getTemporaryFolder(): return QStandardPaths.writableLocation(QStandardPaths.TempLocation) else: from qtpy.QtGui import QDesktopServices def getTemporaryFolder(): return QDesktopServices.storageLocation(QDesktopServices.TempLocation) ## Instruction: Use Cache location instead of temp folder ## Code After: import sys import sip import qtpy __all__ = [ 'getQVariantValue', 'wheelAngleDelta', ] try: if qtpy.PYQT5: QVARIANT_API = 2 else: QVARIANT_API = sip.getapi('QVariant') except ValueError: QVARIANT_API = 1 if QVARIANT_API == 1: def getQVariantValue(variant): return variant.toPyObject() else: def getQVariantValue(variant): return variant if qtpy.PYQT5: def wheelAngleDelta(wheelEvent): return wheelEvent.angleDelta().y() else: def wheelAngleDelta(wheelEvent): return wheelEvent.delta() if qtpy.PYQT5: from qtpy.QtCore import QStandardPaths def getTemporaryFolder(): return QStandardPaths.writableLocation(QStandardPaths.CacheLocation) else: from qtpy.QtGui import QDesktopServices def getTemporaryFolder(): return QDesktopServices.storageLocation(QDesktopServices.CacheLocation)
# ... existing code ... def getTemporaryFolder(): return QStandardPaths.writableLocation(QStandardPaths.CacheLocation) else: # ... modified code ... def getTemporaryFolder(): return QDesktopServices.storageLocation(QDesktopServices.CacheLocation) # ... rest of the code ...
1318d0bc658d23d22452b27004c5d670f4c80d17
spacy/tests/conftest.py
spacy/tests/conftest.py
import pytest import os import spacy @pytest.fixture(scope="session") def EN(): return spacy.load("en") @pytest.fixture(scope="session") def DE(): return spacy.load("de") def pytest_addoption(parser): parser.addoption("--models", action="store_true", help="include tests that require full models") parser.addoption("--vectors", action="store_true", help="include word vectors tests") parser.addoption("--slow", action="store_true", help="include slow tests") def pytest_runtest_setup(item): for opt in ['models', 'vectors', 'slow']: if opt in item.keywords and not item.config.getoption("--%s" % opt): pytest.skip("need --%s option to run" % opt)
import pytest import os from ..en import English from ..de import German @pytest.fixture(scope="session") def EN(): return English(path=None) @pytest.fixture(scope="session") def DE(): return German(path=None) def pytest_addoption(parser): parser.addoption("--models", action="store_true", help="include tests that require full models") parser.addoption("--vectors", action="store_true", help="include word vectors tests") parser.addoption("--slow", action="store_true", help="include slow tests") def pytest_runtest_setup(item): for opt in ['models', 'vectors', 'slow']: if opt in item.keywords and not item.config.getoption("--%s" % opt): pytest.skip("need --%s option to run" % opt)
Test with the non-loaded versions of the English and German pipelines.
Test with the non-loaded versions of the English and German pipelines.
Python
mit
raphael0202/spaCy,honnibal/spaCy,banglakit/spaCy,aikramer2/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,recognai/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,banglakit/spaCy,Gregory-Howard/spaCy,recognai/spaCy,explosion/spaCy,honnibal/spaCy,recognai/spaCy,recognai/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,banglakit/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,spacy-io/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,raphael0202/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,explosion/spaCy,aikramer2/spaCy,spacy-io/spaCy,banglakit/spaCy,banglakit/spaCy,honnibal/spaCy
import pytest import os - import spacy + from ..en import English + from ..de import German @pytest.fixture(scope="session") def EN(): - return spacy.load("en") + return English(path=None) @pytest.fixture(scope="session") def DE(): - return spacy.load("de") + return German(path=None) def pytest_addoption(parser): parser.addoption("--models", action="store_true", help="include tests that require full models") parser.addoption("--vectors", action="store_true", help="include word vectors tests") parser.addoption("--slow", action="store_true", help="include slow tests") def pytest_runtest_setup(item): for opt in ['models', 'vectors', 'slow']: if opt in item.keywords and not item.config.getoption("--%s" % opt): pytest.skip("need --%s option to run" % opt)
Test with the non-loaded versions of the English and German pipelines.
## Code Before: import pytest import os import spacy @pytest.fixture(scope="session") def EN(): return spacy.load("en") @pytest.fixture(scope="session") def DE(): return spacy.load("de") def pytest_addoption(parser): parser.addoption("--models", action="store_true", help="include tests that require full models") parser.addoption("--vectors", action="store_true", help="include word vectors tests") parser.addoption("--slow", action="store_true", help="include slow tests") def pytest_runtest_setup(item): for opt in ['models', 'vectors', 'slow']: if opt in item.keywords and not item.config.getoption("--%s" % opt): pytest.skip("need --%s option to run" % opt) ## Instruction: Test with the non-loaded versions of the English and German pipelines. ## Code After: import pytest import os from ..en import English from ..de import German @pytest.fixture(scope="session") def EN(): return English(path=None) @pytest.fixture(scope="session") def DE(): return German(path=None) def pytest_addoption(parser): parser.addoption("--models", action="store_true", help="include tests that require full models") parser.addoption("--vectors", action="store_true", help="include word vectors tests") parser.addoption("--slow", action="store_true", help="include slow tests") def pytest_runtest_setup(item): for opt in ['models', 'vectors', 'slow']: if opt in item.keywords and not item.config.getoption("--%s" % opt): pytest.skip("need --%s option to run" % opt)
// ... existing code ... import os from ..en import English from ..de import German // ... modified code ... @pytest.fixture(scope="session") def EN(): return English(path=None) @pytest.fixture(scope="session") def DE(): return German(path=None) // ... rest of the code ...
ce9cbc4144c105e9cb59836274ef25a29a9b20a7
webserver/codemanagement/tasks.py
webserver/codemanagement/tasks.py
from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) # Create a submission for the HEAD commit TeamSubmission.objects.create(team=instance.team, commit=instance.repository.repo['HEAD'].id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name))
from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) try: commit = instance.repository.repo['HEAD'] except KeyError: # Log an error if we can't get a commit msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" logger.error(msg.format(team_name)) else: # Create a submission for the HEAD commit TeamSubmission.objects.create(teamclient=instance, commit=commit.id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name))
Handle attempts to tag empty shell repos
Handle attempts to tag empty shell repos
Python
bsd-3-clause
siggame/webserver,siggame/webserver,siggame/webserver
from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) + try: + commit = instance.repository.repo['HEAD'] + except KeyError: + # Log an error if we can't get a commit + msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" + logger.error(msg.format(team_name)) + else: - # Create a submission for the HEAD commit + # Create a submission for the HEAD commit - TeamSubmission.objects.create(team=instance.team, + TeamSubmission.objects.create(teamclient=instance, - commit=instance.repository.repo['HEAD'].id, + commit=commit.id, - name="ShellAI", + name="ShellAI", - submitter=None) + submitter=None) - logger.info("Tagged {}'s repo".format(team_name)) + logger.info("Tagged {}'s repo".format(team_name))
Handle attempts to tag empty shell repos
## Code Before: from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) # Create a submission for the HEAD commit TeamSubmission.objects.create(team=instance.team, commit=instance.repository.repo['HEAD'].id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name)) ## Instruction: Handle attempts to tag empty shell repos ## Code After: from celery import task from celery.result import AsyncResult from .models import TeamSubmission import logging logger = logging.getLogger(__name__) @task() def create_shellai_tag(instance): """Tags the repo's HEAD as "ShellAI" to provide a default tag for the arena to use""" team_name = instance.team.name if instance.repository.task_id is not None: # Wait for the repo to be created AsyncResult(instance.repository.task_id).wait() msg = "Waiting for {}'s repository to be created..." logger.info(msg.format(team_name)) logger.info("{}'s repository is ready".format(team_name)) try: commit = instance.repository.repo['HEAD'] except KeyError: # Log an error if we can't get a commit msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" logger.error(msg.format(team_name)) else: # Create a submission for the HEAD commit TeamSubmission.objects.create(teamclient=instance, commit=commit.id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name))
# ... existing code ... logger.info("{}'s repository is ready".format(team_name)) try: commit = instance.repository.repo['HEAD'] except KeyError: # Log an error if we can't get a commit msg = "Unable to tag {}'s repo. Bad ref 'HEAD'. Is the repo empty?" logger.error(msg.format(team_name)) else: # Create a submission for the HEAD commit TeamSubmission.objects.create(teamclient=instance, commit=commit.id, name="ShellAI", submitter=None) logger.info("Tagged {}'s repo".format(team_name)) # ... rest of the code ...
282d6ae5911e4fcf4625a7e82e7024c5dc0722d8
tests/test_simple_persistence.py
tests/test_simple_persistence.py
from __future__ import unicode_literals, division, absolute_import from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken'
from __future__ import unicode_literals, division, absolute_import from flexget.manager import Session from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' def test_nosession(self): persist = SimplePersistence('testplugin') persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it commits and actually persists persist = SimplePersistence('testplugin') assert persist['aoeu'] == 'test' def test_withsession(self): session = Session() persist = SimplePersistence('testplugin', session=session) persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it didn't commit or close our session session.rollback() assert 'aoeu' not in persist
Add some more tests for simple_persistence
Add some more tests for simple_persistence
Python
mit
cvium/Flexget,OmgOhnoes/Flexget,jawilson/Flexget,patsissons/Flexget,ZefQ/Flexget,tarzasai/Flexget,X-dark/Flexget,qk4l/Flexget,tsnoam/Flexget,Danfocus/Flexget,spencerjanssen/Flexget,crawln45/Flexget,oxc/Flexget,tvcsantos/Flexget,Flexget/Flexget,tarzasai/Flexget,tobinjt/Flexget,qvazzler/Flexget,Pretagonist/Flexget,LynxyssCZ/Flexget,ianstalk/Flexget,thalamus/Flexget,vfrc2/Flexget,LynxyssCZ/Flexget,camon/Flexget,thalamus/Flexget,spencerjanssen/Flexget,sean797/Flexget,offbyone/Flexget,offbyone/Flexget,xfouloux/Flexget,malkavi/Flexget,poulpito/Flexget,sean797/Flexget,dsemi/Flexget,patsissons/Flexget,ZefQ/Flexget,malkavi/Flexget,ZefQ/Flexget,drwyrm/Flexget,malkavi/Flexget,tvcsantos/Flexget,tsnoam/Flexget,grrr2/Flexget,Flexget/Flexget,jacobmetrick/Flexget,OmgOhnoes/Flexget,ibrahimkarahan/Flexget,Pretagonist/Flexget,qk4l/Flexget,ratoaq2/Flexget,gazpachoking/Flexget,drwyrm/Flexget,jawilson/Flexget,tarzasai/Flexget,spencerjanssen/Flexget,lildadou/Flexget,LynxyssCZ/Flexget,qvazzler/Flexget,asm0dey/Flexget,crawln45/Flexget,cvium/Flexget,tobinjt/Flexget,poulpito/Flexget,vfrc2/Flexget,JorisDeRieck/Flexget,jawilson/Flexget,offbyone/Flexget,qvazzler/Flexget,antivirtel/Flexget,xfouloux/Flexget,tobinjt/Flexget,thalamus/Flexget,Danfocus/Flexget,lildadou/Flexget,JorisDeRieck/Flexget,v17al/Flexget,malkavi/Flexget,X-dark/Flexget,lildadou/Flexget,dsemi/Flexget,oxc/Flexget,dsemi/Flexget,cvium/Flexget,v17al/Flexget,jawilson/Flexget,qk4l/Flexget,voriux/Flexget,voriux/Flexget,jacobmetrick/Flexget,antivirtel/Flexget,grrr2/Flexget,ianstalk/Flexget,tobinjt/Flexget,X-dark/Flexget,oxc/Flexget,jacobmetrick/Flexget,poulpito/Flexget,Danfocus/Flexget,ibrahimkarahan/Flexget,crawln45/Flexget,ibrahimkarahan/Flexget,gazpachoking/Flexget,v17al/Flexget,ianstalk/Flexget,tsnoam/Flexget,drwyrm/Flexget,patsissons/Flexget,Flexget/Flexget,ratoaq2/Flexget,JorisDeRieck/Flexget,JorisDeRieck/Flexget,LynxyssCZ/Flexget,sean797/Flexget,asm0dey/Flexget,OmgOhnoes/Flexget,Flexget/Flexget,vfrc2/Flexget,ratoaq2/Flexget,Danfocus/Flexget,grrr2/Flexget,antivirtel/Flexget,asm0dey/Flexget,Pretagonist/Flexget,xfouloux/Flexget,camon/Flexget,crawln45/Flexget
from __future__ import unicode_literals, division, absolute_import + + from flexget.manager import Session + from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' + def test_nosession(self): + persist = SimplePersistence('testplugin') + persist['aoeu'] = 'test' + assert persist['aoeu'] == 'test' + # Make sure it commits and actually persists + persist = SimplePersistence('testplugin') + assert persist['aoeu'] == 'test' + + def test_withsession(self): + session = Session() + persist = SimplePersistence('testplugin', session=session) + persist['aoeu'] = 'test' + assert persist['aoeu'] == 'test' + # Make sure it didn't commit or close our session + session.rollback() + assert 'aoeu' not in persist +
Add some more tests for simple_persistence
## Code Before: from __future__ import unicode_literals, division, absolute_import from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' ## Instruction: Add some more tests for simple_persistence ## Code After: from __future__ import unicode_literals, division, absolute_import from flexget.manager import Session from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase class TestSimplePersistence(FlexGetBase): __yaml__ = """ tasks: test: mock: - {title: 'irrelevant'} """ def test_setdefault(self): self.execute_task('test') task = self.task value1 = task.simple_persistence.setdefault('test', 'abc') value2 = task.simple_persistence.setdefault('test', 'def') assert value1 == value2, 'set default broken' def test_nosession(self): persist = SimplePersistence('testplugin') persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it commits and actually persists persist = SimplePersistence('testplugin') assert persist['aoeu'] == 'test' def test_withsession(self): session = Session() persist = SimplePersistence('testplugin', session=session) persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it didn't commit or close our session session.rollback() assert 'aoeu' not in persist
// ... existing code ... from __future__ import unicode_literals, division, absolute_import from flexget.manager import Session from flexget.utils.simple_persistence import SimplePersistence from tests import FlexGetBase // ... modified code ... assert value1 == value2, 'set default broken' def test_nosession(self): persist = SimplePersistence('testplugin') persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it commits and actually persists persist = SimplePersistence('testplugin') assert persist['aoeu'] == 'test' def test_withsession(self): session = Session() persist = SimplePersistence('testplugin', session=session) persist['aoeu'] = 'test' assert persist['aoeu'] == 'test' # Make sure it didn't commit or close our session session.rollback() assert 'aoeu' not in persist // ... rest of the code ...
fec482c6b1655d7108386760a3e0297850da6e7b
editorsnotes/api/validators.py
editorsnotes/api/validators.py
from rest_framework.serializers import ValidationError class UniqueToProjectValidator: message = u'{model_name} with this {field_name} already exists.' def __init__(self, field, message=None): self.field_name = field self.message = message or self.message def set_context(self, serializer): self.ModelClass = serializer.Meta.model self.instance = getattr(serializer, 'instance', None) def __call__(self, attrs): # Assuming that the field is always required if self.instance is not None: value = attrs.get(self.field_name, getattr(self.instance, self.field_name)) else: value = attrs[self.field_name] kwargs = {'project': attrs['project'], self.field_name: value} qs = self.ModelClass.objects.filter(**kwargs) if self.instance is not None: qs = qs.exclude(id=self.instance.id) if qs.exists(): opts = self.ModelClass._meta raise ValidationError({ self.field_name: self.message.format( model_name=opts.verbose_name.title(), field_name=opts.get_field(self.field_name).verbose_name ) })
from rest_framework.serializers import ValidationError class UniqueToProjectValidator: message = u'{model_name} with this {field_name} already exists.' def __init__(self, field, message=None): self.field_name = field self.message = message or self.message def set_context(self, serializer): self.ModelClass = serializer.Meta.model self.instance = getattr(serializer, 'instance', None) self.project = serializer.context['request'].project def __call__(self, attrs): # Assuming that the field is always required if self.instance is not None: value = attrs.get(self.field_name, getattr(self.instance, self.field_name)) else: value = attrs[self.field_name] kwargs = {'project': self.project, self.field_name: value} qs = self.ModelClass.objects.filter(**kwargs) if self.instance is not None: qs = qs.exclude(id=self.instance.id) if qs.exists(): opts = self.ModelClass._meta raise ValidationError({ self.field_name: self.message.format( model_name=opts.verbose_name.title(), field_name=opts.get_field(self.field_name).verbose_name ) })
Make sure a project is set for the project-specific validator
Make sure a project is set for the project-specific validator
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
from rest_framework.serializers import ValidationError class UniqueToProjectValidator: message = u'{model_name} with this {field_name} already exists.' def __init__(self, field, message=None): self.field_name = field self.message = message or self.message def set_context(self, serializer): self.ModelClass = serializer.Meta.model self.instance = getattr(serializer, 'instance', None) + self.project = serializer.context['request'].project def __call__(self, attrs): # Assuming that the field is always required if self.instance is not None: value = attrs.get(self.field_name, getattr(self.instance, self.field_name)) else: value = attrs[self.field_name] - kwargs = {'project': attrs['project'], self.field_name: value} + kwargs = {'project': self.project, self.field_name: value} qs = self.ModelClass.objects.filter(**kwargs) if self.instance is not None: qs = qs.exclude(id=self.instance.id) if qs.exists(): opts = self.ModelClass._meta raise ValidationError({ self.field_name: self.message.format( model_name=opts.verbose_name.title(), field_name=opts.get_field(self.field_name).verbose_name ) })
Make sure a project is set for the project-specific validator
## Code Before: from rest_framework.serializers import ValidationError class UniqueToProjectValidator: message = u'{model_name} with this {field_name} already exists.' def __init__(self, field, message=None): self.field_name = field self.message = message or self.message def set_context(self, serializer): self.ModelClass = serializer.Meta.model self.instance = getattr(serializer, 'instance', None) def __call__(self, attrs): # Assuming that the field is always required if self.instance is not None: value = attrs.get(self.field_name, getattr(self.instance, self.field_name)) else: value = attrs[self.field_name] kwargs = {'project': attrs['project'], self.field_name: value} qs = self.ModelClass.objects.filter(**kwargs) if self.instance is not None: qs = qs.exclude(id=self.instance.id) if qs.exists(): opts = self.ModelClass._meta raise ValidationError({ self.field_name: self.message.format( model_name=opts.verbose_name.title(), field_name=opts.get_field(self.field_name).verbose_name ) }) ## Instruction: Make sure a project is set for the project-specific validator ## Code After: from rest_framework.serializers import ValidationError class UniqueToProjectValidator: message = u'{model_name} with this {field_name} already exists.' def __init__(self, field, message=None): self.field_name = field self.message = message or self.message def set_context(self, serializer): self.ModelClass = serializer.Meta.model self.instance = getattr(serializer, 'instance', None) self.project = serializer.context['request'].project def __call__(self, attrs): # Assuming that the field is always required if self.instance is not None: value = attrs.get(self.field_name, getattr(self.instance, self.field_name)) else: value = attrs[self.field_name] kwargs = {'project': self.project, self.field_name: value} qs = self.ModelClass.objects.filter(**kwargs) if self.instance is not None: qs = qs.exclude(id=self.instance.id) if qs.exists(): opts = self.ModelClass._meta raise ValidationError({ self.field_name: self.message.format( model_name=opts.verbose_name.title(), field_name=opts.get_field(self.field_name).verbose_name ) })
// ... existing code ... self.ModelClass = serializer.Meta.model self.instance = getattr(serializer, 'instance', None) self.project = serializer.context['request'].project def __call__(self, attrs): // ... modified code ... value = attrs[self.field_name] kwargs = {'project': self.project, self.field_name: value} qs = self.ModelClass.objects.filter(**kwargs) if self.instance is not None: // ... rest of the code ...
540c5f2969e75a0f461e9d46090cfe8d92c53b00
Simulator/plot.py
Simulator/plot.py
from Simulator import * import XMLParser import textToXML def getHistoryFileName(xmlFileName): y = xmlFileName[:-3] return 'history_' + y + 'txt' def plotFromXML(fileName,simulationTime,chemicalList): historyFile = getHistoryFileName(fileName) sim = XMLParser.getSimulator(fileName) sim.simulate(int(simulationTime),historyFile) sim.plot(chemicalList) def plotFromTxt(fileName,simulationTime,chemicalList): xmlFile = textToXML.getXMLFromTxt(fileName) plotFromXML(xmlFile,simulationTime,chemicalList)
from Simulator import * import XMLParser import textToXML def getHistoryFileName(xmlFileName): y = xmlFileName[:-3] y = y + 'txt' i = len(y) - 1 while i>=0 : if y[i]=='\\' or y[i]=='/' : break i-=1 if i>=0 : return y[:i+1] + 'history_' + y[i+1:] else: return 'history_' + y def plotFromXML(fileName,simulationTime,chemicalList): historyFile = getHistoryFileName(fileName) sim = XMLParser.getSimulator(fileName) sim.simulate(int(simulationTime),historyFile) sim.plot(chemicalList) def plotFromTxt(fileName,simulationTime,chemicalList): xmlFile = textToXML.getXMLFromTxt(fileName) plotFromXML(xmlFile,simulationTime,chemicalList)
Remove history name error for absolute paths
Remove history name error for absolute paths
Python
mit
aayushkapadia/chemical_reaction_simulator
from Simulator import * import XMLParser import textToXML + def getHistoryFileName(xmlFileName): y = xmlFileName[:-3] + y = y + 'txt' + + i = len(y) - 1 + while i>=0 : + if y[i]=='\\' or y[i]=='/' : + break + i-=1 + + if i>=0 : + return y[:i+1] + 'history_' + y[i+1:] + else: - return 'history_' + y + 'txt' + return 'history_' + y + def plotFromXML(fileName,simulationTime,chemicalList): historyFile = getHistoryFileName(fileName) sim = XMLParser.getSimulator(fileName) sim.simulate(int(simulationTime),historyFile) sim.plot(chemicalList) def plotFromTxt(fileName,simulationTime,chemicalList): xmlFile = textToXML.getXMLFromTxt(fileName) plotFromXML(xmlFile,simulationTime,chemicalList)
Remove history name error for absolute paths
## Code Before: from Simulator import * import XMLParser import textToXML def getHistoryFileName(xmlFileName): y = xmlFileName[:-3] return 'history_' + y + 'txt' def plotFromXML(fileName,simulationTime,chemicalList): historyFile = getHistoryFileName(fileName) sim = XMLParser.getSimulator(fileName) sim.simulate(int(simulationTime),historyFile) sim.plot(chemicalList) def plotFromTxt(fileName,simulationTime,chemicalList): xmlFile = textToXML.getXMLFromTxt(fileName) plotFromXML(xmlFile,simulationTime,chemicalList) ## Instruction: Remove history name error for absolute paths ## Code After: from Simulator import * import XMLParser import textToXML def getHistoryFileName(xmlFileName): y = xmlFileName[:-3] y = y + 'txt' i = len(y) - 1 while i>=0 : if y[i]=='\\' or y[i]=='/' : break i-=1 if i>=0 : return y[:i+1] + 'history_' + y[i+1:] else: return 'history_' + y def plotFromXML(fileName,simulationTime,chemicalList): historyFile = getHistoryFileName(fileName) sim = XMLParser.getSimulator(fileName) sim.simulate(int(simulationTime),historyFile) sim.plot(chemicalList) def plotFromTxt(fileName,simulationTime,chemicalList): xmlFile = textToXML.getXMLFromTxt(fileName) plotFromXML(xmlFile,simulationTime,chemicalList)
// ... existing code ... import textToXML def getHistoryFileName(xmlFileName): y = xmlFileName[:-3] y = y + 'txt' i = len(y) - 1 while i>=0 : if y[i]=='\\' or y[i]=='/' : break i-=1 if i>=0 : return y[:i+1] + 'history_' + y[i+1:] else: return 'history_' + y def plotFromXML(fileName,simulationTime,chemicalList): // ... rest of the code ...
342e6134a63c5b575ae8e4348a54f61350bca2da
parser/crimeparser/pipelinesEnricher.py
parser/crimeparser/pipelinesEnricher.py
from geopy import Nominatim from geopy.extra.rate_limiter import RateLimiter class GeoCodePipeline(object): def open_spider(self, spider): geolocator = Nominatim(timeout=5) self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2) def process_item(self, item, spider): for crime in item["crimes"]: place = crime["place"] latitude, longitude = self.__geocode_address(place) crime["latitude"] = latitude crime["longitude"] = longitude return item def __geocode_address(self, place): if place is None: return None, None location = self.__geocodeFunc(place) if location is not None: return location.latitude, location.longitude else: return None, None
from geopy import Nominatim, Photon from geopy.extra.rate_limiter import RateLimiter class GeoCodePipeline(object): def open_spider(self, spider): geolocator = Photon(timeout=5) self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2) def process_item(self, item, spider): for crime in item["crimes"]: place = crime["place"] latitude, longitude = self.__geocode_address(place) crime["latitude"] = latitude crime["longitude"] = longitude return item def __geocode_address(self, place): if place is None: return None, None location = self.__geocodeFunc(place) if location is not None: return location.latitude, location.longitude else: return None, None
Use Phonon instead of Nominatim for geo coding
Use Phonon instead of Nominatim for geo coding Phonon is more fault tolerant to spelling mistakes.
Python
mit
aberklotz/crimereport,aberklotz/crimereport,aberklotz/crimereport
- from geopy import Nominatim + from geopy import Nominatim, Photon from geopy.extra.rate_limiter import RateLimiter class GeoCodePipeline(object): def open_spider(self, spider): - geolocator = Nominatim(timeout=5) + geolocator = Photon(timeout=5) self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2) def process_item(self, item, spider): for crime in item["crimes"]: place = crime["place"] latitude, longitude = self.__geocode_address(place) crime["latitude"] = latitude crime["longitude"] = longitude return item def __geocode_address(self, place): if place is None: return None, None location = self.__geocodeFunc(place) if location is not None: return location.latitude, location.longitude else: return None, None
Use Phonon instead of Nominatim for geo coding
## Code Before: from geopy import Nominatim from geopy.extra.rate_limiter import RateLimiter class GeoCodePipeline(object): def open_spider(self, spider): geolocator = Nominatim(timeout=5) self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2) def process_item(self, item, spider): for crime in item["crimes"]: place = crime["place"] latitude, longitude = self.__geocode_address(place) crime["latitude"] = latitude crime["longitude"] = longitude return item def __geocode_address(self, place): if place is None: return None, None location = self.__geocodeFunc(place) if location is not None: return location.latitude, location.longitude else: return None, None ## Instruction: Use Phonon instead of Nominatim for geo coding ## Code After: from geopy import Nominatim, Photon from geopy.extra.rate_limiter import RateLimiter class GeoCodePipeline(object): def open_spider(self, spider): geolocator = Photon(timeout=5) self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2) def process_item(self, item, spider): for crime in item["crimes"]: place = crime["place"] latitude, longitude = self.__geocode_address(place) crime["latitude"] = latitude crime["longitude"] = longitude return item def __geocode_address(self, place): if place is None: return None, None location = self.__geocodeFunc(place) if location is not None: return location.latitude, location.longitude else: return None, None
# ... existing code ... from geopy import Nominatim, Photon from geopy.extra.rate_limiter import RateLimiter # ... modified code ... def open_spider(self, spider): geolocator = Photon(timeout=5) self.__geocodeFunc = RateLimiter(geolocator.geocode, min_delay_seconds=2) # ... rest of the code ...
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), )
# ... existing code ... from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, VPC, VPCGatewayAttachment, ) # ... modified code ... 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), ) # ... rest of the code ...
e7627ee439e2e4f17466bf124629ae353460a68d
__init__.py
__init__.py
import test import afip import invoice import config import partner import account import country import report import currency import product # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
import test import afip import invoice import config import partner import account import country import report import currency # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Change product types are really dangerous!!!
[FIX] Change product types are really dangerous!!!
Python
agpl-3.0
odoo-l10n-ar/l10n_ar_invoice
import test import afip import invoice import config import partner import account import country import report import currency - import product # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Change product types are really dangerous!!!
## Code Before: import test import afip import invoice import config import partner import account import country import report import currency import product # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: ## Instruction: Change product types are really dangerous!!! ## Code After: import test import afip import invoice import config import partner import account import country import report import currency # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
// ... existing code ... import report import currency # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: // ... rest of the code ...
219c474860ca7674070ef19fa95f0282b7c92399
mpages/admin.py
mpages/admin.py
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
Order parents in Admin select field
Order parents in Admin select field
Python
bsd-3-clause
ahernp/DMCM,ahernp/DMCM,ahernp/DMCM
from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) + def formfield_for_foreignkey(self, db_field, request, **kwargs): + if db_field.name == "parent": + kwargs["queryset"] = Page.objects.order_by("title") + return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) + admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
Order parents in Admin select field
## Code Before: from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag) ## Instruction: Order parents in Admin select field ## Code After: from django.contrib import admin from .models import Page, PageRead, Tag class PageAdmin(admin.ModelAdmin): search_fields = ["title"] list_display = ["title", "parent", "updated"] prepopulated_fields = {"slug": ("title",)} readonly_fields = ["updated"] ordering = ["parent", "title"] filter_horizontal = ("tags",) save_on_top = True fieldsets = ( ( None, { "fields": ( ("content",), ("title", "parent"), ("slug", "updated"), ("tags",), ) }, ), ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) admin.site.register(PageRead) admin.site.register(Tag)
// ... existing code ... ) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "parent": kwargs["queryset"] = Page.objects.order_by("title") return super(PageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) admin.site.register(Page, PageAdmin) // ... rest of the code ...
9532a28dacefec67ea67f94cf992a505d8a6629d
utilities/ticker-update.py
utilities/ticker-update.py
import requests from bs4 import BeautifulSoup URL = 'https://finance.yahoo.com/quote/' secutities = [] with open("ticker-updates,cong", r) as conf_file: securities = conf_file.readlines() securities = [s.strip() for s in securities] for security in securities: query = URL + security page = requests.get(query) soup = BeautifulSoup(page.content, 'html.parser') span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}) price = span.get_text() table_row = soup.select('table td') open = table_row[3].text print(f"{security:>6}: {open:<6} {price:<6}")
import requests from bs4 import BeautifulSoup URL = 'https://finance.yahoo.com/quote/' CONF_FILE = "ticker-updates.conf" secutities = [] with open(CONF_FILE, "r") as conf_file: securities = conf_file.readlines() securities = [s.strip() for s in securities] print(securities) for security in securities: print(security) symbol, sell_price = security.split(',') print(f"sy: {symbol} p: {sell_price}") query = URL + symbol page = requests.get(query) soup = BeautifulSoup(page.content, 'html.parser') span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}) price = float(span.get_text()) table_row = soup.select('table td') open = float(table_row[3].text) print(f"{symbol:>6}: {sell_price:<6} {open:<6} {price:<6} {open - price:<6}")
Fix file read, start on sell price
Fix file read, start on sell price
Python
mit
daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various
import requests from bs4 import BeautifulSoup URL = 'https://finance.yahoo.com/quote/' + CONF_FILE = "ticker-updates.conf" secutities = [] - with open("ticker-updates,cong", r) as conf_file: + with open(CONF_FILE, "r") as conf_file: securities = conf_file.readlines() securities = [s.strip() for s in securities] + print(securities) for security in securities: + print(security) + symbol, sell_price = security.split(',') + print(f"sy: {symbol} p: {sell_price}") - query = URL + security + query = URL + symbol page = requests.get(query) soup = BeautifulSoup(page.content, 'html.parser') span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}) - price = span.get_text() + price = float(span.get_text()) table_row = soup.select('table td') - open = table_row[3].text + open = float(table_row[3].text) - print(f"{security:>6}: {open:<6} {price:<6}") + print(f"{symbol:>6}: {sell_price:<6} {open:<6} {price:<6} {open - price:<6}")
Fix file read, start on sell price
## Code Before: import requests from bs4 import BeautifulSoup URL = 'https://finance.yahoo.com/quote/' secutities = [] with open("ticker-updates,cong", r) as conf_file: securities = conf_file.readlines() securities = [s.strip() for s in securities] for security in securities: query = URL + security page = requests.get(query) soup = BeautifulSoup(page.content, 'html.parser') span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}) price = span.get_text() table_row = soup.select('table td') open = table_row[3].text print(f"{security:>6}: {open:<6} {price:<6}") ## Instruction: Fix file read, start on sell price ## Code After: import requests from bs4 import BeautifulSoup URL = 'https://finance.yahoo.com/quote/' CONF_FILE = "ticker-updates.conf" secutities = [] with open(CONF_FILE, "r") as conf_file: securities = conf_file.readlines() securities = [s.strip() for s in securities] print(securities) for security in securities: print(security) symbol, sell_price = security.split(',') print(f"sy: {symbol} p: {sell_price}") query = URL + symbol page = requests.get(query) soup = BeautifulSoup(page.content, 'html.parser') span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}) price = float(span.get_text()) table_row = soup.select('table td') open = float(table_row[3].text) print(f"{symbol:>6}: {sell_price:<6} {open:<6} {price:<6} {open - price:<6}")
... URL = 'https://finance.yahoo.com/quote/' CONF_FILE = "ticker-updates.conf" secutities = [] with open(CONF_FILE, "r") as conf_file: securities = conf_file.readlines() securities = [s.strip() for s in securities] print(securities) for security in securities: print(security) symbol, sell_price = security.split(',') print(f"sy: {symbol} p: {sell_price}") query = URL + symbol page = requests.get(query) ... soup = BeautifulSoup(page.content, 'html.parser') span = soup.find('span', {'class': "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)"}) price = float(span.get_text()) table_row = soup.select('table td') open = float(table_row[3].text) print(f"{symbol:>6}: {sell_price:<6} {open:<6} {price:<6} {open - price:<6}") ...
04b785a9761e4d49c3f0e3dfc5d3df06cd3209a1
coffer/utils/ccopy.py
coffer/utils/ccopy.py
import os import shutil def copy(orig, dest, useShutil=False): if os.path.isdir(orig): if useShutil: shutil.copytree(orig, dest, symlinks=True) else: os.popen("cp -rf {} {}".format(orig, dest)) else: if useShutil: shutil.copy(orig, dest) else: os.popen("cp {} {}".format(orig, dest))
import os import shutil def copy(orig, dest, useShutil=False): if os.path.isdir(orig): if useShutil: shutil.copytree(orig, dest, symlinks=True) else: os.system("cp -rf {} {}".format(orig, dest)) else: if useShutil: shutil.copy(orig, dest) else: os.system("cp {} {}".format(orig, dest))
Copy now waits for files to be copies over
Copy now waits for files to be copies over
Python
mit
Max00355/Coffer
import os import shutil def copy(orig, dest, useShutil=False): if os.path.isdir(orig): if useShutil: shutil.copytree(orig, dest, symlinks=True) else: - os.popen("cp -rf {} {}".format(orig, dest)) + os.system("cp -rf {} {}".format(orig, dest)) else: if useShutil: shutil.copy(orig, dest) else: - os.popen("cp {} {}".format(orig, dest)) + os.system("cp {} {}".format(orig, dest))
Copy now waits for files to be copies over
## Code Before: import os import shutil def copy(orig, dest, useShutil=False): if os.path.isdir(orig): if useShutil: shutil.copytree(orig, dest, symlinks=True) else: os.popen("cp -rf {} {}".format(orig, dest)) else: if useShutil: shutil.copy(orig, dest) else: os.popen("cp {} {}".format(orig, dest)) ## Instruction: Copy now waits for files to be copies over ## Code After: import os import shutil def copy(orig, dest, useShutil=False): if os.path.isdir(orig): if useShutil: shutil.copytree(orig, dest, symlinks=True) else: os.system("cp -rf {} {}".format(orig, dest)) else: if useShutil: shutil.copy(orig, dest) else: os.system("cp {} {}".format(orig, dest))
# ... existing code ... shutil.copytree(orig, dest, symlinks=True) else: os.system("cp -rf {} {}".format(orig, dest)) else: if useShutil: # ... modified code ... shutil.copy(orig, dest) else: os.system("cp {} {}".format(orig, dest)) # ... rest of the code ...
126c58d78360e69c2d16a40f9396a8158844e2b1
tests/test_creators.py
tests/test_creators.py
def test_matrix_creation_endpoint(client): response = client.post('/matrix', { 'bibliography': '12312312', 'fields': 'title,description', }) print(response.json()) assert response.status_code == 200
from condor.models import Bibliography def test_matrix_creation_endpoint(client, session): bib = Bibliography(eid='123', description='lorem') session.add(bib) session.flush() response = client.post('/matrix', { 'bibliography': '123', 'fields': 'title,description', }) response = client.get(f"/matrix/{response.json().get('eid')}") assert response.status_code == 200 assert response.json().get('bibliography_eid') == '123'
Create test for matrix post endpoint
Create test for matrix post endpoint
Python
mit
odarbelaeze/condor-api
+ from condor.models import Bibliography - def test_matrix_creation_endpoint(client): + def test_matrix_creation_endpoint(client, session): + bib = Bibliography(eid='123', description='lorem') + session.add(bib) + session.flush() + response = client.post('/matrix', { - 'bibliography': '12312312', + 'bibliography': '123', 'fields': 'title,description', }) - print(response.json()) + + response = client.get(f"/matrix/{response.json().get('eid')}") + assert response.status_code == 200 + assert response.json().get('bibliography_eid') == '123'
Create test for matrix post endpoint
## Code Before: def test_matrix_creation_endpoint(client): response = client.post('/matrix', { 'bibliography': '12312312', 'fields': 'title,description', }) print(response.json()) assert response.status_code == 200 ## Instruction: Create test for matrix post endpoint ## Code After: from condor.models import Bibliography def test_matrix_creation_endpoint(client, session): bib = Bibliography(eid='123', description='lorem') session.add(bib) session.flush() response = client.post('/matrix', { 'bibliography': '123', 'fields': 'title,description', }) response = client.get(f"/matrix/{response.json().get('eid')}") assert response.status_code == 200 assert response.json().get('bibliography_eid') == '123'
// ... existing code ... from condor.models import Bibliography def test_matrix_creation_endpoint(client, session): bib = Bibliography(eid='123', description='lorem') session.add(bib) session.flush() response = client.post('/matrix', { 'bibliography': '123', 'fields': 'title,description', }) response = client.get(f"/matrix/{response.json().get('eid')}") assert response.status_code == 200 assert response.json().get('bibliography_eid') == '123' // ... rest of the code ...
b7c52258d39e5c0ee8fba2be87e8e671e0c583c3
xclib/postfix_io.py
xclib/postfix_io.py
import sys import re import logging # Message formats described in `../doc/Protocol.md` class postfix_io: @classmethod def read_request(cls, infd, outfd): # "for line in sys.stdin:" would be more concise but adds unwanted buffering while True: line = infd.readline() if not line: break match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line) if match: yield ('isuser',) + match.group(1,2) else: logging.error('Illegal request format: ' + line) outfd.write('500 Illegal request format\n') outfd.flush() @classmethod def write_response(cls, flag, outfd): if flag == None: outfd.write('400 Trouble connecting to backend\n') elif flag: outfd.write('200 OK\n') else: outfd.write('500 No such user\n') outfd.flush()
import sys import re import logging # Message formats described in `../doc/Protocol.md` class postfix_io: @classmethod def read_request(cls, infd, outfd): # "for line in sys.stdin:" would be more concise but adds unwanted buffering while True: line = infd.readline() if not line: break match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line) if match: yield ('isuser',) + match.group(1,2) elif line == 'quit': yield ('quit',) else: logging.error('Illegal request format: ' + line) outfd.write('500 Illegal request format\n') outfd.flush() @classmethod def write_response(cls, flag, outfd): if flag == None: outfd.write('400 Trouble connecting to backend\n') elif flag: outfd.write('200 OK\n') else: outfd.write('500 No such user\n') outfd.flush()
Add quit command to postfix
Add quit command to postfix
Python
mit
jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth,jsxc/xmpp-cloud-auth
import sys import re import logging # Message formats described in `../doc/Protocol.md` class postfix_io: @classmethod def read_request(cls, infd, outfd): # "for line in sys.stdin:" would be more concise but adds unwanted buffering while True: line = infd.readline() if not line: break match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line) if match: yield ('isuser',) + match.group(1,2) + elif line == 'quit': + yield ('quit',) else: logging.error('Illegal request format: ' + line) outfd.write('500 Illegal request format\n') outfd.flush() @classmethod def write_response(cls, flag, outfd): if flag == None: outfd.write('400 Trouble connecting to backend\n') elif flag: outfd.write('200 OK\n') else: outfd.write('500 No such user\n') outfd.flush()
Add quit command to postfix
## Code Before: import sys import re import logging # Message formats described in `../doc/Protocol.md` class postfix_io: @classmethod def read_request(cls, infd, outfd): # "for line in sys.stdin:" would be more concise but adds unwanted buffering while True: line = infd.readline() if not line: break match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line) if match: yield ('isuser',) + match.group(1,2) else: logging.error('Illegal request format: ' + line) outfd.write('500 Illegal request format\n') outfd.flush() @classmethod def write_response(cls, flag, outfd): if flag == None: outfd.write('400 Trouble connecting to backend\n') elif flag: outfd.write('200 OK\n') else: outfd.write('500 No such user\n') outfd.flush() ## Instruction: Add quit command to postfix ## Code After: import sys import re import logging # Message formats described in `../doc/Protocol.md` class postfix_io: @classmethod def read_request(cls, infd, outfd): # "for line in sys.stdin:" would be more concise but adds unwanted buffering while True: line = infd.readline() if not line: break match = re.match('^get ([^\000- @%]+)@([^\000- @%]+)\r?\n$', line) if match: yield ('isuser',) + match.group(1,2) elif line == 'quit': yield ('quit',) else: logging.error('Illegal request format: ' + line) outfd.write('500 Illegal request format\n') outfd.flush() @classmethod def write_response(cls, flag, outfd): if flag == None: outfd.write('400 Trouble connecting to backend\n') elif flag: outfd.write('200 OK\n') else: outfd.write('500 No such user\n') outfd.flush()
... if match: yield ('isuser',) + match.group(1,2) elif line == 'quit': yield ('quit',) else: logging.error('Illegal request format: ' + line) ...
761b0a959882499b629d9bc3fbd1b971beaf66a5
mymodule/blueprints/api_v1/__init__.py
mymodule/blueprints/api_v1/__init__.py
import flask from flask import current_app as app from werkzeug import exceptions from mymodule.blueprints.api_v1 import upload blueprint = flask.Blueprint('v1', __name__, url_prefix='/api/v1') blueprint.add_url_rule('/upload', view_func=upload.post, methods=['POST']) @blueprint.route('/test') def index(): app.logger.info('TEST %d', 1) return flask.jsonify(key='value') @blueprint.route('/error') def error(): raise Exception('oh, oh!') @blueprint.route('/keys') def keys(): code = flask.request.args['code'] return flask.jsonify(key=code) @blueprint.route('/config') def config(): ns = app.config.get_namespace('MYMODULE_') return flask.jsonify(ns) @blueprint.route('/crud') def crud_get(): return flask.jsonify(method=flask.request.method) @blueprint.route('/crud', methods=['POST']) def crud_post(): payload = flask.request.get_json() if payload is None: raise exceptions.BadRequest('no post data') return flask.jsonify(args=payload) @blueprint.errorhandler(exceptions.BadRequestKeyError) def bad_request_key_error(e): message = 'missing \'%s\' parameter' % e.args[0] return flask.jsonify(error=message), e.code
import flask from flask import current_app as app from werkzeug import exceptions from . import upload blueprint = flask.Blueprint('v1', __name__, url_prefix='/api/v1') blueprint.add_url_rule('/upload', view_func=upload.post, methods=['POST']) @blueprint.route('/test') def index(): app.logger.info('TEST %d', 1) return flask.jsonify(key='value') @blueprint.route('/error') def error(): raise Exception('oh, oh!') @blueprint.route('/keys') def keys(): code = flask.request.args['code'] return flask.jsonify(key=code) @blueprint.route('/config') def config(): ns = app.config.get_namespace('MYMODULE_') return flask.jsonify(ns) @blueprint.route('/crud') def crud_get(): return flask.jsonify(method=flask.request.method) @blueprint.route('/crud', methods=['POST']) def crud_post(): payload = flask.request.get_json() if payload is None: raise exceptions.BadRequest('no post data') return flask.jsonify(args=payload) @blueprint.errorhandler(exceptions.BadRequestKeyError) def bad_request_key_error(e): message = 'missing \'%s\' parameter' % e.args[0] return flask.jsonify(error=message), e.code
Simplify import of api_v1 subpackage.
Simplify import of api_v1 subpackage.
Python
mit
eduardobmc/flask-test
import flask from flask import current_app as app from werkzeug import exceptions - from mymodule.blueprints.api_v1 import upload + from . import upload blueprint = flask.Blueprint('v1', __name__, url_prefix='/api/v1') blueprint.add_url_rule('/upload', view_func=upload.post, methods=['POST']) @blueprint.route('/test') def index(): app.logger.info('TEST %d', 1) return flask.jsonify(key='value') @blueprint.route('/error') def error(): raise Exception('oh, oh!') @blueprint.route('/keys') def keys(): code = flask.request.args['code'] return flask.jsonify(key=code) @blueprint.route('/config') def config(): ns = app.config.get_namespace('MYMODULE_') return flask.jsonify(ns) @blueprint.route('/crud') def crud_get(): return flask.jsonify(method=flask.request.method) @blueprint.route('/crud', methods=['POST']) def crud_post(): payload = flask.request.get_json() if payload is None: raise exceptions.BadRequest('no post data') return flask.jsonify(args=payload) @blueprint.errorhandler(exceptions.BadRequestKeyError) def bad_request_key_error(e): message = 'missing \'%s\' parameter' % e.args[0] return flask.jsonify(error=message), e.code
Simplify import of api_v1 subpackage.
## Code Before: import flask from flask import current_app as app from werkzeug import exceptions from mymodule.blueprints.api_v1 import upload blueprint = flask.Blueprint('v1', __name__, url_prefix='/api/v1') blueprint.add_url_rule('/upload', view_func=upload.post, methods=['POST']) @blueprint.route('/test') def index(): app.logger.info('TEST %d', 1) return flask.jsonify(key='value') @blueprint.route('/error') def error(): raise Exception('oh, oh!') @blueprint.route('/keys') def keys(): code = flask.request.args['code'] return flask.jsonify(key=code) @blueprint.route('/config') def config(): ns = app.config.get_namespace('MYMODULE_') return flask.jsonify(ns) @blueprint.route('/crud') def crud_get(): return flask.jsonify(method=flask.request.method) @blueprint.route('/crud', methods=['POST']) def crud_post(): payload = flask.request.get_json() if payload is None: raise exceptions.BadRequest('no post data') return flask.jsonify(args=payload) @blueprint.errorhandler(exceptions.BadRequestKeyError) def bad_request_key_error(e): message = 'missing \'%s\' parameter' % e.args[0] return flask.jsonify(error=message), e.code ## Instruction: Simplify import of api_v1 subpackage. ## Code After: import flask from flask import current_app as app from werkzeug import exceptions from . import upload blueprint = flask.Blueprint('v1', __name__, url_prefix='/api/v1') blueprint.add_url_rule('/upload', view_func=upload.post, methods=['POST']) @blueprint.route('/test') def index(): app.logger.info('TEST %d', 1) return flask.jsonify(key='value') @blueprint.route('/error') def error(): raise Exception('oh, oh!') @blueprint.route('/keys') def keys(): code = flask.request.args['code'] return flask.jsonify(key=code) @blueprint.route('/config') def config(): ns = app.config.get_namespace('MYMODULE_') return flask.jsonify(ns) @blueprint.route('/crud') def crud_get(): return flask.jsonify(method=flask.request.method) @blueprint.route('/crud', methods=['POST']) def crud_post(): payload = flask.request.get_json() if payload is None: raise exceptions.BadRequest('no post data') return flask.jsonify(args=payload) @blueprint.errorhandler(exceptions.BadRequestKeyError) def bad_request_key_error(e): message = 'missing \'%s\' parameter' % e.args[0] return flask.jsonify(error=message), e.code
// ... existing code ... from werkzeug import exceptions from . import upload // ... rest of the code ...
df4d4f2972d8d1a91ce4353343c6279580985e3c
index.py
index.py
from __future__ import division import urllib.request as request, json, os.path import json, time if os.path.exists('config/config.json'): config_file = open('config/config.json') config = json.load(config_file) else: print('Please copy the config.json file to config-local.json and fill in the file.') exit() print(time.strftime("%x") + ": Eagle woke up") total_volume = 0 symbols = ','.join(config['currencies']) url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols with request.urlopen(url) as response: rates = json.loads(response.read().decode('utf-8'))['rates'] for currency in config['currencies'].keys(): if currency not in rates: print("Cryptocurrency", currency, "does not exist.") continue total_volume += rates[currency] * config['currencies'][currency]['balance'] print("Total euro : " + str(total_volume) + " eur")
from __future__ import division import urllib.request as request, json, os.path import json, time if os.path.exists('config/config.json'): config_file = open('config/config.json') config = json.load(config_file) else: print('Please copy the config.json.template file to config.json and fill in the file.') exit() print(time.strftime("%x") + ": Eagle woke up") total_volume = 0 symbols = ','.join(config['currencies']) url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols with request.urlopen(url) as response: rates = json.loads(response.read().decode('utf-8'))['rates'] for currency in config['currencies'].keys(): if currency not in rates: print("Cryptocurrency", currency, "does not exist.") continue total_volume += rates[currency] * config['currencies'][currency]['balance'] print("Total euro : " + str(total_volume) + " eur")
Change print statement about config
Change print statement about config
Python
mit
pkakelas/eagle
from __future__ import division import urllib.request as request, json, os.path import json, time if os.path.exists('config/config.json'): config_file = open('config/config.json') config = json.load(config_file) else: - print('Please copy the config.json file to config-local.json and fill in the file.') + print('Please copy the config.json.template file to config.json and fill in the file.') exit() print(time.strftime("%x") + ": Eagle woke up") total_volume = 0 symbols = ','.join(config['currencies']) url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols with request.urlopen(url) as response: rates = json.loads(response.read().decode('utf-8'))['rates'] for currency in config['currencies'].keys(): if currency not in rates: print("Cryptocurrency", currency, "does not exist.") continue total_volume += rates[currency] * config['currencies'][currency]['balance'] print("Total euro : " + str(total_volume) + " eur")
Change print statement about config
## Code Before: from __future__ import division import urllib.request as request, json, os.path import json, time if os.path.exists('config/config.json'): config_file = open('config/config.json') config = json.load(config_file) else: print('Please copy the config.json file to config-local.json and fill in the file.') exit() print(time.strftime("%x") + ": Eagle woke up") total_volume = 0 symbols = ','.join(config['currencies']) url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols with request.urlopen(url) as response: rates = json.loads(response.read().decode('utf-8'))['rates'] for currency in config['currencies'].keys(): if currency not in rates: print("Cryptocurrency", currency, "does not exist.") continue total_volume += rates[currency] * config['currencies'][currency]['balance'] print("Total euro : " + str(total_volume) + " eur") ## Instruction: Change print statement about config ## Code After: from __future__ import division import urllib.request as request, json, os.path import json, time if os.path.exists('config/config.json'): config_file = open('config/config.json') config = json.load(config_file) else: print('Please copy the config.json.template file to config.json and fill in the file.') exit() print(time.strftime("%x") + ": Eagle woke up") total_volume = 0 symbols = ','.join(config['currencies']) url = "http://api.coinlayer.com/api/live?access_key=" + config['coinlayer'] + "&target=EUR&symbols=" + symbols with request.urlopen(url) as response: rates = json.loads(response.read().decode('utf-8'))['rates'] for currency in config['currencies'].keys(): if currency not in rates: print("Cryptocurrency", currency, "does not exist.") continue total_volume += rates[currency] * config['currencies'][currency]['balance'] print("Total euro : " + str(total_volume) + " eur")
# ... existing code ... config = json.load(config_file) else: print('Please copy the config.json.template file to config.json and fill in the file.') exit() # ... rest of the code ...
264075d9b313f5c2677e32fcf5d340bba73f0b0e
corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py
corehq/apps/app_manager/migrations/0019_exchangeapplication_required_privileges.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_manager', '0018_migrate_case_search_labels'), ] operations = [ migrations.AddField( model_name='exchangeapplication', name='required_privileges', field=models.TextField(null=True), ), ]
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_manager', '0018_migrate_case_search_labels'), ] operations = [ migrations.AddField( model_name='exchangeapplication', name='required_privileges', field=models.TextField(help_text='Space-separated list of privilege strings from corehq.privileges', null=True), ), ]
Fix migration with help text
Fix migration with help text
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_manager', '0018_migrate_case_search_labels'), ] operations = [ migrations.AddField( model_name='exchangeapplication', name='required_privileges', - field=models.TextField(null=True), + field=models.TextField(help_text='Space-separated list of privilege strings from corehq.privileges', null=True), ), ]
Fix migration with help text
## Code Before: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_manager', '0018_migrate_case_search_labels'), ] operations = [ migrations.AddField( model_name='exchangeapplication', name='required_privileges', field=models.TextField(null=True), ), ] ## Instruction: Fix migration with help text ## Code After: from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_manager', '0018_migrate_case_search_labels'), ] operations = [ migrations.AddField( model_name='exchangeapplication', name='required_privileges', field=models.TextField(help_text='Space-separated list of privilege strings from corehq.privileges', null=True), ), ]
... model_name='exchangeapplication', name='required_privileges', field=models.TextField(help_text='Space-separated list of privilege strings from corehq.privileges', null=True), ), ] ...
7c68e3b00e7c66c0223617447e16a7159118d284
goldstone/addons/utils.py
goldstone/addons/utils.py
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. """ from goldstone.core.models import Addon Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on")
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. This also differs from update_xxxxx_nodes by returning the Addon node that is found or created. """ from goldstone.core.models import Addon result, _ = Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") return result
Change update_addon_node() to return the Addon node, whether created or found.
Change update_addon_node() to return the Addon node, whether created or found.
Python
apache-2.0
slashk/goldstone-server,slashk/goldstone-server,Solinea/goldstone-server,slashk/goldstone-server,slashk/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,Solinea/goldstone-server,slashk/goldstone-server
"""Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. + This also differs from update_xxxxx_nodes by returning the Addon node that + is found or created. + """ from goldstone.core.models import Addon - Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") + result, _ = Addon.objects.get_or_create(native_id="Add-on", + native_name="Add-on") + return result +
Change update_addon_node() to return the Addon node, whether created or found.
## Code Before: """Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. """ from goldstone.core.models import Addon Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") ## Instruction: Change update_addon_node() to return the Addon node, whether created or found. ## Code After: """Addon utilities.""" # Copyright 2015 Solinea, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def update_addon_node(): """Update the persistent resource graph's Addon node. This is much simpler than the update_xxxxx_nodes functions that update nodes for cloud entities. There will be only one Addon node in the table, and all add-ons will be owned by it. If we're running for the first time, the Addon node needs to be created. If it's already there, we leave it alone. This also differs from update_xxxxx_nodes by returning the Addon node that is found or created. """ from goldstone.core.models import Addon result, _ = Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") return result
... alone. This also differs from update_xxxxx_nodes by returning the Addon node that is found or created. """ from goldstone.core.models import Addon result, _ = Addon.objects.get_or_create(native_id="Add-on", native_name="Add-on") return result ...
c6dae4cbd8d8dcbcd323526c2811fea9525bcb74
__init__.py
__init__.py
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
Add an event module import
Add an event module import
Python
lgpl-2.1
platipy/spyral
import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib + import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
Add an event module import
## Code Before: import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import pygame director = scene.Director() def init(): pygame.init() pygame.font.init() ## Instruction: Add an event module import ## Code After: import spyral.memoize import spyral.point import spyral.camera import spyral.util import spyral.sprite import spyral.gui import spyral.scene import spyral._lib import spyral.event import pygame director = scene.Director() def init(): pygame.init() pygame.font.init()
... import spyral.scene import spyral._lib import spyral.event import pygame ...
ea3660bcc1a9f7be619def8e26dd7b0ab4a873cf
estmator_project/est_client/forms.py
estmator_project/est_client/forms.py
from django.forms import ModelForm, Select, TextInput from .models import Client, Company class ClientCreateForm(ModelForm): class Meta: model = Client fields = [ 'company', 'first_name', 'last_name', 'title', 'cell', 'desk', 'email' ] widgets = { 'company': Select(attrs={'required': True}), } class CompanyCreateForm(ModelForm): class Meta: model = Company fields = [ 'company_name', 'phone', 'address', 'address2', 'city', 'state', 'postal', 'st_rate', 'ot_rate' ] widgets = { 'company_name': TextInput(attrs={'required': True}), } class CompanyListForm(ModelForm): class Meta: model = Client fields = ['company']
from django.forms import ModelForm, Select, TextInput from .models import Client, Company class ClientCreateForm(ModelForm): class Meta: model = Client fields = [ 'company', 'first_name', 'last_name', 'title', 'cell', 'desk', 'email' ] widgets = { 'company': Select(attrs={'required': True}), 'first_name': TextInput(attrs={'required': True}), 'last_name': TextInput(attrs={'required': True}), 'title': TextInput(attrs={'required': True}), 'cell': TextInput(attrs={'required': True}), 'email': TextInput(attrs={'required': True}), } class CompanyCreateForm(ModelForm): class Meta: model = Company fields = [ 'company_name', 'phone', 'address', 'address2', 'city', 'state', 'postal', 'st_rate', 'ot_rate' ] widgets = { 'company_name': TextInput(attrs={'required': True}), 'phone': TextInput(attrs={'required': True}), 'address': TextInput(attrs={'required': True}), 'city': TextInput(attrs={'required': True}), 'postal': TextInput(attrs={'required': True}), } class CompanyListForm(ModelForm): class Meta: model = Client fields = ['company']
Make fields required on new client and company
Make fields required on new client and company
Python
mit
Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp
from django.forms import ModelForm, Select, TextInput from .models import Client, Company class ClientCreateForm(ModelForm): class Meta: model = Client fields = [ 'company', 'first_name', 'last_name', 'title', 'cell', 'desk', 'email' ] widgets = { 'company': Select(attrs={'required': True}), + 'first_name': TextInput(attrs={'required': True}), + 'last_name': TextInput(attrs={'required': True}), + 'title': TextInput(attrs={'required': True}), + 'cell': TextInput(attrs={'required': True}), + 'email': TextInput(attrs={'required': True}), } class CompanyCreateForm(ModelForm): class Meta: model = Company fields = [ 'company_name', 'phone', 'address', 'address2', 'city', 'state', 'postal', 'st_rate', 'ot_rate' ] widgets = { 'company_name': TextInput(attrs={'required': True}), + 'phone': TextInput(attrs={'required': True}), + 'address': TextInput(attrs={'required': True}), + 'city': TextInput(attrs={'required': True}), + 'postal': TextInput(attrs={'required': True}), } class CompanyListForm(ModelForm): class Meta: model = Client fields = ['company']
Make fields required on new client and company
## Code Before: from django.forms import ModelForm, Select, TextInput from .models import Client, Company class ClientCreateForm(ModelForm): class Meta: model = Client fields = [ 'company', 'first_name', 'last_name', 'title', 'cell', 'desk', 'email' ] widgets = { 'company': Select(attrs={'required': True}), } class CompanyCreateForm(ModelForm): class Meta: model = Company fields = [ 'company_name', 'phone', 'address', 'address2', 'city', 'state', 'postal', 'st_rate', 'ot_rate' ] widgets = { 'company_name': TextInput(attrs={'required': True}), } class CompanyListForm(ModelForm): class Meta: model = Client fields = ['company'] ## Instruction: Make fields required on new client and company ## Code After: from django.forms import ModelForm, Select, TextInput from .models import Client, Company class ClientCreateForm(ModelForm): class Meta: model = Client fields = [ 'company', 'first_name', 'last_name', 'title', 'cell', 'desk', 'email' ] widgets = { 'company': Select(attrs={'required': True}), 'first_name': TextInput(attrs={'required': True}), 'last_name': TextInput(attrs={'required': True}), 'title': TextInput(attrs={'required': True}), 'cell': TextInput(attrs={'required': True}), 'email': TextInput(attrs={'required': True}), } class CompanyCreateForm(ModelForm): class Meta: model = Company fields = [ 'company_name', 'phone', 'address', 'address2', 'city', 'state', 'postal', 'st_rate', 'ot_rate' ] widgets = { 'company_name': TextInput(attrs={'required': True}), 'phone': TextInput(attrs={'required': True}), 'address': TextInput(attrs={'required': True}), 'city': TextInput(attrs={'required': True}), 'postal': TextInput(attrs={'required': True}), } class CompanyListForm(ModelForm): class Meta: model = Client fields = ['company']
// ... existing code ... widgets = { 'company': Select(attrs={'required': True}), 'first_name': TextInput(attrs={'required': True}), 'last_name': TextInput(attrs={'required': True}), 'title': TextInput(attrs={'required': True}), 'cell': TextInput(attrs={'required': True}), 'email': TextInput(attrs={'required': True}), } // ... modified code ... widgets = { 'company_name': TextInput(attrs={'required': True}), 'phone': TextInput(attrs={'required': True}), 'address': TextInput(attrs={'required': True}), 'city': TextInput(attrs={'required': True}), 'postal': TextInput(attrs={'required': True}), } // ... rest of the code ...
c7030e461026e718c46b86dadecc9681d226c27c
cupy/util.py
cupy/util.py
import atexit import functools from cupy import cuda _memoized_funcs = [] def memoize(for_each_device=False): """Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes the results for each device. Otherwise, it memoizes the results only based on the arguments. """ def decorator(f): global _memoized_funcs f._cupy_memo = {} _memoized_funcs.append(f) @functools.wraps(f) def ret(*args, **kwargs): arg_key = (args, frozenset(kwargs.items())) if for_each_device: arg_key = (cuda.Device().id, arg_key) memo = f._cupy_memo result = memo.get(arg_key, None) if result is None: result = f(*args, **kwargs) memo[arg_key] = result return result return ret return decorator @atexit.register def clear_memo(): """Clears the memoized results for all functions decorated by memoize.""" global _memoized_funcs for f in _memoized_funcs: del f._cupy_memo _memoized_funcs = []
import atexit import functools from cupy import cuda _memos = [] def memoize(for_each_device=False): """Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes the results for each device. Otherwise, it memoizes the results only based on the arguments. """ def decorator(f): memo = {} _memos.append(memo) @functools.wraps(f) def ret(*args, **kwargs): arg_key = (args, frozenset(kwargs.items())) if for_each_device: arg_key = (cuda.Device().id, arg_key) result = memo.get(arg_key, None) if result is None: result = f(*args, **kwargs) memo[arg_key] = result return result return ret return decorator @atexit.register def clear_memo(): """Clears the memoized results for all functions decorated by memoize.""" for memo in _memos: memo.clear()
Fix unintended late finalization of memoized functions
Fix unintended late finalization of memoized functions
Python
mit
ktnyt/chainer,niboshi/chainer,niboshi/chainer,laysakura/chainer,tscohen/chainer,benob/chainer,chainer/chainer,cupy/cupy,aonotas/chainer,cupy/cupy,jnishi/chainer,cupy/cupy,tkerola/chainer,cemoody/chainer,ktnyt/chainer,chainer/chainer,jnishi/chainer,jnishi/chainer,keisuke-umezawa/chainer,truongdq/chainer,kashif/chainer,wkentaro/chainer,ronekko/chainer,pfnet/chainer,delta2323/chainer,okuta/chainer,cupy/cupy,muupan/chainer,okuta/chainer,ysekky/chainer,hvy/chainer,chainer/chainer,truongdq/chainer,jnishi/chainer,keisuke-umezawa/chainer,t-abe/chainer,chainer/chainer,wkentaro/chainer,tigerneil/chainer,AlpacaDB/chainer,okuta/chainer,wkentaro/chainer,hvy/chainer,niboshi/chainer,ytoyama/yans_chainer_hackathon,sinhrks/chainer,keisuke-umezawa/chainer,ktnyt/chainer,kikusu/chainer,niboshi/chainer,rezoo/chainer,hvy/chainer,benob/chainer,sinhrks/chainer,anaruse/chainer,1986ks/chainer,ktnyt/chainer,sou81821/chainer,kikusu/chainer,okuta/chainer,kiyukuta/chainer,wkentaro/chainer,muupan/chainer,t-abe/chainer,AlpacaDB/chainer,Kaisuke5/chainer,minhpqn/chainer,hvy/chainer,keisuke-umezawa/chainer
import atexit import functools from cupy import cuda - _memoized_funcs = [] + _memos = [] def memoize(for_each_device=False): """Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes the results for each device. Otherwise, it memoizes the results only based on the arguments. """ def decorator(f): - global _memoized_funcs - f._cupy_memo = {} + memo = {} - _memoized_funcs.append(f) + _memos.append(memo) @functools.wraps(f) def ret(*args, **kwargs): arg_key = (args, frozenset(kwargs.items())) if for_each_device: arg_key = (cuda.Device().id, arg_key) - memo = f._cupy_memo result = memo.get(arg_key, None) if result is None: result = f(*args, **kwargs) memo[arg_key] = result return result return ret return decorator @atexit.register def clear_memo(): """Clears the memoized results for all functions decorated by memoize.""" + for memo in _memos: + memo.clear() - global _memoized_funcs - for f in _memoized_funcs: - del f._cupy_memo - _memoized_funcs = []
Fix unintended late finalization of memoized functions
## Code Before: import atexit import functools from cupy import cuda _memoized_funcs = [] def memoize(for_each_device=False): """Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes the results for each device. Otherwise, it memoizes the results only based on the arguments. """ def decorator(f): global _memoized_funcs f._cupy_memo = {} _memoized_funcs.append(f) @functools.wraps(f) def ret(*args, **kwargs): arg_key = (args, frozenset(kwargs.items())) if for_each_device: arg_key = (cuda.Device().id, arg_key) memo = f._cupy_memo result = memo.get(arg_key, None) if result is None: result = f(*args, **kwargs) memo[arg_key] = result return result return ret return decorator @atexit.register def clear_memo(): """Clears the memoized results for all functions decorated by memoize.""" global _memoized_funcs for f in _memoized_funcs: del f._cupy_memo _memoized_funcs = [] ## Instruction: Fix unintended late finalization of memoized functions ## Code After: import atexit import functools from cupy import cuda _memos = [] def memoize(for_each_device=False): """Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes the results for each device. Otherwise, it memoizes the results only based on the arguments. """ def decorator(f): memo = {} _memos.append(memo) @functools.wraps(f) def ret(*args, **kwargs): arg_key = (args, frozenset(kwargs.items())) if for_each_device: arg_key = (cuda.Device().id, arg_key) result = memo.get(arg_key, None) if result is None: result = f(*args, **kwargs) memo[arg_key] = result return result return ret return decorator @atexit.register def clear_memo(): """Clears the memoized results for all functions decorated by memoize.""" for memo in _memos: memo.clear()
// ... existing code ... _memos = [] // ... modified code ... """ def decorator(f): memo = {} _memos.append(memo) @functools.wraps(f) ... arg_key = (cuda.Device().id, arg_key) result = memo.get(arg_key, None) if result is None: ... def clear_memo(): """Clears the memoized results for all functions decorated by memoize.""" for memo in _memos: memo.clear() // ... rest of the code ...
b3f7b677edb0a87abff2ef64dadb64547d757d6b
elasticsearch_django/migrations/0004_auto_20161129_1135.py
elasticsearch_django/migrations/0004_auto_20161129_1135.py
from django.db import migrations from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
from django.contrib.postgres.fields import JSONField from django.db import migrations class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
Update migration to use native JSONField
Update migration to use native JSONField
Python
mit
yunojuno/elasticsearch-django
+ from django.contrib.postgres.fields import JSONField from django.db import migrations - - from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
Update migration to use native JSONField
## Code Before: from django.db import migrations from ..db.fields import JSONField class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ] ## Instruction: Update migration to use native JSONField ## Code After: from django.contrib.postgres.fields import JSONField from django.db import migrations class Migration(migrations.Migration): dependencies = [("elasticsearch_django", "0003_auto_20160926_2021")] operations = [ migrations.AlterField( model_name="searchquery", name="hits", field=JSONField( help_text="The list of meta info for each of the query matches returned." ), ), migrations.AlterField( model_name="searchquery", name="query", field=JSONField(help_text="The raw ElasticSearch DSL query."), ), ]
# ... existing code ... from django.contrib.postgres.fields import JSONField from django.db import migrations # ... rest of the code ...
609fcedf1aa90e0022c72121865452b3cbdd0ba3
icekit/plugins/content_listing/forms.py
icekit/plugins/content_listing/forms.py
from fluent_contents.forms import ContentItemForm #from icekit.content_collections.abstract_models import AbstractCollectedContent from .models import ContentListingItem class ContentListingAdminForm(ContentItemForm): class Meta: model = ContentListingItem fields = '__all__' # def __init__(self, *args, **kwargs): # super(ContentListingAdminForm, self).__init__(*args, **kwargs) # # TODO Restrict content types to those for models that are subclasses # # of `AbstractCollectedContent`? # valid_ct_ids = [] # cts_qs = self.fields['content_type'].queryset.all() # for ct in cts_qs: # model = ct.model_class() # if model and issubclass(model, AbstractCollectedContent): # valid_ct_ids.append(ct.id) # cts_qs = self.fields['content_type'].queryset = \ # cts_qs.filter(pk__in=valid_ct_ids)
from django.forms import ModelChoiceField from django.contrib.contenttypes.models import ContentType from fluent_contents.forms import ContentItemForm from .models import ContentListingItem class ContentTypeModelChoiceField(ModelChoiceField): def label_from_instance(self, content_type): return u".".join(content_type.natural_key()) class ContentListingAdminForm(ContentItemForm): content_type = ContentTypeModelChoiceField( queryset=ContentType.objects.all() ) class Meta: model = ContentListingItem fields = '__all__' def __init__(self, *args, **kwargs): super(ContentListingAdminForm, self).__init__(*args, **kwargs) # Apply `filter_content_types` filter self.fields['content_type'].queryset = self.filter_content_types( self.fields['content_type'].queryset) def filter_content_types(self, content_type_qs): """ Filter the content types selectable for the content listing. Example to restrict content types to those for models that are subclasses of `AbstractCollectedContent`: valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, AbstractCollectedContent): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids) """ return content_type_qs
Improve content listing plugin's admin form
Improve content listing plugin's admin form - show natural key of content types in select field to disambiguate the SELECT field listing in the admin - add `filter_content_types` method to form to simplify filtering the selectable content types in derived plugins.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
+ from django.forms import ModelChoiceField + from django.contrib.contenttypes.models import ContentType + from fluent_contents.forms import ContentItemForm - - #from icekit.content_collections.abstract_models import AbstractCollectedContent from .models import ContentListingItem + class ContentTypeModelChoiceField(ModelChoiceField): + + def label_from_instance(self, content_type): + return u".".join(content_type.natural_key()) + + class ContentListingAdminForm(ContentItemForm): + + content_type = ContentTypeModelChoiceField( + queryset=ContentType.objects.all() + ) class Meta: model = ContentListingItem fields = '__all__' - # def __init__(self, *args, **kwargs): + def __init__(self, *args, **kwargs): - # super(ContentListingAdminForm, self).__init__(*args, **kwargs) + super(ContentListingAdminForm, self).__init__(*args, **kwargs) + # Apply `filter_content_types` filter + self.fields['content_type'].queryset = self.filter_content_types( - # # TODO Restrict content types to those for models that are subclasses - # # of `AbstractCollectedContent`? - # valid_ct_ids = [] - # cts_qs = self.fields['content_type'].queryset.all() + self.fields['content_type'].queryset) - # for ct in cts_qs: - # model = ct.model_class() - # if model and issubclass(model, AbstractCollectedContent): - # valid_ct_ids.append(ct.id) - # cts_qs = self.fields['content_type'].queryset = \ - # cts_qs.filter(pk__in=valid_ct_ids) + def filter_content_types(self, content_type_qs): + """ + Filter the content types selectable for the content listing. + + Example to restrict content types to those for models that are + subclasses of `AbstractCollectedContent`: + + valid_ct_ids = [] + for ct in content_type_qs: + model = ct.model_class() + if model and issubclass(model, AbstractCollectedContent): + valid_ct_ids.append(ct.id) + return content_type_qs.filter(pk__in=valid_ct_ids) + """ + return content_type_qs +
Improve content listing plugin's admin form
## Code Before: from fluent_contents.forms import ContentItemForm #from icekit.content_collections.abstract_models import AbstractCollectedContent from .models import ContentListingItem class ContentListingAdminForm(ContentItemForm): class Meta: model = ContentListingItem fields = '__all__' # def __init__(self, *args, **kwargs): # super(ContentListingAdminForm, self).__init__(*args, **kwargs) # # TODO Restrict content types to those for models that are subclasses # # of `AbstractCollectedContent`? # valid_ct_ids = [] # cts_qs = self.fields['content_type'].queryset.all() # for ct in cts_qs: # model = ct.model_class() # if model and issubclass(model, AbstractCollectedContent): # valid_ct_ids.append(ct.id) # cts_qs = self.fields['content_type'].queryset = \ # cts_qs.filter(pk__in=valid_ct_ids) ## Instruction: Improve content listing plugin's admin form ## Code After: from django.forms import ModelChoiceField from django.contrib.contenttypes.models import ContentType from fluent_contents.forms import ContentItemForm from .models import ContentListingItem class ContentTypeModelChoiceField(ModelChoiceField): def label_from_instance(self, content_type): return u".".join(content_type.natural_key()) class ContentListingAdminForm(ContentItemForm): content_type = ContentTypeModelChoiceField( queryset=ContentType.objects.all() ) class Meta: model = ContentListingItem fields = '__all__' def __init__(self, *args, **kwargs): super(ContentListingAdminForm, self).__init__(*args, **kwargs) # Apply `filter_content_types` filter self.fields['content_type'].queryset = self.filter_content_types( self.fields['content_type'].queryset) def filter_content_types(self, content_type_qs): """ Filter the content types selectable for the content listing. Example to restrict content types to those for models that are subclasses of `AbstractCollectedContent`: valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, AbstractCollectedContent): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids) """ return content_type_qs
... from django.forms import ModelChoiceField from django.contrib.contenttypes.models import ContentType from fluent_contents.forms import ContentItemForm from .models import ContentListingItem ... class ContentTypeModelChoiceField(ModelChoiceField): def label_from_instance(self, content_type): return u".".join(content_type.natural_key()) class ContentListingAdminForm(ContentItemForm): content_type = ContentTypeModelChoiceField( queryset=ContentType.objects.all() ) class Meta: ... fields = '__all__' def __init__(self, *args, **kwargs): super(ContentListingAdminForm, self).__init__(*args, **kwargs) # Apply `filter_content_types` filter self.fields['content_type'].queryset = self.filter_content_types( self.fields['content_type'].queryset) def filter_content_types(self, content_type_qs): """ Filter the content types selectable for the content listing. Example to restrict content types to those for models that are subclasses of `AbstractCollectedContent`: valid_ct_ids = [] for ct in content_type_qs: model = ct.model_class() if model and issubclass(model, AbstractCollectedContent): valid_ct_ids.append(ct.id) return content_type_qs.filter(pk__in=valid_ct_ids) """ return content_type_qs ...
bd4ee91c964ce7fb506b722d4d93a8af019d4e7c
test/test_future_and_futures.py
test/test_future_and_futures.py
import imp import os import sys from django.test import TestCase from kolibri import dist as kolibri_dist dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0] == 3: # Python 3 is supposed to import its builtin package `concurrent` # instead of being inside kolibri/dist/py2only or kolibri/dist concurrent_parent_path = os.path.realpath( os.path.dirname(os.path.dirname(concurrent.__file__)) ) self.assertNotEqual(dist_dir, concurrent_parent_path) self.assertNotEqual( os.path.join(dist_dir, "py2only"), concurrent_parent_path ) def test_import_future_py2(self): from future.standard_library import TOP_LEVEL_MODULES if sys.version_info[0] == 2: for module_name in TOP_LEVEL_MODULES: if "test" in module_name: continue module_parent_path = os.path.realpath( os.path.dirname(imp.find_module(module_name)[1]) ) # future's standard libraries such as `html` should not be found # at the same level as kolibri/dist; otherwise, python3 will try to # import them from kolibri/dist instead of its builtin packages self.assertNotEqual(dist_dir, module_parent_path)
import imp import os import sys # Import from kolibri first to ensure Kolibri's monkey patches are applied. from kolibri import dist as kolibri_dist # noreorder from django.test import TestCase # noreorder dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0] == 3: # Python 3 is supposed to import its builtin package `concurrent` # instead of being inside kolibri/dist/py2only or kolibri/dist concurrent_parent_path = os.path.realpath( os.path.dirname(os.path.dirname(concurrent.__file__)) ) self.assertNotEqual(dist_dir, concurrent_parent_path) self.assertNotEqual( os.path.join(dist_dir, "py2only"), concurrent_parent_path ) def test_import_future_py2(self): from future.standard_library import TOP_LEVEL_MODULES if sys.version_info[0] == 2: for module_name in TOP_LEVEL_MODULES: if "test" in module_name: continue module_parent_path = os.path.realpath( os.path.dirname(imp.find_module(module_name)[1]) ) # future's standard libraries such as `html` should not be found # at the same level as kolibri/dist; otherwise, python3 will try to # import them from kolibri/dist instead of its builtin packages self.assertNotEqual(dist_dir, module_parent_path)
Fix import order in tests.
Fix import order in tests.
Python
mit
learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri
import imp import os import sys - from django.test import TestCase + # Import from kolibri first to ensure Kolibri's monkey patches are applied. + from kolibri import dist as kolibri_dist # noreorder - from kolibri import dist as kolibri_dist + from django.test import TestCase # noreorder dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0] == 3: # Python 3 is supposed to import its builtin package `concurrent` # instead of being inside kolibri/dist/py2only or kolibri/dist concurrent_parent_path = os.path.realpath( os.path.dirname(os.path.dirname(concurrent.__file__)) ) self.assertNotEqual(dist_dir, concurrent_parent_path) self.assertNotEqual( os.path.join(dist_dir, "py2only"), concurrent_parent_path ) def test_import_future_py2(self): from future.standard_library import TOP_LEVEL_MODULES if sys.version_info[0] == 2: for module_name in TOP_LEVEL_MODULES: if "test" in module_name: continue module_parent_path = os.path.realpath( os.path.dirname(imp.find_module(module_name)[1]) ) # future's standard libraries such as `html` should not be found # at the same level as kolibri/dist; otherwise, python3 will try to # import them from kolibri/dist instead of its builtin packages self.assertNotEqual(dist_dir, module_parent_path)
Fix import order in tests.
## Code Before: import imp import os import sys from django.test import TestCase from kolibri import dist as kolibri_dist dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0] == 3: # Python 3 is supposed to import its builtin package `concurrent` # instead of being inside kolibri/dist/py2only or kolibri/dist concurrent_parent_path = os.path.realpath( os.path.dirname(os.path.dirname(concurrent.__file__)) ) self.assertNotEqual(dist_dir, concurrent_parent_path) self.assertNotEqual( os.path.join(dist_dir, "py2only"), concurrent_parent_path ) def test_import_future_py2(self): from future.standard_library import TOP_LEVEL_MODULES if sys.version_info[0] == 2: for module_name in TOP_LEVEL_MODULES: if "test" in module_name: continue module_parent_path = os.path.realpath( os.path.dirname(imp.find_module(module_name)[1]) ) # future's standard libraries such as `html` should not be found # at the same level as kolibri/dist; otherwise, python3 will try to # import them from kolibri/dist instead of its builtin packages self.assertNotEqual(dist_dir, module_parent_path) ## Instruction: Fix import order in tests. ## Code After: import imp import os import sys # Import from kolibri first to ensure Kolibri's monkey patches are applied. from kolibri import dist as kolibri_dist # noreorder from django.test import TestCase # noreorder dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0] == 3: # Python 3 is supposed to import its builtin package `concurrent` # instead of being inside kolibri/dist/py2only or kolibri/dist concurrent_parent_path = os.path.realpath( os.path.dirname(os.path.dirname(concurrent.__file__)) ) self.assertNotEqual(dist_dir, concurrent_parent_path) self.assertNotEqual( os.path.join(dist_dir, "py2only"), concurrent_parent_path ) def test_import_future_py2(self): from future.standard_library import TOP_LEVEL_MODULES if sys.version_info[0] == 2: for module_name in TOP_LEVEL_MODULES: if "test" in module_name: continue module_parent_path = os.path.realpath( os.path.dirname(imp.find_module(module_name)[1]) ) # future's standard libraries such as `html` should not be found # at the same level as kolibri/dist; otherwise, python3 will try to # import them from kolibri/dist instead of its builtin packages self.assertNotEqual(dist_dir, module_parent_path)
... import sys # Import from kolibri first to ensure Kolibri's monkey patches are applied. from kolibri import dist as kolibri_dist # noreorder from django.test import TestCase # noreorder dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) ...
09fa1e01c6de9dffc99c7726607d64c843b564ba
osgtest/tests/test_53_gums.py
osgtest/tests/test_53_gums.py
import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums-service') host_dn, _ = core.certificate_info(core.config['certs.hostcert']) pwd_entry = pwd.getpwnam(core.options.username) cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) command = ('gums-host', 'mapUser', user_dn) core.check_system(command, 'Map GUMS user')
import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums-service') host_dn, _ = core.certificate_info(core.config['certs.hostcert']) pwd_entry = pwd.getpwnam(core.options.username) cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) command = ('gums', 'mapUser', '--serv', host_dn, user_dn) core.check_system(command, 'Map GUMS user')
Revert accidental gums test change from previous commit.
Revert accidental gums test change from previous commit. git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@17355 4e558342-562e-0410-864c-e07659590f8c
Python
apache-2.0
efajardo/osg-test,efajardo/osg-test
import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums-service') host_dn, _ = core.certificate_info(core.config['certs.hostcert']) pwd_entry = pwd.getpwnam(core.options.username) cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) - command = ('gums-host', 'mapUser', user_dn) + command = ('gums', 'mapUser', '--serv', host_dn, user_dn) core.check_system(command, 'Map GUMS user')
Revert accidental gums test change from previous commit.
## Code Before: import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums-service') host_dn, _ = core.certificate_info(core.config['certs.hostcert']) pwd_entry = pwd.getpwnam(core.options.username) cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) command = ('gums-host', 'mapUser', user_dn) core.check_system(command, 'Map GUMS user') ## Instruction: Revert accidental gums test change from previous commit. ## Code After: import os import pwd import unittest import osgtest.library.core as core import osgtest.library.files as files import osgtest.library.tomcat as tomcat import osgtest.library.osgunittest as osgunittest class TestGUMS(osgunittest.OSGTestCase): def test_01_map_user(self): core.skip_ok_unless_installed('gums-service') host_dn, _ = core.certificate_info(core.config['certs.hostcert']) pwd_entry = pwd.getpwnam(core.options.username) cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) command = ('gums', 'mapUser', '--serv', host_dn, user_dn) core.check_system(command, 'Map GUMS user')
... cert_path = os.path.join(pwd_entry.pw_dir, '.globus', 'usercert.pem') user_dn, _ = core.certificate_info(cert_path) command = ('gums', 'mapUser', '--serv', host_dn, user_dn) core.check_system(command, 'Map GUMS user') ...
3f394e47841b2d9e49554b21c67b06a46f99f25c
celery_app.py
celery_app.py
import config import logging from celery.schedules import crontab from lazyblacksmith.app import create_app from lazyblacksmith.extension.celery_app import celery_app # disable / enable loggers we want logging.getLogger('pyswagger').setLevel(logging.ERROR) app = create_app(config) app.app_context().push() celery_app.init_app(app) #celery_app.conf.broker_url = config.broker_url celery_app.conf.beat_schedule.update({ 'character-task-spawner': { 'task': 'schedule.character_task_spawner', 'schedule': crontab(minute='*'), }, 'universe-task-spawner': { 'task': 'schedule.universe_task_spawner', 'schedule': crontab(minute='*/30'), }, }) celery_app.conf.imports = [ 'lazyblacksmith.tasks.task_spawner', 'lazyblacksmith.tasks.market.adjusted_price', 'lazyblacksmith.tasks.market.market_order', 'lazyblacksmith.tasks.industry.indexes', 'lazyblacksmith.tasks.character.skills', 'lazyblacksmith.tasks.character.blueprints', ]
import config import logging from celery.schedules import crontab from lazyblacksmith.app import create_app from lazyblacksmith.extension.celery_app import celery_app # disable / enable loggers we want logging.getLogger('pyswagger').setLevel(logging.ERROR) app = create_app(config) app.app_context().push() celery_app.init_app(app) #celery_app.conf.broker_url = config.broker_url celery_app.conf.beat_schedule.update({ 'character-task-spawner': { 'task': 'schedule.character_task_spawner', 'schedule': crontab(minute='*'), }, 'universe-task-spawner': { 'task': 'schedule.universe_task_spawner', 'schedule': crontab(minute='*/30'), }, }) celery_app.conf.imports = [ 'lazyblacksmith.tasks.task_spawner', 'lazyblacksmith.tasks.market.adjusted_price', 'lazyblacksmith.tasks.market.market_order', 'lazyblacksmith.tasks.industry.indexes', 'lazyblacksmith.tasks.character.skills', 'lazyblacksmith.tasks.character.blueprints', 'lazyblacksmith.tasks.corporation.blueprints', ]
Add corporation task in celery data
Add corporation task in celery data
Python
bsd-3-clause
Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith
import config import logging from celery.schedules import crontab from lazyblacksmith.app import create_app from lazyblacksmith.extension.celery_app import celery_app # disable / enable loggers we want logging.getLogger('pyswagger').setLevel(logging.ERROR) app = create_app(config) app.app_context().push() celery_app.init_app(app) #celery_app.conf.broker_url = config.broker_url celery_app.conf.beat_schedule.update({ 'character-task-spawner': { 'task': 'schedule.character_task_spawner', 'schedule': crontab(minute='*'), }, 'universe-task-spawner': { 'task': 'schedule.universe_task_spawner', 'schedule': crontab(minute='*/30'), }, }) celery_app.conf.imports = [ 'lazyblacksmith.tasks.task_spawner', 'lazyblacksmith.tasks.market.adjusted_price', 'lazyblacksmith.tasks.market.market_order', 'lazyblacksmith.tasks.industry.indexes', 'lazyblacksmith.tasks.character.skills', 'lazyblacksmith.tasks.character.blueprints', + 'lazyblacksmith.tasks.corporation.blueprints', ]
Add corporation task in celery data
## Code Before: import config import logging from celery.schedules import crontab from lazyblacksmith.app import create_app from lazyblacksmith.extension.celery_app import celery_app # disable / enable loggers we want logging.getLogger('pyswagger').setLevel(logging.ERROR) app = create_app(config) app.app_context().push() celery_app.init_app(app) #celery_app.conf.broker_url = config.broker_url celery_app.conf.beat_schedule.update({ 'character-task-spawner': { 'task': 'schedule.character_task_spawner', 'schedule': crontab(minute='*'), }, 'universe-task-spawner': { 'task': 'schedule.universe_task_spawner', 'schedule': crontab(minute='*/30'), }, }) celery_app.conf.imports = [ 'lazyblacksmith.tasks.task_spawner', 'lazyblacksmith.tasks.market.adjusted_price', 'lazyblacksmith.tasks.market.market_order', 'lazyblacksmith.tasks.industry.indexes', 'lazyblacksmith.tasks.character.skills', 'lazyblacksmith.tasks.character.blueprints', ] ## Instruction: Add corporation task in celery data ## Code After: import config import logging from celery.schedules import crontab from lazyblacksmith.app import create_app from lazyblacksmith.extension.celery_app import celery_app # disable / enable loggers we want logging.getLogger('pyswagger').setLevel(logging.ERROR) app = create_app(config) app.app_context().push() celery_app.init_app(app) #celery_app.conf.broker_url = config.broker_url celery_app.conf.beat_schedule.update({ 'character-task-spawner': { 'task': 'schedule.character_task_spawner', 'schedule': crontab(minute='*'), }, 'universe-task-spawner': { 'task': 'schedule.universe_task_spawner', 'schedule': crontab(minute='*/30'), }, }) celery_app.conf.imports = [ 'lazyblacksmith.tasks.task_spawner', 'lazyblacksmith.tasks.market.adjusted_price', 'lazyblacksmith.tasks.market.market_order', 'lazyblacksmith.tasks.industry.indexes', 'lazyblacksmith.tasks.character.skills', 'lazyblacksmith.tasks.character.blueprints', 'lazyblacksmith.tasks.corporation.blueprints', ]
... 'lazyblacksmith.tasks.character.skills', 'lazyblacksmith.tasks.character.blueprints', 'lazyblacksmith.tasks.corporation.blueprints', ] ...
d1917d20f3aa26380e1e617f50b380142905d745
engines/string_template_engine.py
engines/string_template_engine.py
"""Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, **kwargs): """Initialize string.Template.""" super(StringTemplate, self).__init__(**kwargs) self.template = Template(template) self.tolerant = tolerant def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" if self.tolerant: return self.template.safe_substitute(mapping) return self.template.substitute(mapping)
"""Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, **kwargs): """Initialize string.Template.""" super(StringTemplate, self).__init__(**kwargs) self.template = Template(template) self.tolerant = tolerant def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" mapping = {name: self.str(value, tolerant=self.tolerant) for name, value in mapping.items() if value is not None or self.tolerant} if self.tolerant: return self.template.safe_substitute(mapping) return self.template.substitute(mapping)
Transform values in string.Template engine before substitution.
Transform values in string.Template engine before substitution.
Python
mit
blubberdiblub/eztemplate
"""Provide the standard Python string.Template engine.""" from __future__ import print_function - from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, **kwargs): """Initialize string.Template.""" super(StringTemplate, self).__init__(**kwargs) self.template = Template(template) self.tolerant = tolerant def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" + mapping = {name: self.str(value, tolerant=self.tolerant) + for name, value in mapping.items() + if value is not None or self.tolerant} + if self.tolerant: return self.template.safe_substitute(mapping) return self.template.substitute(mapping)
Transform values in string.Template engine before substitution.
## Code Before: """Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, **kwargs): """Initialize string.Template.""" super(StringTemplate, self).__init__(**kwargs) self.template = Template(template) self.tolerant = tolerant def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" if self.tolerant: return self.template.safe_substitute(mapping) return self.template.substitute(mapping) ## Instruction: Transform values in string.Template engine before substitution. ## Code After: """Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, **kwargs): """Initialize string.Template.""" super(StringTemplate, self).__init__(**kwargs) self.template = Template(template) self.tolerant = tolerant def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" mapping = {name: self.str(value, tolerant=self.tolerant) for name, value in mapping.items() if value is not None or self.tolerant} if self.tolerant: return self.template.safe_substitute(mapping) return self.template.substitute(mapping)
# ... existing code ... from __future__ import print_function from string import Template # ... modified code ... def apply(self, mapping): """Apply a mapping of name-value-pairs to a template.""" mapping = {name: self.str(value, tolerant=self.tolerant) for name, value in mapping.items() if value is not None or self.tolerant} if self.tolerant: return self.template.safe_substitute(mapping) # ... rest of the code ...
37b0387f9425c25a53c981dce3911e98c7ca14dd
test/test_config.py
test/test_config.py
import os from nose.tools import * from lctools import config class TestConfig(object): test_filename = "bebebe" def setup(self): fd = open(self.test_filename, 'w') fd.write("[default]\n") fd.write("foo = bar\n") fd.close() def test_basic_functionality(self): config.LC_CONFIG = self.test_filename conf = config.get_config("default") assert_true("default" in conf.sections()) assert_equal(conf.get("foo"), "bar") def teardown(self): os.unlink(self.test_filename)
import os import stat from nose.tools import * from lctools import config class TestConfig(object): test_filename = "bebebe" def setup(self): fd = open(self.test_filename, 'w') fd.write("[default]\n") fd.write("foo = bar\n") fd.close() os.chmod(self.test_filename, stat.S_IRUSR) def test_basic_functionality(self): config.LC_CONFIG = self.test_filename conf = config.get_config("default") assert_true("default" in conf.sections()) assert_equal(conf.get("foo"), "bar") @raises(RuntimeError) def test_get_config_permission_checks(self): os.chmod(self.test_filename, stat.S_IRWXG | stat.S_IRWXO) config.LC_CONFIG = self.test_filename config.get_config("default") def teardown(self): os.unlink(self.test_filename)
Add a test for config file permissions check.
Add a test for config file permissions check.
Python
apache-2.0
novel/lc-tools,novel/lc-tools
import os + import stat from nose.tools import * from lctools import config class TestConfig(object): test_filename = "bebebe" def setup(self): fd = open(self.test_filename, 'w') fd.write("[default]\n") fd.write("foo = bar\n") fd.close() + os.chmod(self.test_filename, stat.S_IRUSR) def test_basic_functionality(self): config.LC_CONFIG = self.test_filename conf = config.get_config("default") assert_true("default" in conf.sections()) assert_equal(conf.get("foo"), "bar") + @raises(RuntimeError) + def test_get_config_permission_checks(self): + os.chmod(self.test_filename, stat.S_IRWXG | stat.S_IRWXO) + config.LC_CONFIG = self.test_filename + config.get_config("default") + def teardown(self): os.unlink(self.test_filename)
Add a test for config file permissions check.
## Code Before: import os from nose.tools import * from lctools import config class TestConfig(object): test_filename = "bebebe" def setup(self): fd = open(self.test_filename, 'w') fd.write("[default]\n") fd.write("foo = bar\n") fd.close() def test_basic_functionality(self): config.LC_CONFIG = self.test_filename conf = config.get_config("default") assert_true("default" in conf.sections()) assert_equal(conf.get("foo"), "bar") def teardown(self): os.unlink(self.test_filename) ## Instruction: Add a test for config file permissions check. ## Code After: import os import stat from nose.tools import * from lctools import config class TestConfig(object): test_filename = "bebebe" def setup(self): fd = open(self.test_filename, 'w') fd.write("[default]\n") fd.write("foo = bar\n") fd.close() os.chmod(self.test_filename, stat.S_IRUSR) def test_basic_functionality(self): config.LC_CONFIG = self.test_filename conf = config.get_config("default") assert_true("default" in conf.sections()) assert_equal(conf.get("foo"), "bar") @raises(RuntimeError) def test_get_config_permission_checks(self): os.chmod(self.test_filename, stat.S_IRWXG | stat.S_IRWXO) config.LC_CONFIG = self.test_filename config.get_config("default") def teardown(self): os.unlink(self.test_filename)
// ... existing code ... import os import stat from nose.tools import * // ... modified code ... fd.write("foo = bar\n") fd.close() os.chmod(self.test_filename, stat.S_IRUSR) def test_basic_functionality(self): ... assert_equal(conf.get("foo"), "bar") @raises(RuntimeError) def test_get_config_permission_checks(self): os.chmod(self.test_filename, stat.S_IRWXG | stat.S_IRWXO) config.LC_CONFIG = self.test_filename config.get_config("default") def teardown(self): os.unlink(self.test_filename) // ... rest of the code ...
4026b8e352229c6f640d428640cd08919ba440e6
dodo_commands/extra/webdev_commands/django-manage.py
dodo_commands/extra/webdev_commands/django-manage.py
"""Run a django-manage command.""" import argparse from dodo_commands.extra.standard_commands import DodoCommand from dodo_commands.util import remove_trailing_dashes class Command(DodoCommand): # noqa decorators = ['docker'] def add_arguments_imp(self, parser): # noqa parser.add_argument( 'manage_args', nargs=argparse.REMAINDER ) def handle_imp( # noqa self, manage_args, *args, **kwargs ): self.runcmd( [ self.get_config("/DJANGO/python"), "manage.py", ] + remove_trailing_dashes(manage_args), cwd=self.get_config("/DJANGO/src_dir") )
"""Run a django-manage command.""" import argparse from dodo_commands.extra.standard_commands import DodoCommand from dodo_commands.framework.util import remove_trailing_dashes class Command(DodoCommand): # noqa decorators = ['docker'] def add_arguments_imp(self, parser): # noqa parser.add_argument( 'manage_args', nargs=argparse.REMAINDER ) def handle_imp( # noqa self, manage_args, *args, **kwargs ): self.runcmd( [ self.get_config("/DJANGO/python"), "manage.py", ] + remove_trailing_dashes(manage_args), cwd=self.get_config("/DJANGO/src_dir") )
Fix remaining broken import of remove_trailing_dashes
Fix remaining broken import of remove_trailing_dashes
Python
mit
mnieber/dodo_commands
"""Run a django-manage command.""" import argparse from dodo_commands.extra.standard_commands import DodoCommand - from dodo_commands.util import remove_trailing_dashes + from dodo_commands.framework.util import remove_trailing_dashes class Command(DodoCommand): # noqa decorators = ['docker'] def add_arguments_imp(self, parser): # noqa parser.add_argument( 'manage_args', nargs=argparse.REMAINDER ) def handle_imp( # noqa self, manage_args, *args, **kwargs ): self.runcmd( [ self.get_config("/DJANGO/python"), "manage.py", ] + remove_trailing_dashes(manage_args), cwd=self.get_config("/DJANGO/src_dir") )
Fix remaining broken import of remove_trailing_dashes
## Code Before: """Run a django-manage command.""" import argparse from dodo_commands.extra.standard_commands import DodoCommand from dodo_commands.util import remove_trailing_dashes class Command(DodoCommand): # noqa decorators = ['docker'] def add_arguments_imp(self, parser): # noqa parser.add_argument( 'manage_args', nargs=argparse.REMAINDER ) def handle_imp( # noqa self, manage_args, *args, **kwargs ): self.runcmd( [ self.get_config("/DJANGO/python"), "manage.py", ] + remove_trailing_dashes(manage_args), cwd=self.get_config("/DJANGO/src_dir") ) ## Instruction: Fix remaining broken import of remove_trailing_dashes ## Code After: """Run a django-manage command.""" import argparse from dodo_commands.extra.standard_commands import DodoCommand from dodo_commands.framework.util import remove_trailing_dashes class Command(DodoCommand): # noqa decorators = ['docker'] def add_arguments_imp(self, parser): # noqa parser.add_argument( 'manage_args', nargs=argparse.REMAINDER ) def handle_imp( # noqa self, manage_args, *args, **kwargs ): self.runcmd( [ self.get_config("/DJANGO/python"), "manage.py", ] + remove_trailing_dashes(manage_args), cwd=self.get_config("/DJANGO/src_dir") )
// ... existing code ... import argparse from dodo_commands.extra.standard_commands import DodoCommand from dodo_commands.framework.util import remove_trailing_dashes // ... rest of the code ...
7f006958e97cf5cc972d9f8340b327ea7508e03d
packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py
packages/Python/lldbsuite/test/functionalities/command_script_immediate_output/TestCommandScriptImmediateOutput.py
from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are
Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@257656 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb
from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 - @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") - @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are
## Code Before: from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot") @expectedFlakeyLinux("llvm.org/pr25172") @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False) ## Instruction: Mark these tests on FreeBSD and Linux as non-flakey. We don't know that they are ## Code After: from __future__ import print_function import os, time import lldb from lldbsuite.test.lldbtest import * from lldbsuite.test.lldbpexpect import * class CommandScriptImmediateOutputTestCase (PExpectTest): mydir = TestBase.compute_mydir(__file__) def setUp(self): # Call super's setUp(). PExpectTest.setUp(self) @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): """Test that LLDB correctly allows scripted commands to set an immediate output file.""" self.launch(timeout=5) script = os.path.join(os.getcwd(), 'custom_command.py') prompt = "(lldb)" self.sendline('command script import %s' % script, patterns=[prompt]) self.sendline('command script add -f custom_command.command_function mycommand', patterns=[prompt]) self.sendline('mycommand', patterns='this is a test string, just a test string') self.sendline('command script delete mycommand', patterns=[prompt]) self.quit(gracefully=False)
... @skipIfRemote # test not remote-ready llvm.org/pr24813 @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows") def test_command_script_immediate_output (self): ...
9eabdbc6b73661865c4d785cbc57d7ee51fe59cd
future/tests/test_imports_urllib.py
future/tests/test_imports_urllib.py
from __future__ import absolute_import, print_function import unittest import sys class ImportUrllibTest(unittest.TestCase): def test_urllib(self): """ This should perhaps fail: importing urllib first means that the import hooks won't be consulted when importing urllib.response. """ import urllib print(urllib.__file__) from future import standard_library with standard_library.hooks(): import urllib.response print(urllib.__file__) print(urllib.response.__file__) if __name__ == '__main__': unittest.main()
from __future__ import absolute_import, print_function import unittest import sys class ImportUrllibTest(unittest.TestCase): def test_urllib(self): import urllib orig_file = urllib.__file__ from future.standard_library.urllib import response as urllib_response self.assertEqual(orig_file, urllib.__file__) print(urllib_response.__file__) if __name__ == '__main__': unittest.main()
Change urllib test to use an explicit import
Change urllib test to use an explicit import
Python
mit
QuLogic/python-future,michaelpacer/python-future,PythonCharmers/python-future,krischer/python-future,krischer/python-future,QuLogic/python-future,michaelpacer/python-future,PythonCharmers/python-future
from __future__ import absolute_import, print_function import unittest import sys class ImportUrllibTest(unittest.TestCase): def test_urllib(self): - """ - This should perhaps fail: importing urllib first means that the import hooks - won't be consulted when importing urllib.response. - """ import urllib - print(urllib.__file__) + orig_file = urllib.__file__ + from future.standard_library.urllib import response as urllib_response + self.assertEqual(orig_file, urllib.__file__) - from future import standard_library - with standard_library.hooks(): - import urllib.response - print(urllib.__file__) - print(urllib.response.__file__) + print(urllib_response.__file__) if __name__ == '__main__': unittest.main()
Change urllib test to use an explicit import
## Code Before: from __future__ import absolute_import, print_function import unittest import sys class ImportUrllibTest(unittest.TestCase): def test_urllib(self): """ This should perhaps fail: importing urllib first means that the import hooks won't be consulted when importing urllib.response. """ import urllib print(urllib.__file__) from future import standard_library with standard_library.hooks(): import urllib.response print(urllib.__file__) print(urllib.response.__file__) if __name__ == '__main__': unittest.main() ## Instruction: Change urllib test to use an explicit import ## Code After: from __future__ import absolute_import, print_function import unittest import sys class ImportUrllibTest(unittest.TestCase): def test_urllib(self): import urllib orig_file = urllib.__file__ from future.standard_library.urllib import response as urllib_response self.assertEqual(orig_file, urllib.__file__) print(urllib_response.__file__) if __name__ == '__main__': unittest.main()
... class ImportUrllibTest(unittest.TestCase): def test_urllib(self): import urllib orig_file = urllib.__file__ from future.standard_library.urllib import response as urllib_response self.assertEqual(orig_file, urllib.__file__) print(urllib_response.__file__) if __name__ == '__main__': ...
133bddf28eed38273eeb384b152ec35ae861a480
sunpy/__init__.py
sunpy/__init__.py
from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info']
from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' try: _ASTROPY_SETUP_ except NameError: _ASTROPY_SETUP_ = False if not _ASTROPY_SETUP_: import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info']
Make sure package does not import itself during setup
Make sure package does not import itself during setup
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' - import os - from sunpy.util.config import load_config, print_config - from sunpy.util import system_info - from sunpy.tests.runner import SunPyTestRunner + try: + _ASTROPY_SETUP_ + except NameError: + _ASTROPY_SETUP_ = False - self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) - # Load user configuration - config = load_config() + if not _ASTROPY_SETUP_: + import os + from sunpy.util.config import load_config, print_config + from sunpy.util import system_info + from sunpy.tests.runner import SunPyTestRunner - __all__ = ['config', 'self_test', 'system_info'] + self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) + # Load user configuration + config = load_config() + + __all__ = ['config', 'self_test', 'system_info'] +
Make sure package does not import itself during setup
## Code Before: from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info'] ## Instruction: Make sure package does not import itself during setup ## Code After: from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: from .version import githash as __githash__ except ImportError: __githash__ = '' try: _ASTROPY_SETUP_ except NameError: _ASTROPY_SETUP_ = False if not _ASTROPY_SETUP_: import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info']
# ... existing code ... __githash__ = '' try: _ASTROPY_SETUP_ except NameError: _ASTROPY_SETUP_ = False if not _ASTROPY_SETUP_: import os from sunpy.util.config import load_config, print_config from sunpy.util import system_info from sunpy.tests.runner import SunPyTestRunner self_test = SunPyTestRunner.make_test_runner_in(os.path.dirname(__file__)) # Load user configuration config = load_config() __all__ = ['config', 'self_test', 'system_info'] # ... rest of the code ...
243f973ee1757b7b8426e9e4b62de2a272d82407
protocols/urls.py
protocols/urls.py
from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), )
from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), url(r'^page/(?P<page>.*)/$', 'listing', name='pagination') )
Add url for listing protocols
Add url for listing protocols
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), + url(r'^page/(?P<page>.*)/$', 'listing', name='pagination') )
Add url for listing protocols
## Code Before: from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), ) ## Instruction: Add url for listing protocols ## Code After: from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), url(r'^page/(?P<page>.*)/$', 'listing', name='pagination') )
# ... existing code ... url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), url(r'^page/(?P<page>.*)/$', 'listing', name='pagination') ) # ... rest of the code ...
80162fd636cea87b9d096d6df8b93c59887d8785
scripts/crontab/gen-cron.py
scripts/crontab/gen-cron.py
import os from optparse import OptionParser TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option("-z", "--zamboni", help="Location of zamboni (required)") parser.add_option("-u", "--user", help=("Prefix cron with this user. " "Only define for cron.d style crontabs")) parser.add_option("-p", "--python", default="/usr/bin/python2.7", help="Python interpreter to use") parser.add_option("-d", "--deprecations", default=False, help="Show deprecation warnings") (opts, args) = parser.parse_args() if not opts.zamboni: parser.error("-z must be defined") if not opts.deprecations: opts.python += ' -W ignore::DeprecationWarning' ctx = {'django': 'cd %s; %s manage.py' % (opts.zamboni, opts.python)} ctx['z_cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ctx.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python print(TEMPLATE % ctx) if __name__ == "__main__": main()
import os from optparse import OptionParser TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option("-z", "--zamboni", help="Location of zamboni (required)") parser.add_option("-u", "--user", help=("Prefix cron with this user. " "Only define for cron.d style crontabs")) parser.add_option("-p", "--python", default="/usr/bin/python2.7", help="Python interpreter to use") parser.add_option("-d", "--deprecations", default=False, help="Show deprecation warnings") (opts, args) = parser.parse_args() if not opts.zamboni: parser.error("-z must be defined") if not opts.deprecations: opts.python += ' -W ignore::DeprecationWarning' dogwrap_path = '/usr/local/bin/amo_cron_dogwrap' ctx = { "django": "cd %s; %s %s manage.py" % (opts.zamboni, dogwrap_path, opts.python) } ctx['z_cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ctx.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python print(TEMPLATE % ctx) if __name__ == "__main__": main()
Add DataDog monitoring to cron job runs
Add DataDog monitoring to cron job runs
Python
bsd-3-clause
mozilla/addons-server,diox/olympia,mozilla/addons-server,kumar303/olympia,wagnerand/addons-server,atiqueahmedziad/addons-server,eviljeff/olympia,eviljeff/olympia,wagnerand/addons-server,kumar303/addons-server,wagnerand/addons-server,bqbn/addons-server,psiinon/addons-server,bqbn/addons-server,kumar303/olympia,diox/olympia,psiinon/addons-server,bqbn/addons-server,wagnerand/olympia,psiinon/addons-server,mozilla/addons-server,mozilla/olympia,mozilla/addons-server,atiqueahmedziad/addons-server,kumar303/olympia,diox/olympia,wagnerand/addons-server,wagnerand/olympia,eviljeff/olympia,kumar303/olympia,atiqueahmedziad/addons-server,kumar303/addons-server,psiinon/addons-server,diox/olympia,kumar303/addons-server,aviarypl/mozilla-l10n-addons-server,mozilla/olympia,mozilla/olympia,atiqueahmedziad/addons-server,bqbn/addons-server,wagnerand/olympia,kumar303/addons-server,aviarypl/mozilla-l10n-addons-server,mozilla/olympia,aviarypl/mozilla-l10n-addons-server,eviljeff/olympia,wagnerand/olympia,aviarypl/mozilla-l10n-addons-server
import os from optparse import OptionParser TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option("-z", "--zamboni", help="Location of zamboni (required)") parser.add_option("-u", "--user", help=("Prefix cron with this user. " "Only define for cron.d style crontabs")) parser.add_option("-p", "--python", default="/usr/bin/python2.7", help="Python interpreter to use") parser.add_option("-d", "--deprecations", default=False, help="Show deprecation warnings") (opts, args) = parser.parse_args() if not opts.zamboni: parser.error("-z must be defined") if not opts.deprecations: opts.python += ' -W ignore::DeprecationWarning' - ctx = {'django': 'cd %s; %s manage.py' % (opts.zamboni, opts.python)} + dogwrap_path = '/usr/local/bin/amo_cron_dogwrap' + + ctx = { + "django": "cd %s; %s %s manage.py" % (opts.zamboni, + dogwrap_path, + opts.python) + } ctx['z_cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ctx.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python print(TEMPLATE % ctx) if __name__ == "__main__": main()
Add DataDog monitoring to cron job runs
## Code Before: import os from optparse import OptionParser TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option("-z", "--zamboni", help="Location of zamboni (required)") parser.add_option("-u", "--user", help=("Prefix cron with this user. " "Only define for cron.d style crontabs")) parser.add_option("-p", "--python", default="/usr/bin/python2.7", help="Python interpreter to use") parser.add_option("-d", "--deprecations", default=False, help="Show deprecation warnings") (opts, args) = parser.parse_args() if not opts.zamboni: parser.error("-z must be defined") if not opts.deprecations: opts.python += ' -W ignore::DeprecationWarning' ctx = {'django': 'cd %s; %s manage.py' % (opts.zamboni, opts.python)} ctx['z_cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ctx.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python print(TEMPLATE % ctx) if __name__ == "__main__": main() ## Instruction: Add DataDog monitoring to cron job runs ## Code After: import os from optparse import OptionParser TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option("-z", "--zamboni", help="Location of zamboni (required)") parser.add_option("-u", "--user", help=("Prefix cron with this user. " "Only define for cron.d style crontabs")) parser.add_option("-p", "--python", default="/usr/bin/python2.7", help="Python interpreter to use") parser.add_option("-d", "--deprecations", default=False, help="Show deprecation warnings") (opts, args) = parser.parse_args() if not opts.zamboni: parser.error("-z must be defined") if not opts.deprecations: opts.python += ' -W ignore::DeprecationWarning' dogwrap_path = '/usr/local/bin/amo_cron_dogwrap' ctx = { "django": "cd %s; %s %s manage.py" % (opts.zamboni, dogwrap_path, opts.python) } ctx['z_cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ctx.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python print(TEMPLATE % ctx) if __name__ == "__main__": main()
... opts.python += ' -W ignore::DeprecationWarning' dogwrap_path = '/usr/local/bin/amo_cron_dogwrap' ctx = { "django": "cd %s; %s %s manage.py" % (opts.zamboni, dogwrap_path, opts.python) } ctx['z_cron'] = '%s cron' % ctx['django'] ...
bdcdeee5c913f65dc2ea7f611a0ca0882b4e910f
tests/views/test_view.py
tests/views/test_view.py
from gitfs.views.view import View class SimpleView(View): pass class TestView(object): def test_get_attr(self): simple_view = SimpleView(**{ 'uid': 1, 'gid': 1, 'mount_time': "now", }) asserted_getattr = { 'st_uid': 1, 'st_gid': 1, 'st_ctime': "now", 'st_mtime': "now", } assert simple_view.getattr() == asserted_getattr
from gitfs.views.view import View class SimpleView(View): pass class TestView(object): def test_get_attr(self): simple_view = SimpleView(**{ 'uid': 1, 'gid': 1, 'mount_time': "now", }) asserted_getattr = { 'st_uid': 1, 'st_gid': 1, 'st_ctime': "now", 'st_mtime': "now", } assert simple_view.getattr("/fake/test/path") == asserted_getattr
Update test for the getattr method.
Update test for the getattr method.
Python
apache-2.0
rowhit/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,PressLabs/gitfs,bussiere/gitfs
from gitfs.views.view import View class SimpleView(View): pass class TestView(object): def test_get_attr(self): simple_view = SimpleView(**{ 'uid': 1, 'gid': 1, 'mount_time': "now", }) asserted_getattr = { 'st_uid': 1, 'st_gid': 1, 'st_ctime': "now", 'st_mtime': "now", } - assert simple_view.getattr() == asserted_getattr + assert simple_view.getattr("/fake/test/path") == asserted_getattr
Update test for the getattr method.
## Code Before: from gitfs.views.view import View class SimpleView(View): pass class TestView(object): def test_get_attr(self): simple_view = SimpleView(**{ 'uid': 1, 'gid': 1, 'mount_time': "now", }) asserted_getattr = { 'st_uid': 1, 'st_gid': 1, 'st_ctime': "now", 'st_mtime': "now", } assert simple_view.getattr() == asserted_getattr ## Instruction: Update test for the getattr method. ## Code After: from gitfs.views.view import View class SimpleView(View): pass class TestView(object): def test_get_attr(self): simple_view = SimpleView(**{ 'uid': 1, 'gid': 1, 'mount_time': "now", }) asserted_getattr = { 'st_uid': 1, 'st_gid': 1, 'st_ctime': "now", 'st_mtime': "now", } assert simple_view.getattr("/fake/test/path") == asserted_getattr
... 'st_mtime': "now", } assert simple_view.getattr("/fake/test/path") == asserted_getattr ...
bb3605bd99892bed37ecb2b6371d2bc88d599e1a
caso/__init__.py
caso/__init__.py
import pbr.version __version__ = pbr.version.VersionInfo( 'caso').version_string() user_agent = "caso/%s" % __version__
import pbr.version __version__ = pbr.version.VersionInfo( 'caso').version_string() user_agent = "caso/%s (OpenStack)" % __version__
Include "OpenStack" string in the user agent
Include "OpenStack" string in the user agent EGI's accounting team requires that we put "OpenStack" in the UA string. closes IFCA/caso#38
Python
apache-2.0
alvarolopez/caso,IFCA/caso,IFCA/caso
import pbr.version __version__ = pbr.version.VersionInfo( 'caso').version_string() - user_agent = "caso/%s" % __version__ + user_agent = "caso/%s (OpenStack)" % __version__
Include "OpenStack" string in the user agent
## Code Before: import pbr.version __version__ = pbr.version.VersionInfo( 'caso').version_string() user_agent = "caso/%s" % __version__ ## Instruction: Include "OpenStack" string in the user agent ## Code After: import pbr.version __version__ = pbr.version.VersionInfo( 'caso').version_string() user_agent = "caso/%s (OpenStack)" % __version__
// ... existing code ... 'caso').version_string() user_agent = "caso/%s (OpenStack)" % __version__ // ... rest of the code ...
c5467b2ad4fbb0dbc37809df077e5c69915489c9
go_cli/send.py
go_cli/send.py
""" Send messages via an HTTP API (nostream) conversation. """ import click from go_http.send import HttpApiSender @click.option( '--conversation', '-c', help='HTTP API conversation key') @click.option( '--token', '-t', help='HTTP API conversation token') @click.option( '--csv', type=click.File('rb'), help=('CSV file with columns to_addr, content and, optionally,' 'session_event.')) @click.option( '--json', type=click.File('rb'), help=('JSON objects, one per line with fields to_addr, content and,' ' optionally, session_event')) @click.pass_context def send(ctx, conversation, token, csv, json): """ Send messages via an HTTP API (nostream) conversation. """ http_api = HttpApiSender(ctx.obj.account_key, conversation, token) messages = [] # TODO: parse csv or json for msg in messages: http_api.send_text(**msg)
""" Send messages via an HTTP API (nostream) conversation. """ import csv import json import click from go_http.send import HttpApiSender @click.option( '--conversation', '-c', help='HTTP API conversation key') @click.option( '--token', '-t', help='HTTP API conversation token') @click.option( '--csv', type=click.File('rb'), help=('CSV file with columns to_addr, content and, optionally,' 'session_event.')) @click.option( '--json', type=click.File('rb'), help=('JSON objects, one per line with fields to_addr, content and,' ' optionally, session_event')) @click.pass_context def send(ctx, conversation, token, csv, json): """ Send messages via an HTTP API (nostream) conversation. """ if not any((csv, json)): click.echo("Please specify either --csv or --json.") ctx.abort() http_api = HttpApiSender(ctx.obj.account_key, conversation, token) if csv: for msg in messages_from_csv(csv): http_api.send_text(**msg) if json: for msg in messages_from_json(json): http_api.send_text(**msg) def messages_from_csv(csv_file): reader = csv.DictReader(csv_file) for data in reader: yield { "to_addr": data["to_addr"], "content": data["content"], "session_event": data.get("session_event") } def messages_from_json(json_file): for line in json_file: data = json.loads(line.rstrip("\n")) yield { "to_addr": data["to_addr"], "content": data["content"], "session_event": data.get("session_event") }
Add CSV and JSON parsing.
Add CSV and JSON parsing.
Python
bsd-3-clause
praekelt/go-cli,praekelt/go-cli
""" Send messages via an HTTP API (nostream) conversation. """ + + import csv + import json import click from go_http.send import HttpApiSender @click.option( '--conversation', '-c', help='HTTP API conversation key') @click.option( '--token', '-t', help='HTTP API conversation token') @click.option( '--csv', type=click.File('rb'), help=('CSV file with columns to_addr, content and, optionally,' 'session_event.')) @click.option( '--json', type=click.File('rb'), help=('JSON objects, one per line with fields to_addr, content and,' ' optionally, session_event')) @click.pass_context def send(ctx, conversation, token, csv, json): """ Send messages via an HTTP API (nostream) conversation. """ + if not any((csv, json)): + click.echo("Please specify either --csv or --json.") + ctx.abort() http_api = HttpApiSender(ctx.obj.account_key, conversation, token) - messages = [] # TODO: parse csv or json - for msg in messages: + if csv: + for msg in messages_from_csv(csv): - http_api.send_text(**msg) + http_api.send_text(**msg) + if json: + for msg in messages_from_json(json): + http_api.send_text(**msg) + + def messages_from_csv(csv_file): + reader = csv.DictReader(csv_file) + for data in reader: + yield { + "to_addr": data["to_addr"], + "content": data["content"], + "session_event": data.get("session_event") + } + + + def messages_from_json(json_file): + for line in json_file: + data = json.loads(line.rstrip("\n")) + yield { + "to_addr": data["to_addr"], + "content": data["content"], + "session_event": data.get("session_event") + } +
Add CSV and JSON parsing.
## Code Before: """ Send messages via an HTTP API (nostream) conversation. """ import click from go_http.send import HttpApiSender @click.option( '--conversation', '-c', help='HTTP API conversation key') @click.option( '--token', '-t', help='HTTP API conversation token') @click.option( '--csv', type=click.File('rb'), help=('CSV file with columns to_addr, content and, optionally,' 'session_event.')) @click.option( '--json', type=click.File('rb'), help=('JSON objects, one per line with fields to_addr, content and,' ' optionally, session_event')) @click.pass_context def send(ctx, conversation, token, csv, json): """ Send messages via an HTTP API (nostream) conversation. """ http_api = HttpApiSender(ctx.obj.account_key, conversation, token) messages = [] # TODO: parse csv or json for msg in messages: http_api.send_text(**msg) ## Instruction: Add CSV and JSON parsing. ## Code After: """ Send messages via an HTTP API (nostream) conversation. """ import csv import json import click from go_http.send import HttpApiSender @click.option( '--conversation', '-c', help='HTTP API conversation key') @click.option( '--token', '-t', help='HTTP API conversation token') @click.option( '--csv', type=click.File('rb'), help=('CSV file with columns to_addr, content and, optionally,' 'session_event.')) @click.option( '--json', type=click.File('rb'), help=('JSON objects, one per line with fields to_addr, content and,' ' optionally, session_event')) @click.pass_context def send(ctx, conversation, token, csv, json): """ Send messages via an HTTP API (nostream) conversation. """ if not any((csv, json)): click.echo("Please specify either --csv or --json.") ctx.abort() http_api = HttpApiSender(ctx.obj.account_key, conversation, token) if csv: for msg in messages_from_csv(csv): http_api.send_text(**msg) if json: for msg in messages_from_json(json): http_api.send_text(**msg) def messages_from_csv(csv_file): reader = csv.DictReader(csv_file) for data in reader: yield { "to_addr": data["to_addr"], "content": data["content"], "session_event": data.get("session_event") } def messages_from_json(json_file): for line in json_file: data = json.loads(line.rstrip("\n")) yield { "to_addr": data["to_addr"], "content": data["content"], "session_event": data.get("session_event") }
# ... existing code ... """ Send messages via an HTTP API (nostream) conversation. """ import csv import json import click # ... modified code ... """ Send messages via an HTTP API (nostream) conversation. """ if not any((csv, json)): click.echo("Please specify either --csv or --json.") ctx.abort() http_api = HttpApiSender(ctx.obj.account_key, conversation, token) if csv: for msg in messages_from_csv(csv): http_api.send_text(**msg) if json: for msg in messages_from_json(json): http_api.send_text(**msg) def messages_from_csv(csv_file): reader = csv.DictReader(csv_file) for data in reader: yield { "to_addr": data["to_addr"], "content": data["content"], "session_event": data.get("session_event") } def messages_from_json(json_file): for line in json_file: data = json.loads(line.rstrip("\n")) yield { "to_addr": data["to_addr"], "content": data["content"], "session_event": data.get("session_event") } # ... rest of the code ...
62017dc7dc210d09e8f6753ad86365ac679f4a0a
oscar/apps/catalogue/categories.py
oscar/apps/catalogue/categories.py
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) except Category.DoesNotExist: root = Category.add_root(name=bits[0]) return [root] else: parents = create_from_sequence(bits[:-1]) try: child = parents[-1].get_children().get(name=bits[-1]) except Category.DoesNotExist: child = parents[-1].add_child(name=bits[-1]) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
Rework category creation from breadcrumbs
Rework category creation from breadcrumbs We now handle MultipleObjectsReturned exceptions, which are possible as we are looking up based on non-unique filters.
Python
bsd-3-clause
vovanbo/django-oscar,adamend/django-oscar,MatthewWilkes/django-oscar,manevant/django-oscar,django-oscar/django-oscar,WadeYuChen/django-oscar,elliotthill/django-oscar,sasha0/django-oscar,WillisXChen/django-oscar,jinnykoo/wuyisj,Jannes123/django-oscar,makielab/django-oscar,WadeYuChen/django-oscar,lijoantony/django-oscar,jinnykoo/christmas,elliotthill/django-oscar,vovanbo/django-oscar,dongguangming/django-oscar,adamend/django-oscar,WillisXChen/django-oscar,ka7eh/django-oscar,dongguangming/django-oscar,bschuon/django-oscar,jinnykoo/wuyisj,monikasulik/django-oscar,solarissmoke/django-oscar,WadeYuChen/django-oscar,pdonadeo/django-oscar,DrOctogon/unwash_ecom,josesanch/django-oscar,nfletton/django-oscar,jinnykoo/wuyisj.com,WillisXChen/django-oscar,john-parton/django-oscar,spartonia/django-oscar,saadatqadri/django-oscar,eddiep1101/django-oscar,QLGu/django-oscar,ademuk/django-oscar,MatthewWilkes/django-oscar,eddiep1101/django-oscar,jmt4/django-oscar,Jannes123/django-oscar,bnprk/django-oscar,rocopartners/django-oscar,anentropic/django-oscar,ka7eh/django-oscar,taedori81/django-oscar,ka7eh/django-oscar,kapari/django-oscar,lijoantony/django-oscar,ademuk/django-oscar,bnprk/django-oscar,eddiep1101/django-oscar,adamend/django-oscar,marcoantoniooliveira/labweb,kapari/django-oscar,Bogh/django-oscar,machtfit/django-oscar,spartonia/django-oscar,manevant/django-oscar,jmt4/django-oscar,makielab/django-oscar,nfletton/django-oscar,jmt4/django-oscar,rocopartners/django-oscar,thechampanurag/django-oscar,Jannes123/django-oscar,monikasulik/django-oscar,manevant/django-oscar,jinnykoo/wuyisj.com,mexeniz/django-oscar,sonofatailor/django-oscar,ahmetdaglarbas/e-commerce,vovanbo/django-oscar,marcoantoniooliveira/labweb,taedori81/django-oscar,kapari/django-oscar,okfish/django-oscar,nickpack/django-oscar,dongguangming/django-oscar,kapt/django-oscar,manevant/django-oscar,marcoantoniooliveira/labweb,kapt/django-oscar,itbabu/django-oscar,okfish/django-oscar,QLGu/django-oscar,okfish/django-oscar,nickpack/django-oscar,solarissmoke/django-oscar,marcoantoniooliveira/labweb,kapari/django-oscar,itbabu/django-oscar,sonofatailor/django-oscar,vovanbo/django-oscar,Bogh/django-oscar,faratro/django-oscar,binarydud/django-oscar,jinnykoo/wuyisj.com,pasqualguerrero/django-oscar,saadatqadri/django-oscar,nfletton/django-oscar,jlmadurga/django-oscar,michaelkuty/django-oscar,WillisXChen/django-oscar,elliotthill/django-oscar,spartonia/django-oscar,Idematica/django-oscar,anentropic/django-oscar,dongguangming/django-oscar,okfish/django-oscar,faratro/django-oscar,QLGu/django-oscar,Bogh/django-oscar,josesanch/django-oscar,kapt/django-oscar,adamend/django-oscar,jinnykoo/wuyisj,mexeniz/django-oscar,solarissmoke/django-oscar,john-parton/django-oscar,michaelkuty/django-oscar,sasha0/django-oscar,WillisXChen/django-oscar,Jannes123/django-oscar,Bogh/django-oscar,faratro/django-oscar,amirrpp/django-oscar,ademuk/django-oscar,anentropic/django-oscar,DrOctogon/unwash_ecom,john-parton/django-oscar,itbabu/django-oscar,jinnykoo/christmas,jinnykoo/wuyisj.com,WadeYuChen/django-oscar,itbabu/django-oscar,pdonadeo/django-oscar,monikasulik/django-oscar,ahmetdaglarbas/e-commerce,eddiep1101/django-oscar,django-oscar/django-oscar,thechampanurag/django-oscar,makielab/django-oscar,binarydud/django-oscar,josesanch/django-oscar,monikasulik/django-oscar,machtfit/django-oscar,lijoantony/django-oscar,taedori81/django-oscar,sonofatailor/django-oscar,lijoantony/django-oscar,faratro/django-oscar,bschuon/django-oscar,amirrpp/django-oscar,taedori81/django-oscar,DrOctogon/unwash_ecom,michaelkuty/django-oscar,nfletton/django-oscar,WillisXChen/django-oscar,solarissmoke/django-oscar,bnprk/django-oscar,john-parton/django-oscar,saadatqadri/django-oscar,Idematica/django-oscar,mexeniz/django-oscar,jlmadurga/django-oscar,MatthewWilkes/django-oscar,MatthewWilkes/django-oscar,ahmetdaglarbas/e-commerce,bnprk/django-oscar,django-oscar/django-oscar,ademuk/django-oscar,bschuon/django-oscar,Idematica/django-oscar,ahmetdaglarbas/e-commerce,jlmadurga/django-oscar,amirrpp/django-oscar,binarydud/django-oscar,amirrpp/django-oscar,mexeniz/django-oscar,pdonadeo/django-oscar,spartonia/django-oscar,bschuon/django-oscar,rocopartners/django-oscar,makielab/django-oscar,jmt4/django-oscar,sonofatailor/django-oscar,thechampanurag/django-oscar,nickpack/django-oscar,ka7eh/django-oscar,sasha0/django-oscar,anentropic/django-oscar,jinnykoo/christmas,michaelkuty/django-oscar,pasqualguerrero/django-oscar,binarydud/django-oscar,machtfit/django-oscar,pasqualguerrero/django-oscar,saadatqadri/django-oscar,django-oscar/django-oscar,jinnykoo/wuyisj,jlmadurga/django-oscar,rocopartners/django-oscar,pasqualguerrero/django-oscar,QLGu/django-oscar,pdonadeo/django-oscar,thechampanurag/django-oscar,sasha0/django-oscar,nickpack/django-oscar
from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node + name = bits[0] try: + # Category names should be unique at the depth=1 - root = Category.objects.get(depth=1, name=bits[0]) + root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: - root = Category.add_root(name=bits[0]) + root = Category.add_root(name=name) + except Category.MultipleObjectsReturned: + raise ValueError(( + "There are more than one categories with name " + "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) + parent, name = parents[-1], bits[-1] try: - child = parents[-1].get_children().get(name=bits[-1]) + child = parent.get_children().get(name=name) except Category.DoesNotExist: - child = parents[-1].add_child(name=bits[-1]) + child = parent.add_child(name=name) + except Category.MultipleObjectsReturned: + raise ValueError(( + "There are more than one categories with name " + "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
Rework category creation from breadcrumbs
## Code Before: from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node try: root = Category.objects.get(depth=1, name=bits[0]) except Category.DoesNotExist: root = Category.add_root(name=bits[0]) return [root] else: parents = create_from_sequence(bits[:-1]) try: child = parents[-1].get_children().get(name=bits[-1]) except Category.DoesNotExist: child = parents[-1].add_child(name=bits[-1]) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1] ## Instruction: Rework category creation from breadcrumbs ## Code After: from django.db.models import get_model Category = get_model('catalogue', 'category') def create_from_sequence(bits): """ Create categories from an iterable """ if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents def create_from_breadcrumbs(breadcrumb_str, separator='>'): """ Create categories from a breadcrumb string """ category_names = [x.strip() for x in breadcrumb_str.split(separator)] categories = create_from_sequence(category_names) return categories[-1]
# ... existing code ... if len(bits) == 1: # Get or create root node name = bits[0] try: # Category names should be unique at the depth=1 root = Category.objects.get(depth=1, name=name) except Category.DoesNotExist: root = Category.add_root(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s at depth=1") % name) return [root] else: parents = create_from_sequence(bits[:-1]) parent, name = parents[-1], bits[-1] try: child = parent.get_children().get(name=name) except Category.DoesNotExist: child = parent.add_child(name=name) except Category.MultipleObjectsReturned: raise ValueError(( "There are more than one categories with name " "%s which are children of %s") % (name, parent)) parents.append(child) return parents # ... rest of the code ...
d178fb001b8b6869038ed6ec288acf5fb427205c
rssmailer/tasks/mail.py
rssmailer/tasks/mail.py
from celery.decorators import task from django.core.mail import send_mail from ..models import Email @task(ignore_result=True, name="rssmailer.tasks.mail.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending entry: %s" % entry.title) emails_all = Email.objects.all() step = 3 # how many recipients in one e-mail for i in range(0, len(emails_all), step): recipients = map(lambda e: e.email, emails_all[i:i+step]) send_entry_to.delay(entry.title, entry.summary, recipients) @task(ignore_result=True, name="rssmailer.tasks.mail.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) send_mail(title, body, "[email protected]", recipients)
from celery.decorators import task from django.core.mail import send_mail from ..models import Email @task(ignore_result=True, name="rssmailer.tasks.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending entry: %s" % entry.title) emails_all = Email.objects.all() step = 3 # how many recipients in one e-mail for i in range(0, len(emails_all), step): recipients = map(lambda e: e.email, emails_all[i:i+step]) send_entry_to.delay(entry.title, entry.summary, recipients) @task(ignore_result=True, name="rssmailer.tasks.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) send_mail(title, body, "[email protected]", recipients)
Fix naming issues with tasks
Fix naming issues with tasks
Python
bsd-3-clause
praus/django-rssmailer
from celery.decorators import task from django.core.mail import send_mail from ..models import Email - @task(ignore_result=True, name="rssmailer.tasks.mail.send") + @task(ignore_result=True, name="rssmailer.tasks.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending entry: %s" % entry.title) emails_all = Email.objects.all() step = 3 # how many recipients in one e-mail for i in range(0, len(emails_all), step): recipients = map(lambda e: e.email, emails_all[i:i+step]) send_entry_to.delay(entry.title, entry.summary, recipients) - @task(ignore_result=True, name="rssmailer.tasks.mail.send_entry_to") + @task(ignore_result=True, name="rssmailer.tasks.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) - send_mail(title, body, "[email protected]", recipients) + send_mail(title, body, "[email protected]", recipients) -
Fix naming issues with tasks
## Code Before: from celery.decorators import task from django.core.mail import send_mail from ..models import Email @task(ignore_result=True, name="rssmailer.tasks.mail.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending entry: %s" % entry.title) emails_all = Email.objects.all() step = 3 # how many recipients in one e-mail for i in range(0, len(emails_all), step): recipients = map(lambda e: e.email, emails_all[i:i+step]) send_entry_to.delay(entry.title, entry.summary, recipients) @task(ignore_result=True, name="rssmailer.tasks.mail.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) send_mail(title, body, "[email protected]", recipients) ## Instruction: Fix naming issues with tasks ## Code After: from celery.decorators import task from django.core.mail import send_mail from ..models import Email @task(ignore_result=True, name="rssmailer.tasks.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending entry: %s" % entry.title) emails_all = Email.objects.all() step = 3 # how many recipients in one e-mail for i in range(0, len(emails_all), step): recipients = map(lambda e: e.email, emails_all[i:i+step]) send_entry_to.delay(entry.title, entry.summary, recipients) @task(ignore_result=True, name="rssmailer.tasks.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) send_mail(title, body, "[email protected]", recipients)
# ... existing code ... from ..models import Email @task(ignore_result=True, name="rssmailer.tasks.send") def send(entry, **kwargs): logger = send.get_logger(**kwargs) # ... modified code ... @task(ignore_result=True, name="rssmailer.tasks.send_entry_to") def send_entry_to(title, body, recipients, **kwargs): logger = send.get_logger(**kwargs) logger.info("Sending to: %s" % ','.join(recipients)) send_mail(title, body, "[email protected]", recipients) # ... rest of the code ...