commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
91709b78c27ed0e05f3c67fcc13ffa8085dac15a
heavy-ion-luminosity.py
heavy-ion-luminosity.py
__author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) print(arr.dtype) # The TTree name is always optional if there is only one TTree in the file # Convert a TTree in a ROOT file into a NumPy record array rec = root2rec(filename) # Get the TTree from the ROOT file rfile = ROOT.TFile(filename)
__author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) for element in arr.dtype.names: print(element) print("\n") # The TTree name is always optional if there is only one TTree in the file # Convert a TTree in a ROOT file into a NumPy record array rec = root2rec(filename) # Get the TTree from the ROOT file rfile = ROOT.TFile(filename)
Print out dtypes in .root file individually
Print out dtypes in .root file individually
Python
mit
jacobbieker/ATLAS-Luminosity
__author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) - print(arr.dtype) + for element in arr.dtype.names: + print(element) + print("\n") # The TTree name is always optional if there is only one TTree in the file # Convert a TTree in a ROOT file into a NumPy record array rec = root2rec(filename) # Get the TTree from the ROOT file rfile = ROOT.TFile(filename)
Print out dtypes in .root file individually
## Code Before: __author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) print(arr.dtype) # The TTree name is always optional if there is only one TTree in the file # Convert a TTree in a ROOT file into a NumPy record array rec = root2rec(filename) # Get the TTree from the ROOT file rfile = ROOT.TFile(filename) ## Instruction: Print out dtypes in .root file individually ## Code After: __author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) for element in arr.dtype.names: print(element) print("\n") # The TTree name is always optional if there is only one TTree in the file # Convert a TTree in a ROOT file into a NumPy record array rec = root2rec(filename) # Get the TTree from the ROOT file rfile = ROOT.TFile(filename)
bfec6f3e2db99e20baf9b87fcd85da9ff050b030
UM/OutputDevice/OutputDeviceError.py
UM/OutputDevice/OutputDeviceError.py
class ErrorCodes: UserCanceledError = 1 DeviceBusyError = 2 class WriteRequestFailedError(Exception): def __init__(self, code, message): super().__init__(message) self.code = code self.message = message
class WriteRequestFailedError(Exception): pass class UserCancelledError(WriteRequestFailedError): pass class PermissionDeniedError(WriteRequestFailedError): pass class DeviceBusyError(WriteRequestFailedError): pass
Replace error codes with error subclasses
Replace error codes with error subclasses This provides the same information but is a cleaner solution for python
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
- - class ErrorCodes: - UserCanceledError = 1 - DeviceBusyError = 2 class WriteRequestFailedError(Exception): + pass - def __init__(self, code, message): - super().__init__(message) - self.code = code - self.message = message + class UserCancelledError(WriteRequestFailedError): + pass + + class PermissionDeniedError(WriteRequestFailedError): + pass + + class DeviceBusyError(WriteRequestFailedError): + pass +
Replace error codes with error subclasses
## Code Before: class ErrorCodes: UserCanceledError = 1 DeviceBusyError = 2 class WriteRequestFailedError(Exception): def __init__(self, code, message): super().__init__(message) self.code = code self.message = message ## Instruction: Replace error codes with error subclasses ## Code After: class WriteRequestFailedError(Exception): pass class UserCancelledError(WriteRequestFailedError): pass class PermissionDeniedError(WriteRequestFailedError): pass class DeviceBusyError(WriteRequestFailedError): pass
094132685688d0e9e599da6e8c0e0554945d56a5
html5lib/trie/datrie.py
html5lib/trie/datrie.py
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not isinstance(key, str): raise TypeError("All keys must be strings") for char in key: chars.add(char) self._data = DATrie("".join(chars)) for key, value in data.items(): self._data[key] = value def __contains__(self, key): return key in self._data def __len__(self): return len(self._data) def __iter__(self): raise NotImplementedError() def __getitem__(self, key): return self._data[key] def keys(self, prefix=None): return self._data.keys(prefix) def has_keys_with_prefix(self, prefix): return self._data.has_keys_with_prefix(prefix) def longest_prefix(self, prefix): return self._data.longest_prefix(prefix) def longest_prefix_item(self, prefix): return self._data.longest_prefix_item(prefix)
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from six import text_type from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not isinstance(key, text_type): raise TypeError("All keys must be strings") for char in key: chars.add(char) self._data = DATrie("".join(chars)) for key, value in data.items(): self._data[key] = value def __contains__(self, key): return key in self._data def __len__(self): return len(self._data) def __iter__(self): raise NotImplementedError() def __getitem__(self, key): return self._data[key] def keys(self, prefix=None): return self._data.keys(prefix) def has_keys_with_prefix(self, prefix): return self._data.has_keys_with_prefix(prefix) def longest_prefix(self, prefix): return self._data.longest_prefix(prefix) def longest_prefix_item(self, prefix): return self._data.longest_prefix_item(prefix)
Fix DATrie support under Python 2.
Fix DATrie support under Python 2. This is a simple issue of using `str` to refer to what should be `six.text_type`.
Python
mit
mindw/html5lib-python,html5lib/html5lib-python,alex/html5lib-python,gsnedders/html5lib-python,ordbogen/html5lib-python,dstufft/html5lib-python,alex/html5lib-python,mgilson/html5lib-python,alex/html5lib-python,mindw/html5lib-python,dstufft/html5lib-python,dstufft/html5lib-python,ordbogen/html5lib-python,html5lib/html5lib-python,mgilson/html5lib-python,gsnedders/html5lib-python,mgilson/html5lib-python,ordbogen/html5lib-python,mindw/html5lib-python,html5lib/html5lib-python
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie + from six import text_type from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): - if not isinstance(key, str): + if not isinstance(key, text_type): raise TypeError("All keys must be strings") for char in key: chars.add(char) self._data = DATrie("".join(chars)) for key, value in data.items(): self._data[key] = value def __contains__(self, key): return key in self._data def __len__(self): return len(self._data) def __iter__(self): raise NotImplementedError() def __getitem__(self, key): return self._data[key] def keys(self, prefix=None): return self._data.keys(prefix) def has_keys_with_prefix(self, prefix): return self._data.has_keys_with_prefix(prefix) def longest_prefix(self, prefix): return self._data.longest_prefix(prefix) def longest_prefix_item(self, prefix): return self._data.longest_prefix_item(prefix)
Fix DATrie support under Python 2.
## Code Before: from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not isinstance(key, str): raise TypeError("All keys must be strings") for char in key: chars.add(char) self._data = DATrie("".join(chars)) for key, value in data.items(): self._data[key] = value def __contains__(self, key): return key in self._data def __len__(self): return len(self._data) def __iter__(self): raise NotImplementedError() def __getitem__(self, key): return self._data[key] def keys(self, prefix=None): return self._data.keys(prefix) def has_keys_with_prefix(self, prefix): return self._data.has_keys_with_prefix(prefix) def longest_prefix(self, prefix): return self._data.longest_prefix(prefix) def longest_prefix_item(self, prefix): return self._data.longest_prefix_item(prefix) ## Instruction: Fix DATrie support under Python 2. ## Code After: from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from six import text_type from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not isinstance(key, text_type): raise TypeError("All keys must be strings") for char in key: chars.add(char) self._data = DATrie("".join(chars)) for key, value in data.items(): self._data[key] = value def __contains__(self, key): return key in self._data def __len__(self): return len(self._data) def __iter__(self): raise NotImplementedError() def __getitem__(self, key): return self._data[key] def keys(self, prefix=None): return self._data.keys(prefix) def has_keys_with_prefix(self, prefix): return self._data.has_keys_with_prefix(prefix) def longest_prefix(self, prefix): return self._data.longest_prefix(prefix) def longest_prefix_item(self, prefix): return self._data.longest_prefix_item(prefix)
e20dc134911ad7b99014fdbf77dacd498cecce19
eventkit/plugins/fluentevent/migrations/0002_fluentevent_layout.py
eventkit/plugins/fluentevent/migrations/0002_fluentevent_layout.py
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_name='fluentevent', name='layout', field=models.ForeignKey(blank=True, to='icekit.Layout', null=True), preserve_default=True, ), ]
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_name='fluentevent', name='layout', field=models.ForeignKey(related_name='eventkit_fluentevent_fluentevent_related', blank=True, to='icekit.Layout', null=True), preserve_default=True, ), ]
Update related name for `layout` field.
Update related name for `layout` field.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_name='fluentevent', name='layout', - field=models.ForeignKey(blank=True, to='icekit.Layout', null=True), + field=models.ForeignKey(related_name='eventkit_fluentevent_fluentevent_related', blank=True, to='icekit.Layout', null=True), preserve_default=True, ), ]
Update related name for `layout` field.
## Code Before: from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_name='fluentevent', name='layout', field=models.ForeignKey(blank=True, to='icekit.Layout', null=True), preserve_default=True, ), ] ## Instruction: Update related name for `layout` field. ## Code After: from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_name='fluentevent', name='layout', field=models.ForeignKey(related_name='eventkit_fluentevent_fluentevent_related', blank=True, to='icekit.Layout', null=True), preserve_default=True, ), ]
73f76034b0d00c48774cafe3584bb672b8ba55bd
apps/announcements/models.py
apps/announcements/models.py
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): author = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('author', 'object_id') def __unicode__(self): return self.content_object.name class Announcements(models.Model): title = models.CharField(max_length = 500) pubdate = models.DateTimeField() creator = models.ForeignKey(Authors) unique = models.CharField(max_length = 255, unique = True) url = models.URLField() summary = models.TextField(null = True) enclosure = models.CharField("Attachment URL", max_length = 255, null = True) def __unicode__(self): return self.title
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.content_object.name class Announcements(models.Model): title = models.CharField(max_length = 500) pubdate = models.DateTimeField() creator = models.ForeignKey(Authors) unique = models.CharField(max_length = 255, unique = True) url = models.URLField() summary = models.TextField(null = True) enclosure = models.CharField("Attachment URL", max_length = 255, null = True) def __unicode__(self): return self.title
Rename of the author field to content_type in the model, in order to avoid confusion
Rename of the author field to content_type in the model, in order to avoid confusion
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): - author = models.ForeignKey(ContentType) + content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() - content_object = generic.GenericForeignKey('author', 'object_id') + content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.content_object.name class Announcements(models.Model): title = models.CharField(max_length = 500) pubdate = models.DateTimeField() creator = models.ForeignKey(Authors) unique = models.CharField(max_length = 255, unique = True) url = models.URLField() summary = models.TextField(null = True) enclosure = models.CharField("Attachment URL", max_length = 255, null = True) def __unicode__(self): return self.title
Rename of the author field to content_type in the model, in order to avoid confusion
## Code Before: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): author = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('author', 'object_id') def __unicode__(self): return self.content_object.name class Announcements(models.Model): title = models.CharField(max_length = 500) pubdate = models.DateTimeField() creator = models.ForeignKey(Authors) unique = models.CharField(max_length = 255, unique = True) url = models.URLField() summary = models.TextField(null = True) enclosure = models.CharField("Attachment URL", max_length = 255, null = True) def __unicode__(self): return self.title ## Instruction: Rename of the author field to content_type in the model, in order to avoid confusion ## Code After: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.content_object.name class Announcements(models.Model): title = models.CharField(max_length = 500) pubdate = models.DateTimeField() creator = models.ForeignKey(Authors) unique = models.CharField(max_length = 255, unique = True) url = models.URLField() summary = models.TextField(null = True) enclosure = models.CharField("Attachment URL", max_length = 255, null = True) def __unicode__(self): return self.title
d6b7cccb14cd1f82bb3a6b070999204fafacf07e
hyper/common/util.py
hyper/common/util.py
from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ try: host, port = host_port_str.rsplit(':', 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ if ']' in host_port_str: delim = ']:' else: delim = ':' try: host, port = host_port_str.rsplit(delim, 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
Fix to_host_port_tuple to resolve test case issues
Fix to_host_port_tuple to resolve test case issues
Python
mit
Lukasa/hyper,lawnmowerlatte/hyper,irvind/hyper,Lukasa/hyper,lawnmowerlatte/hyper,fredthomsen/hyper,irvind/hyper,plucury/hyper,fredthomsen/hyper,plucury/hyper
from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ + if ']' in host_port_str: + delim = ']:' + else: + delim = ':' + try: - host, port = host_port_str.rsplit(':', 1) + host, port = host_port_str.rsplit(delim, 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
Fix to_host_port_tuple to resolve test case issues
## Code Before: from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ try: host, port = host_port_str.rsplit(':', 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port)) ## Instruction: Fix to_host_port_tuple to resolve test case issues ## Code After: from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: raise ValueError("Non string type.") def to_bytestring_tuple(*x): """ Converts the given strings to a bytestring if necessary, returning a tuple. Uses ``to_bytestring``. """ return tuple(imap(to_bytestring, x)) def to_host_port_tuple(host_port_str, default_port=80): """ Converts the given string containing a host and possibly a port to a tuple. """ if ']' in host_port_str: delim = ']:' else: delim = ':' try: host, port = host_port_str.rsplit(delim, 1) except ValueError: host, port = host_port_str, default_port else: port = int(port) host = host.strip('[]') return ((host, port))
67a50f33177e0fa6aec15fc7d26836c38b374c31
plugins/lastfm.py
plugins/lastfm.py
from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", api_key=api_key, user=user, limit=1) if 'error' in response: if inp: # specified a user name return "error: %s" % response["message"] else: return "your nick is not a LastFM account. try '.lastfm username'." track = response["recenttracks"]["track"] title = track["name"] album = track["album"]["#text"] artist = track["artist"]["#text"] ret = "\x02%s\x0F's last track - \x02%s\x0f" % (user, title) if artist: ret += " by \x02%s\x0f" % artist if album: ret += " on \x02%s\x0f" % album say(ret)
from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", api_key=api_key, user=user, limit=1) if 'error' in response: if inp: # specified a user name return "error: %s" % response["message"] else: return "your nick is not a LastFM account. try '.lastfm username'." tracks = response["recenttracks"]["track"] if len(tracks) == 0: return "no recent tracks for user %r found" % user if type(tracks) == list: # if the user is listening to something, the tracks entry is a list # the first item is the current track track = tracks[0] status = 'current track' elif type(tracks) == dict: # otherwise, they aren't listening to anything right now, and # the tracks entry is a dict representing the most recent track track = tracks status = 'last track' else: return "error parsing track listing" title = track["name"] album = track["album"]["#text"] artist = track["artist"]["#text"] ret = "\x02%s\x0F's %s - \x02%s\x0f" % (user, status, title) if artist: ret += " by \x02%s\x0f" % artist if album: ret += " on \x02%s\x0f" % album say(ret)
Fix last.fm bug for users not listening to something.
Fix last.fm bug for users not listening to something. The last.fm plugin previously worked only for users not listening to anything, and then it was 'fixed' for users listening to something, but broke for users not listening to something. See lastfm.py comments for changes.
Python
unlicense
parkrrr/skybot,Jeebeevee/DouweBot_JJ15,craisins/wh2kbot,callumhogsden/ausbot,df-5/skybot,ddwo/nhl-bot,Jeebeevee/DouweBot,rmmh/skybot,TeamPeggle/ppp-helpdesk,crisisking/skybot,Teino1978-Corp/Teino1978-Corp-skybot,isislab/botbot,cmarguel/skybot,jmgao/skybot,craisins/nascarbot,olslash/skybot,andyeff/skybot,SophosBlitz/glacon,elitan/mybot
from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", api_key=api_key, user=user, limit=1) if 'error' in response: if inp: # specified a user name return "error: %s" % response["message"] else: return "your nick is not a LastFM account. try '.lastfm username'." - track = response["recenttracks"]["track"] + tracks = response["recenttracks"]["track"] + + if len(tracks) == 0: + return "no recent tracks for user %r found" % user + + if type(tracks) == list: + # if the user is listening to something, the tracks entry is a list + # the first item is the current track + track = tracks[0] + status = 'current track' + elif type(tracks) == dict: + # otherwise, they aren't listening to anything right now, and + # the tracks entry is a dict representing the most recent track + track = tracks + status = 'last track' + else: + return "error parsing track listing" + title = track["name"] album = track["album"]["#text"] artist = track["artist"]["#text"] - ret = "\x02%s\x0F's last track - \x02%s\x0f" % (user, title) + ret = "\x02%s\x0F's %s - \x02%s\x0f" % (user, status, title) if artist: ret += " by \x02%s\x0f" % artist if album: ret += " on \x02%s\x0f" % album say(ret)
Fix last.fm bug for users not listening to something.
## Code Before: from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", api_key=api_key, user=user, limit=1) if 'error' in response: if inp: # specified a user name return "error: %s" % response["message"] else: return "your nick is not a LastFM account. try '.lastfm username'." track = response["recenttracks"]["track"] title = track["name"] album = track["album"]["#text"] artist = track["artist"]["#text"] ret = "\x02%s\x0F's last track - \x02%s\x0f" % (user, title) if artist: ret += " by \x02%s\x0f" % artist if album: ret += " on \x02%s\x0f" % album say(ret) ## Instruction: Fix last.fm bug for users not listening to something. ## Code After: from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", api_key=api_key, user=user, limit=1) if 'error' in response: if inp: # specified a user name return "error: %s" % response["message"] else: return "your nick is not a LastFM account. try '.lastfm username'." tracks = response["recenttracks"]["track"] if len(tracks) == 0: return "no recent tracks for user %r found" % user if type(tracks) == list: # if the user is listening to something, the tracks entry is a list # the first item is the current track track = tracks[0] status = 'current track' elif type(tracks) == dict: # otherwise, they aren't listening to anything right now, and # the tracks entry is a dict representing the most recent track track = tracks status = 'last track' else: return "error parsing track listing" title = track["name"] album = track["album"]["#text"] artist = track["artist"]["#text"] ret = "\x02%s\x0F's %s - \x02%s\x0f" % (user, status, title) if artist: ret += " by \x02%s\x0f" % artist if album: ret += " on \x02%s\x0f" % album say(ret)
c487dfc63e71abb0e11534c42591c216def5c433
ITDB/ITDB_Main/views.py
ITDB/ITDB_Main/views.py
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): try: theater = Theater.objects.get(pk=theater_id) except Theater.DoesNotExist: raise Http404("Theater does not exist") return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): theater = get_object_or_404(Theater, pk=theater_id) return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
Update theater view to use get_object_or_404 shortcut
Update theater view to use get_object_or_404 shortcut
Python
apache-2.0
Plaudenslager/ITDB,Plaudenslager/ITDB,Plaudenslager/ITDB
from django.http import Http404 from django.http import HttpResponse - from django.shortcuts import render + from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): + + theater = get_object_or_404(Theater, pk=theater_id) - try: - theater = Theater.objects.get(pk=theater_id) - except Theater.DoesNotExist: - raise Http404("Theater does not exist") return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
Update theater view to use get_object_or_404 shortcut
## Code Before: from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): try: theater = Theater.objects.get(pk=theater_id) except Theater.DoesNotExist: raise Http404("Theater does not exist") return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People") ## Instruction: Update theater view to use get_object_or_404 shortcut ## Code After: from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main index. This is where you will be able to search.") # page for Theaters & theater details. Will show the details about a theater, and a list of Productions. def theaters(request): all_theaters_by_alpha = Theater.objects.order_by('name') context = RequestContext(request, {'all_theaters_by_alpha': all_theaters_by_alpha}) return render(request, 'ITDB_Main/theaters.html',context) def theater_detail(request, theater_id): theater = get_object_or_404(Theater, pk=theater_id) return render(request, 'ITDB_Main/theater_detail.html', {'theater' : theater}) # page for People def person(request): return HttpResponse("Page showing a single person - e.g. actor, director, writer, followed by a list of Productions") # page for Plays def play(request): return HttpResponse("Page showing a single play, followed by a list of Productions") # page for Productions def production(request): return HttpResponse("Page showing a single production, with details about theater and play, followed by a list of People")
18ed712bad3beb8c128f56638878e66f34bcf722
Lib/test/test_binhex.py
Lib/test/test_binhex.py
import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open(fname1, 'w') except: raise TestSkipped, "Cannot test binhex without a temp file" start = 'Jack is my hero' f.write(start) f.close() binhex.binhex(fname1, fname2) if verbose: print 'binhex' binhex.hexbin(fname2, fname1) if verbose: print 'hexbin' f = open(fname1, 'r') finish = f.readline() f.close() # on Windows an open file cannot be unlinked if start != finish: print 'Error: binhex != hexbin' elif verbose: print 'binhex == hexbin' try: import os os.unlink(fname1) os.unlink(fname2) except: pass test()
import binhex import os import tempfile import test_support import unittest class BinHexTestCase(unittest.TestCase): def setUp(self): self.fname1 = tempfile.mktemp() self.fname2 = tempfile.mktemp() def tearDown(self): try: os.unlink(self.fname1) except OSError: pass try: os.unlink(self.fname2) except OSError: pass DATA = 'Jack is my hero' def test_binhex(self): f = open(self.fname1, 'w') f.write(self.DATA) f.close() binhex.binhex(self.fname1, self.fname2) binhex.hexbin(self.fname2, self.fname1) f = open(self.fname1, 'r') finish = f.readline() f.close() self.assertEqual(self.DATA, finish) test_support.run_unittest(BinHexTestCase)
Convert binhex regression test to PyUnit. We could use a better test for this.
Convert binhex regression test to PyUnit. We could use a better test for this.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
import binhex + import os import tempfile - from test_support import verbose, TestSkipped + import test_support + import unittest - def test(): + class BinHexTestCase(unittest.TestCase): - try: - fname1 = tempfile.mktemp() - fname2 = tempfile.mktemp() - f = open(fname1, 'w') - except: - raise TestSkipped, "Cannot test binhex without a temp file" - start = 'Jack is my hero' - f.write(start) - f.close() + def setUp(self): + self.fname1 = tempfile.mktemp() + self.fname2 = tempfile.mktemp() - binhex.binhex(fname1, fname2) - if verbose: - print 'binhex' + def tearDown(self): + try: os.unlink(self.fname1) + except OSError: pass + try: os.unlink(self.fname2) + except OSError: pass - binhex.hexbin(fname2, fname1) - if verbose: - print 'hexbin' + DATA = 'Jack is my hero' - f = open(fname1, 'r') - finish = f.readline() - f.close() # on Windows an open file cannot be unlinked - if start != finish: - print 'Error: binhex != hexbin' - elif verbose: - print 'binhex == hexbin' + def test_binhex(self): + f = open(self.fname1, 'w') + f.write(self.DATA) + f.close() + binhex.binhex(self.fname1, self.fname2) - try: - import os - os.unlink(fname1) - os.unlink(fname2) - except: - pass - test() + binhex.hexbin(self.fname2, self.fname1) + + f = open(self.fname1, 'r') + finish = f.readline() + f.close() + + self.assertEqual(self.DATA, finish) + + + test_support.run_unittest(BinHexTestCase) +
Convert binhex regression test to PyUnit. We could use a better test for this.
## Code Before: import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open(fname1, 'w') except: raise TestSkipped, "Cannot test binhex without a temp file" start = 'Jack is my hero' f.write(start) f.close() binhex.binhex(fname1, fname2) if verbose: print 'binhex' binhex.hexbin(fname2, fname1) if verbose: print 'hexbin' f = open(fname1, 'r') finish = f.readline() f.close() # on Windows an open file cannot be unlinked if start != finish: print 'Error: binhex != hexbin' elif verbose: print 'binhex == hexbin' try: import os os.unlink(fname1) os.unlink(fname2) except: pass test() ## Instruction: Convert binhex regression test to PyUnit. We could use a better test for this. ## Code After: import binhex import os import tempfile import test_support import unittest class BinHexTestCase(unittest.TestCase): def setUp(self): self.fname1 = tempfile.mktemp() self.fname2 = tempfile.mktemp() def tearDown(self): try: os.unlink(self.fname1) except OSError: pass try: os.unlink(self.fname2) except OSError: pass DATA = 'Jack is my hero' def test_binhex(self): f = open(self.fname1, 'w') f.write(self.DATA) f.close() binhex.binhex(self.fname1, self.fname2) binhex.hexbin(self.fname2, self.fname1) f = open(self.fname1, 'r') finish = f.readline() f.close() self.assertEqual(self.DATA, finish) test_support.run_unittest(BinHexTestCase)
9fece51bc6b3496381871c0fc7db486f8fbfebd7
chef/tests/test_role.py
chef/tests/test_role.py
from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r.run_list, []) def test_create(self): name = self.random() r = Role.create(name, description='A test role', run_list=['recipe[foo]']) self.register(r) self.assertEqual(r.description, 'A test role') self.assertEqual(r.run_list, ['recipe[foo]']) r2 = Role(name) self.assertTrue(r2.exists) self.assertEqual(r2.description, 'A test role') self.assertEqual(r2.run_list, ['recipe[foo]']) def test_delete(self): name = self.random() r = Role.create(name) r.delete() for n in Role.list(): self.assertNotEqual(n, name) self.assertFalse(Role(name).exists)
from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r.run_list, []) self.assertEqual(r.default_attributes['test_attr'], 'default') self.assertEqual(r.default_attributes['nested']['nested_attr'], 1) self.assertEqual(r.override_attributes['test_attr'], 'override') def test_create(self): name = self.random() r = Role.create(name, description='A test role', run_list=['recipe[foo]'], default_attributes={'attr': 'foo'}, override_attributes={'attr': 'bar'}) self.register(r) self.assertEqual(r.description, 'A test role') self.assertEqual(r.run_list, ['recipe[foo]']) self.assertEqual(r.default_attributes['attr'], 'foo') self.assertEqual(r.override_attributes['attr'], 'bar') r2 = Role(name) self.assertTrue(r2.exists) self.assertEqual(r2.description, 'A test role') self.assertEqual(r2.run_list, ['recipe[foo]']) self.assertEqual(r2.default_attributes['attr'], 'foo') self.assertEqual(r2.override_attributes['attr'], 'bar') def test_delete(self): name = self.random() r = Role.create(name) r.delete() for n in Role.list(): self.assertNotEqual(n, name) self.assertFalse(Role(name).exists)
Add tests for role attributes.
Add tests for role attributes.
Python
apache-2.0
cread/pychef,jarosser06/pychef,jarosser06/pychef,coderanger/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,dipakvwarade/pychef,coderanger/pychef,Scalr/pychef
from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r.run_list, []) + self.assertEqual(r.default_attributes['test_attr'], 'default') + self.assertEqual(r.default_attributes['nested']['nested_attr'], 1) + self.assertEqual(r.override_attributes['test_attr'], 'override') def test_create(self): name = self.random() - r = Role.create(name, description='A test role', run_list=['recipe[foo]']) + r = Role.create(name, description='A test role', run_list=['recipe[foo]'], + default_attributes={'attr': 'foo'}, override_attributes={'attr': 'bar'}) self.register(r) self.assertEqual(r.description, 'A test role') self.assertEqual(r.run_list, ['recipe[foo]']) + self.assertEqual(r.default_attributes['attr'], 'foo') + self.assertEqual(r.override_attributes['attr'], 'bar') r2 = Role(name) self.assertTrue(r2.exists) self.assertEqual(r2.description, 'A test role') self.assertEqual(r2.run_list, ['recipe[foo]']) + self.assertEqual(r2.default_attributes['attr'], 'foo') + self.assertEqual(r2.override_attributes['attr'], 'bar') def test_delete(self): name = self.random() r = Role.create(name) r.delete() for n in Role.list(): self.assertNotEqual(n, name) self.assertFalse(Role(name).exists)
Add tests for role attributes.
## Code Before: from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r.run_list, []) def test_create(self): name = self.random() r = Role.create(name, description='A test role', run_list=['recipe[foo]']) self.register(r) self.assertEqual(r.description, 'A test role') self.assertEqual(r.run_list, ['recipe[foo]']) r2 = Role(name) self.assertTrue(r2.exists) self.assertEqual(r2.description, 'A test role') self.assertEqual(r2.run_list, ['recipe[foo]']) def test_delete(self): name = self.random() r = Role.create(name) r.delete() for n in Role.list(): self.assertNotEqual(n, name) self.assertFalse(Role(name).exists) ## Instruction: Add tests for role attributes. ## Code After: from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r.run_list, []) self.assertEqual(r.default_attributes['test_attr'], 'default') self.assertEqual(r.default_attributes['nested']['nested_attr'], 1) self.assertEqual(r.override_attributes['test_attr'], 'override') def test_create(self): name = self.random() r = Role.create(name, description='A test role', run_list=['recipe[foo]'], default_attributes={'attr': 'foo'}, override_attributes={'attr': 'bar'}) self.register(r) self.assertEqual(r.description, 'A test role') self.assertEqual(r.run_list, ['recipe[foo]']) self.assertEqual(r.default_attributes['attr'], 'foo') self.assertEqual(r.override_attributes['attr'], 'bar') r2 = Role(name) self.assertTrue(r2.exists) self.assertEqual(r2.description, 'A test role') self.assertEqual(r2.run_list, ['recipe[foo]']) self.assertEqual(r2.default_attributes['attr'], 'foo') self.assertEqual(r2.override_attributes['attr'], 'bar') def test_delete(self): name = self.random() r = Role.create(name) r.delete() for n in Role.list(): self.assertNotEqual(n, name) self.assertFalse(Role(name).exists)
9f925f0da6d3a06d085ee71b8bee0fcdecaed5a0
marrow/schema/transform/primitive.py
marrow/schema/transform/primitive.py
raise ImportError("For future use.") from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null Tuple List Set Mapping Sequence Tuple Integer Float String Decimal Boolean DateTime Date Time """
from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null Tuple List Set Mapping Sequence Tuple Integer Float String Decimal Boolean DateTime Date Time """
Fix for insanely silly pip.
Fix for insanely silly pip.
Python
mit
marrow/schema,marrow/schema
- - raise ImportError("For future use.") from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null Tuple List Set Mapping Sequence Tuple Integer Float String Decimal Boolean DateTime Date Time """ +
Fix for insanely silly pip.
## Code Before: raise ImportError("For future use.") from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null Tuple List Set Mapping Sequence Tuple Integer Float String Decimal Boolean DateTime Date Time """ ## Instruction: Fix for insanely silly pip. ## Code After: from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null Tuple List Set Mapping Sequence Tuple Integer Float String Decimal Boolean DateTime Date Time """
57ef9c9166d5bc573589cb58313056a2ef515ad8
tests/test_misc.py
tests/test_misc.py
import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]) _ = _.map(add,1)\ .map(add_one)\ .flatmap( double)\ .flatmap(repeat_n_times, n = 2) _.drain()
import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]) _ = _.map(add,1)\ .map(add_one)\ .flatmap( double)\ .flatmap(repeat_n_times, n = 2) _.drain() def test_embedded(self): stream_1 = ms.stream(range(10)) stream_2 = ms.stream(stream_1) stream_3 = ms.stream(stream_2) stream_3.drain()
Add test for nesting streamer data-structures.
Add test for nesting streamer data-structures.
Python
mit
caffeine-potent/Streamer-Datastructure
import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]) _ = _.map(add,1)\ .map(add_one)\ .flatmap( double)\ .flatmap(repeat_n_times, n = 2) _.drain() + def test_embedded(self): + stream_1 = ms.stream(range(10)) + stream_2 = ms.stream(stream_1) + stream_3 = ms.stream(stream_2) + stream_3.drain()
Add test for nesting streamer data-structures.
## Code Before: import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]) _ = _.map(add,1)\ .map(add_one)\ .flatmap( double)\ .flatmap(repeat_n_times, n = 2) _.drain() ## Instruction: Add test for nesting streamer data-structures. ## Code After: import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]) _ = _.map(add,1)\ .map(add_one)\ .flatmap( double)\ .flatmap(repeat_n_times, n = 2) _.drain() def test_embedded(self): stream_1 = ms.stream(range(10)) stream_2 = ms.stream(stream_1) stream_3 = ms.stream(stream_2) stream_3.drain()
30f1156140a4a246a2090aa3e8d5183ceea0beed
tests/test_mmap.py
tests/test_mmap.py
from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_init_alt_name') self.assertFalse(os.path.exists(expected_fn)) fn, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_init_alt_name') self.assertEqual(fn, expected_fn) self.assertTrue(os.path.exists(fn))
from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_init_alt_name') self.assertFalse(os.path.exists(expected_fn)) fn, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_init_alt_name') self.assertEqual(fn, expected_fn) self.assertTrue(os.path.exists(fn)) def test_size_adjusting1(self): """mmapped files must be at least PAGESIZE in size""" _, sz, m = mmstats._init_mmap(path=self.path, filename='mmstats-test_size_adjusting-1', size=1) self.assertEqual(sz, mmstats.PAGESIZE) self.assertEqual(m[:], '\x00' * mmstats.PAGESIZE) def test_size_adjusting2(self): """mmapped files must be multiples of PAGESIZE""" _, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_size_adjusting-2', size=(mmstats.PAGESIZE+1) ) self.assertEqual(sz, mmstats.PAGESIZE * 2) self.assertEqual(m[:], '\x00' * mmstats.PAGESIZE * 2) def test_truncate(self): """mmapped files must be initialized with null bytes""" fn, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_truncate', ) m[0] = 'X' reopened_file = open(fn) self.assertEqual(reopened_file.read(1), 'X') self.assertEqual(reopened_file.read(1), '\x00')
Add some more mmap related tests
Add some more mmap related tests
Python
bsd-3-clause
schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats
from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_init_alt_name') self.assertFalse(os.path.exists(expected_fn)) fn, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_init_alt_name') self.assertEqual(fn, expected_fn) self.assertTrue(os.path.exists(fn)) + def test_size_adjusting1(self): + """mmapped files must be at least PAGESIZE in size""" + _, sz, m = mmstats._init_mmap(path=self.path, + filename='mmstats-test_size_adjusting-1', size=1) + + self.assertEqual(sz, mmstats.PAGESIZE) + self.assertEqual(m[:], '\x00' * mmstats.PAGESIZE) + + def test_size_adjusting2(self): + """mmapped files must be multiples of PAGESIZE""" + _, sz, m = mmstats._init_mmap( + path=self.path, + filename='mmstats-test_size_adjusting-2', + size=(mmstats.PAGESIZE+1) + ) + + self.assertEqual(sz, mmstats.PAGESIZE * 2) + self.assertEqual(m[:], '\x00' * mmstats.PAGESIZE * 2) + + def test_truncate(self): + """mmapped files must be initialized with null bytes""" + fn, sz, m = mmstats._init_mmap( + path=self.path, + filename='mmstats-test_truncate', + ) + + m[0] = 'X' + + reopened_file = open(fn) + self.assertEqual(reopened_file.read(1), 'X') + self.assertEqual(reopened_file.read(1), '\x00') +
Add some more mmap related tests
## Code Before: from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_init_alt_name') self.assertFalse(os.path.exists(expected_fn)) fn, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_init_alt_name') self.assertEqual(fn, expected_fn) self.assertTrue(os.path.exists(fn)) ## Instruction: Add some more mmap related tests ## Code After: from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_init_alt_name') self.assertFalse(os.path.exists(expected_fn)) fn, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_init_alt_name') self.assertEqual(fn, expected_fn) self.assertTrue(os.path.exists(fn)) def test_size_adjusting1(self): """mmapped files must be at least PAGESIZE in size""" _, sz, m = mmstats._init_mmap(path=self.path, filename='mmstats-test_size_adjusting-1', size=1) self.assertEqual(sz, mmstats.PAGESIZE) self.assertEqual(m[:], '\x00' * mmstats.PAGESIZE) def test_size_adjusting2(self): """mmapped files must be multiples of PAGESIZE""" _, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_size_adjusting-2', size=(mmstats.PAGESIZE+1) ) self.assertEqual(sz, mmstats.PAGESIZE * 2) self.assertEqual(m[:], '\x00' * mmstats.PAGESIZE * 2) def test_truncate(self): """mmapped files must be initialized with null bytes""" fn, sz, m = mmstats._init_mmap( path=self.path, filename='mmstats-test_truncate', ) m[0] = 'X' reopened_file = open(fn) self.assertEqual(reopened_file.read(1), 'X') self.assertEqual(reopened_file.read(1), '\x00')
89a8d6021d8ca8a714af018f3168298109013c6f
radio/__init__.py
radio/__init__.py
from django.utils.version import get_version from subprocess import check_output, CalledProcessError VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __git_hash__ = '0' __fullversion__ = '{} #{}'.format(__version__,__git_hash__) print('Trunk-Player Version ' + __fullversion__)
import logging from django.utils.version import get_version from subprocess import check_output, CalledProcessError logger = logging.getLogger(__name__) VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __git_hash__ = '0' __fullversion__ = '{} #{}'.format(__version__,__git_hash__) logger.error('Trunk-Player Version ' + __fullversion__)
Move version print to logger
Move version print to logger
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
+ import logging + from django.utils.version import get_version from subprocess import check_output, CalledProcessError + + logger = logging.getLogger(__name__) + VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __git_hash__ = '0' __fullversion__ = '{} #{}'.format(__version__,__git_hash__) - print('Trunk-Player Version ' + __fullversion__) + logger.error('Trunk-Player Version ' + __fullversion__)
Move version print to logger
## Code Before: from django.utils.version import get_version from subprocess import check_output, CalledProcessError VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __git_hash__ = '0' __fullversion__ = '{} #{}'.format(__version__,__git_hash__) print('Trunk-Player Version ' + __fullversion__) ## Instruction: Move version print to logger ## Code After: import logging from django.utils.version import get_version from subprocess import check_output, CalledProcessError logger = logging.getLogger(__name__) VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __git_hash__ = '0' __fullversion__ = '{} #{}'.format(__version__,__git_hash__) logger.error('Trunk-Player Version ' + __fullversion__)
009113edec59e788bb495b80ddaf763aabd8c82f
GreyMatter/notes.py
GreyMatter/notes.py
import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.commit() conn.close() def note_something(speech_text): conn = sqlite3.connect('memory.db') words_of_message = speech_text.split() words_of_message.remove('note') cleaned_message = ' '.join(words_of_message) conn.execute("INSERT INTO notes (notes, notes_date) VALUES (?, ?)", (cleaned_message, datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() tts('Your note has been saved.')
import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.close() def note_something(speech_text): conn = sqlite3.connect('memory.db') words_of_message = speech_text.split() words_of_message.remove('note') cleaned_message = ' '.join(words_of_message) conn.execute("INSERT INTO notes (notes, notes_date) VALUES (?, ?)", (cleaned_message, datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() tts('Your note has been saved.')
Remove unused line of code
Remove unused line of code
Python
mit
Melissa-AI/Melissa-Core,Melissa-AI/Melissa-Core,Melissa-AI/Melissa-Core,anurag-ks/Melissa-Core,Melissa-AI/Melissa-Core,anurag-ks/Melissa-Core,anurag-ks/Melissa-Core,anurag-ks/Melissa-Core
import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) - conn.commit() conn.close() def note_something(speech_text): conn = sqlite3.connect('memory.db') words_of_message = speech_text.split() words_of_message.remove('note') cleaned_message = ' '.join(words_of_message) conn.execute("INSERT INTO notes (notes, notes_date) VALUES (?, ?)", (cleaned_message, datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() tts('Your note has been saved.') +
Remove unused line of code
## Code Before: import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.commit() conn.close() def note_something(speech_text): conn = sqlite3.connect('memory.db') words_of_message = speech_text.split() words_of_message.remove('note') cleaned_message = ' '.join(words_of_message) conn.execute("INSERT INTO notes (notes, notes_date) VALUES (?, ?)", (cleaned_message, datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() tts('Your note has been saved.') ## Instruction: Remove unused line of code ## Code After: import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.close() def note_something(speech_text): conn = sqlite3.connect('memory.db') words_of_message = speech_text.split() words_of_message.remove('note') cleaned_message = ' '.join(words_of_message) conn.execute("INSERT INTO notes (notes, notes_date) VALUES (?, ?)", (cleaned_message, datetime.strftime(datetime.now(), '%d-%m-%Y'))) conn.commit() conn.close() tts('Your note has been saved.')
7f42966277eff0d16fd15d5192cffcf7a91aae2e
expyfun/__init__.py
expyfun/__init__.py
__version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from ._eyelink_controller import EyelinkController from ._create_system_config import create_system_config # initialize logging set_log_level(None, False)
__version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from ._eyelink_controller import EyelinkController from ._create_system_config import create_system_config from . import analyze # fast enough, include here # initialize logging set_log_level(None, False)
Add `analyze` to `expyfun` init
FIX: Add `analyze` to `expyfun` init
Python
bsd-3-clause
LABSN/expyfun,rkmaddox/expyfun,Eric89GXL/expyfun,lkishline/expyfun,drammock/expyfun
__version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from ._eyelink_controller import EyelinkController from ._create_system_config import create_system_config + from . import analyze # fast enough, include here # initialize logging set_log_level(None, False)
Add `analyze` to `expyfun` init
## Code Before: __version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from ._eyelink_controller import EyelinkController from ._create_system_config import create_system_config # initialize logging set_log_level(None, False) ## Instruction: Add `analyze` to `expyfun` init ## Code After: __version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from ._eyelink_controller import EyelinkController from ._create_system_config import create_system_config from . import analyze # fast enough, include here # initialize logging set_log_level(None, False)
9d4dca76abb3f6fb0f107c93874942496f4f8e7b
src/healthcheck/__init__.py
src/healthcheck/__init__.py
import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message if response is not None: result["status"] = response.status_code result["response_time_ms"] = int(response.elapsed.total_seconds() * 1000) return result def check_site(self, site): response = None try: response = requests.get(site["url"]) if response.status_code not in site["acceptable_statuses"]: print("Bad status code: {}".format(response.status_code)) return self._result(site, "DOWN", response, "Unacceptable status code") for mandatory_string in site.get("mandatory_strings", []): if mandatory_string not in response.text: print("String not found in response: " + mandatory_string) return self._result(site, "DOWN", response, "String not found in response: {}".format(mandatory_string)) return self._result(site, "UP", response) except Exception as err: print(err) return self._result(site, "UNKNOWN", response, "Exception while trying to check site health: {}".format(err))
import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message if response is not None: result["status"] = response.status_code result["response_time_ms"] = int(response.elapsed.total_seconds() * 1000) return result def check_site(self, site): response = None try: print(f"Checking site {site['name']}") response = requests.get(site["url"]) if response.status_code not in site["acceptable_statuses"]: print("Bad status code: {}".format(response.status_code)) return self._result(site, "DOWN", response, "Unacceptable status code") for mandatory_string in site.get("mandatory_strings", []): if mandatory_string not in response.text: print("String not found in response: " + mandatory_string) return self._result(site, "DOWN", response, "String not found in response: {}".format(mandatory_string)) return self._result(site, "UP", response) except Exception as err: print(err) return self._result(site, "UNKNOWN", response, "Exception while trying to check site health: {}".format(err))
Debug print each health check
Debug print each health check
Python
mit
Vilsepi/nysseituu,Vilsepi/nysseituu
import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message if response is not None: result["status"] = response.status_code result["response_time_ms"] = int(response.elapsed.total_seconds() * 1000) return result def check_site(self, site): response = None try: + print(f"Checking site {site['name']}") response = requests.get(site["url"]) if response.status_code not in site["acceptable_statuses"]: print("Bad status code: {}".format(response.status_code)) return self._result(site, "DOWN", response, "Unacceptable status code") for mandatory_string in site.get("mandatory_strings", []): if mandatory_string not in response.text: print("String not found in response: " + mandatory_string) return self._result(site, "DOWN", response, "String not found in response: {}".format(mandatory_string)) return self._result(site, "UP", response) except Exception as err: print(err) return self._result(site, "UNKNOWN", response, "Exception while trying to check site health: {}".format(err))
Debug print each health check
## Code Before: import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message if response is not None: result["status"] = response.status_code result["response_time_ms"] = int(response.elapsed.total_seconds() * 1000) return result def check_site(self, site): response = None try: response = requests.get(site["url"]) if response.status_code not in site["acceptable_statuses"]: print("Bad status code: {}".format(response.status_code)) return self._result(site, "DOWN", response, "Unacceptable status code") for mandatory_string in site.get("mandatory_strings", []): if mandatory_string not in response.text: print("String not found in response: " + mandatory_string) return self._result(site, "DOWN", response, "String not found in response: {}".format(mandatory_string)) return self._result(site, "UP", response) except Exception as err: print(err) return self._result(site, "UNKNOWN", response, "Exception while trying to check site health: {}".format(err)) ## Instruction: Debug print each health check ## Code After: import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message if response is not None: result["status"] = response.status_code result["response_time_ms"] = int(response.elapsed.total_seconds() * 1000) return result def check_site(self, site): response = None try: print(f"Checking site {site['name']}") response = requests.get(site["url"]) if response.status_code not in site["acceptable_statuses"]: print("Bad status code: {}".format(response.status_code)) return self._result(site, "DOWN", response, "Unacceptable status code") for mandatory_string in site.get("mandatory_strings", []): if mandatory_string not in response.text: print("String not found in response: " + mandatory_string) return self._result(site, "DOWN", response, "String not found in response: {}".format(mandatory_string)) return self._result(site, "UP", response) except Exception as err: print(err) return self._result(site, "UNKNOWN", response, "Exception while trying to check site health: {}".format(err))
59544c531a4cd52e363bf0714ff51bac779c2018
fleece/httperror.py
fleece/httperror.py
try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler class HTTPError(Exception): default_status = 500 def __init__(self, status=None, message=None): """Initialize class.""" responses = BaseHTTPRequestHandler.responses self.status_code = status or self.default_status error_message = "%d: %s" % (self.status_code, responses[self.status_code][0]) if message: error_message = "%s - %s" % (error_message, message) super(HTTPError, self).__init__(error_message)
try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler # import lzstring # lz = lzstring.LZString() # lz.decompressFromBase64(SECRET) SECRET = ('FAAj4yrAKVogfQeAlCV9qIDQ0agHTLQxxKK76U0GEKZg' '4Dkl9YA9NADoQfeJQHFiC4gAPgCJJ4np07BZS8OMqyo4' 'kaNDcABoXUpoHePpAAuIxb5YQZq+cItbYXQFpitGjjfNgQAA') class HTTPError(Exception): default_status = 500 def __init__(self, status=None, message=None): """Initialize class.""" responses = BaseHTTPRequestHandler.responses # Add some additional responses that aren't included... responses[418] = ('I\'m a teapot', SECRET) responses[422] = ('Unprocessable Entity', 'The request was well-formed but was' ' unable to be followed due to semantic errors') self.status_code = status or self.default_status error_message = "%d: %s" % (self.status_code, responses[self.status_code][0]) if message: error_message = "%s - %s" % (error_message, message) super(HTTPError, self).__init__(error_message)
Add extra status codes to HTTPError
Add extra status codes to HTTPError
Python
apache-2.0
racker/fleece,racker/fleece
try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler + + # import lzstring + # lz = lzstring.LZString() + # lz.decompressFromBase64(SECRET) + SECRET = ('FAAj4yrAKVogfQeAlCV9qIDQ0agHTLQxxKK76U0GEKZg' + '4Dkl9YA9NADoQfeJQHFiC4gAPgCJJ4np07BZS8OMqyo4' + 'kaNDcABoXUpoHePpAAuIxb5YQZq+cItbYXQFpitGjjfNgQAA') class HTTPError(Exception): default_status = 500 def __init__(self, status=None, message=None): """Initialize class.""" responses = BaseHTTPRequestHandler.responses + + # Add some additional responses that aren't included... + responses[418] = ('I\'m a teapot', SECRET) + responses[422] = ('Unprocessable Entity', + 'The request was well-formed but was' + ' unable to be followed due to semantic errors') + self.status_code = status or self.default_status error_message = "%d: %s" % (self.status_code, responses[self.status_code][0]) if message: error_message = "%s - %s" % (error_message, message) super(HTTPError, self).__init__(error_message)
Add extra status codes to HTTPError
## Code Before: try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler class HTTPError(Exception): default_status = 500 def __init__(self, status=None, message=None): """Initialize class.""" responses = BaseHTTPRequestHandler.responses self.status_code = status or self.default_status error_message = "%d: %s" % (self.status_code, responses[self.status_code][0]) if message: error_message = "%s - %s" % (error_message, message) super(HTTPError, self).__init__(error_message) ## Instruction: Add extra status codes to HTTPError ## Code After: try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler # import lzstring # lz = lzstring.LZString() # lz.decompressFromBase64(SECRET) SECRET = ('FAAj4yrAKVogfQeAlCV9qIDQ0agHTLQxxKK76U0GEKZg' '4Dkl9YA9NADoQfeJQHFiC4gAPgCJJ4np07BZS8OMqyo4' 'kaNDcABoXUpoHePpAAuIxb5YQZq+cItbYXQFpitGjjfNgQAA') class HTTPError(Exception): default_status = 500 def __init__(self, status=None, message=None): """Initialize class.""" responses = BaseHTTPRequestHandler.responses # Add some additional responses that aren't included... responses[418] = ('I\'m a teapot', SECRET) responses[422] = ('Unprocessable Entity', 'The request was well-formed but was' ' unable to be followed due to semantic errors') self.status_code = status or self.default_status error_message = "%d: %s" % (self.status_code, responses[self.status_code][0]) if message: error_message = "%s - %s" % (error_message, message) super(HTTPError, self).__init__(error_message)
2c572024bf4e5070c999a3653fbc3f5de679e126
common/responses.py
common/responses.py
from django.http import HttpResponse from django.utils import simplejson def JSONResponse(data): return HttpResponse(simplejson.dumps(data), mimetype='application/json')
from django.http import HttpResponse import json def JSONResponse(data): return HttpResponse(json.dumps(data), content_type='application/json')
Fix JSONResponse to work without complaints on django 1.6
Fix JSONResponse to work without complaints on django 1.6
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
from django.http import HttpResponse - from django.utils import simplejson + import json def JSONResponse(data): - return HttpResponse(simplejson.dumps(data), mimetype='application/json') + return HttpResponse(json.dumps(data), content_type='application/json')
Fix JSONResponse to work without complaints on django 1.6
## Code Before: from django.http import HttpResponse from django.utils import simplejson def JSONResponse(data): return HttpResponse(simplejson.dumps(data), mimetype='application/json') ## Instruction: Fix JSONResponse to work without complaints on django 1.6 ## Code After: from django.http import HttpResponse import json def JSONResponse(data): return HttpResponse(json.dumps(data), content_type='application/json')
ac0a166f96509c37ade42e9ae4c35f43137bbbbb
mygpoauth/login/urls.py
mygpoauth/login/urls.py
from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ path('', auth_views.login, { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, }, name='login'), ]
from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ path('', auth_views.LoginView.as_view(), { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, }, name='login'), ]
Use LoginView instead of login
Use LoginView instead of login see https://docs.djangoproject.com/en/dev/releases/1.11/#django-contrib-auth
Python
agpl-3.0
gpodder/mygpo-auth,gpodder/mygpo-auth
from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ - path('', auth_views.login, { + path('', auth_views.LoginView.as_view(), { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, }, name='login'), ]
Use LoginView instead of login
## Code Before: from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ path('', auth_views.login, { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, }, name='login'), ] ## Instruction: Use LoginView instead of login ## Code After: from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ path('', auth_views.LoginView.as_view(), { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, }, name='login'), ]
1fdb305233916d766a82a3d92818f2d2fd593752
get_sample_names.py
get_sample_names.py
import sys from statusdb.db import connections as statusdb if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] pcon = statusdb.ProjectSummaryConnection() prj_obj = pcon.get_entry(prj) prj_samples = prj_obj.get('samples',{}) print("NGI_id\tUser_id") for sample in sorted(prj_samples.keys()): user_name = prj_samples[sample].get('customer_name','') print("{}\t{}".format(sample, user_name))
import sys import os from taca.utils.statusdb import ProjectSummaryConnection from taca.utils.config import load_config if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] statusdb_config = os.getenv('STATUS_DB_CONFIG') conf = load_config(statusdb_config) conf = conf.get('statusdb') pcon = ProjectSummaryConnection(config=conf) prj_obj = pcon.get_entry(prj) prj_samples = prj_obj.get('samples',{}) print("NGI_id\tUser_id") for sample in sorted(prj_samples.keys()): user_name = prj_samples[sample].get('customer_name','') print("{}\t{}".format(sample, user_name))
Use tacas statusdb module instead
Use tacas statusdb module instead
Python
mit
SciLifeLab/standalone_scripts,SciLifeLab/standalone_scripts
import sys - from statusdb.db import connections as statusdb + import os + from taca.utils.statusdb import ProjectSummaryConnection + from taca.utils.config import load_config if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] + statusdb_config = os.getenv('STATUS_DB_CONFIG') + conf = load_config(statusdb_config) + conf = conf.get('statusdb') + - pcon = statusdb.ProjectSummaryConnection() + pcon = ProjectSummaryConnection(config=conf) prj_obj = pcon.get_entry(prj) prj_samples = prj_obj.get('samples',{}) print("NGI_id\tUser_id") for sample in sorted(prj_samples.keys()): user_name = prj_samples[sample].get('customer_name','') print("{}\t{}".format(sample, user_name))
Use tacas statusdb module instead
## Code Before: import sys from statusdb.db import connections as statusdb if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] pcon = statusdb.ProjectSummaryConnection() prj_obj = pcon.get_entry(prj) prj_samples = prj_obj.get('samples',{}) print("NGI_id\tUser_id") for sample in sorted(prj_samples.keys()): user_name = prj_samples[sample].get('customer_name','') print("{}\t{}".format(sample, user_name)) ## Instruction: Use tacas statusdb module instead ## Code After: import sys import os from taca.utils.statusdb import ProjectSummaryConnection from taca.utils.config import load_config if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] statusdb_config = os.getenv('STATUS_DB_CONFIG') conf = load_config(statusdb_config) conf = conf.get('statusdb') pcon = ProjectSummaryConnection(config=conf) prj_obj = pcon.get_entry(prj) prj_samples = prj_obj.get('samples',{}) print("NGI_id\tUser_id") for sample in sorted(prj_samples.keys()): user_name = prj_samples[sample].get('customer_name','') print("{}\t{}".format(sample, user_name))
f551d23531ec4aab041494ac8af921eb77d6b2a0
nb_conda/__init__.py
nb_conda/__init__.py
from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'nbextension/static', 'dest': 'nb_conda', 'require': 'nb_conda/main' }] def _jupyter_server_extension_paths(): return [{ 'require': 'nb_conda.nbextension' }]
from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [dict(section="notebook", src="nbextension/static", dest="nb_conda", require="nb_conda/main")] def _jupyter_server_extension_paths(): return [dict(module='nb_conda.nbextension')]
Update to the latest way to offer metadata
Update to the latest way to offer metadata
Python
bsd-3-clause
Anaconda-Server/nb_conda,Anaconda-Server/nb_conda,Anaconda-Server/nb_conda,Anaconda-Server/nb_conda
from ._version import version_info, __version__ + def _jupyter_nbextension_paths(): + return [dict(section="notebook", - return [{ - 'section': 'notebook', - 'src': 'nbextension/static', + src="nbextension/static", - 'dest': 'nb_conda', - 'require': 'nb_conda/main' - }] + dest="nb_conda", + require="nb_conda/main")] + def _jupyter_server_extension_paths(): + return [dict(module='nb_conda.nbextension')] - return [{ - 'require': 'nb_conda.nbextension' - }]
Update to the latest way to offer metadata
## Code Before: from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'nbextension/static', 'dest': 'nb_conda', 'require': 'nb_conda/main' }] def _jupyter_server_extension_paths(): return [{ 'require': 'nb_conda.nbextension' }] ## Instruction: Update to the latest way to offer metadata ## Code After: from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [dict(section="notebook", src="nbextension/static", dest="nb_conda", require="nb_conda/main")] def _jupyter_server_extension_paths(): return [dict(module='nb_conda.nbextension')]
4546054e84f5c352bb7b5e1fc4f9530e8ebfab78
app.py
app.py
import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use", type=str, default="hubbot.yaml") options = parser.parse_args() if not os.path.exists(os.path.join("hubbot", "data", "data.db")): createDB() logging.basicConfig(stream=sys.stdout, level=logging.INFO) bothandler = BotHandler(options)
import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use", type=str, default="hubbot.yaml") options = parser.parse_args() if not os.path.exists(os.path.join("hubbot", "data", "data.db")): createDB() # set up console output for logging handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')) handler.setLevel(logging.INFO) logging.getLogger().addHandler(handler) bothandler = BotHandler(options)
Use the same format everywhere
[Logging] Use the same format everywhere
Python
mit
HubbeKing/Hubbot_Twisted
import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use", type=str, default="hubbot.yaml") options = parser.parse_args() if not os.path.exists(os.path.join("hubbot", "data", "data.db")): createDB() - logging.basicConfig(stream=sys.stdout, level=logging.INFO) + # set up console output for logging + handler = logging.StreamHandler(stream=sys.stdout) + handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')) + handler.setLevel(logging.INFO) + logging.getLogger().addHandler(handler) bothandler = BotHandler(options)
Use the same format everywhere
## Code Before: import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use", type=str, default="hubbot.yaml") options = parser.parse_args() if not os.path.exists(os.path.join("hubbot", "data", "data.db")): createDB() logging.basicConfig(stream=sys.stdout, level=logging.INFO) bothandler = BotHandler(options) ## Instruction: Use the same format everywhere ## Code After: import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use", type=str, default="hubbot.yaml") options = parser.parse_args() if not os.path.exists(os.path.join("hubbot", "data", "data.db")): createDB() # set up console output for logging handler = logging.StreamHandler(stream=sys.stdout) handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', '%H:%M:%S')) handler.setLevel(logging.INFO) logging.getLogger().addHandler(handler) bothandler = BotHandler(options)
ad69cbc6814e0458ab27412cfad9519fe30545e0
conanfile.py
conanfile.py
from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author = "Michele Caini <michele.caini@gmail.com>" license = "MIT" exports = ["LICENSE"] exports_sources = ["src/*"] no_copy_source = True def package(self): self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="*", dst="include", src="src", keep_path=True) def package_id(self): self.info.header_only()
from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author = "Michele Caini <michele.caini@gmail.com>" license = "MIT" exports = ["LICENSE"] exports_sources = ["src/*"] no_copy_source = True def package(self): self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="*", dst="include", src="src", keep_path=True) def package_info(self): if not self.in_local_cache: self.cpp_info.includedirs = ["src"] def package_id(self): self.info.header_only()
Support package in editable mode
Conan: Support package in editable mode Add a method to the recipe that maps the include path to "src" when the package is put into "editable mode". See: https://docs.conan.io/en/latest/developing_packages/editable_packages.html
Python
mit
skypjack/entt,skypjack/entt,skypjack/entt,skypjack/entt
from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author = "Michele Caini <michele.caini@gmail.com>" license = "MIT" exports = ["LICENSE"] exports_sources = ["src/*"] no_copy_source = True def package(self): self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="*", dst="include", src="src", keep_path=True) + def package_info(self): + if not self.in_local_cache: + self.cpp_info.includedirs = ["src"] + def package_id(self): self.info.header_only()
Support package in editable mode
## Code Before: from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author = "Michele Caini <michele.caini@gmail.com>" license = "MIT" exports = ["LICENSE"] exports_sources = ["src/*"] no_copy_source = True def package(self): self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="*", dst="include", src="src", keep_path=True) def package_id(self): self.info.header_only() ## Instruction: Support package in editable mode ## Code After: from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author = "Michele Caini <michele.caini@gmail.com>" license = "MIT" exports = ["LICENSE"] exports_sources = ["src/*"] no_copy_source = True def package(self): self.copy(pattern="LICENSE", dst="licenses") self.copy(pattern="*", dst="include", src="src", keep_path=True) def package_info(self): if not self.in_local_cache: self.cpp_info.includedirs = ["src"] def package_id(self): self.info.header_only()
0d2816e4ea0bf5a04794456651e79f7db9b2571f
src/jupyter_notebook_gist/config.py
src/jupyter_notebook_gist/config.py
from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id client_id = self.config.NotebookGist.oauth_client_id if not isinstance(client_id, (str, bytes)): client_id = None self.config_manager.update('notebook', { 'oauth_client_id': client_id, })
import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id client_id = self.config.NotebookGist.oauth_client_id if not isinstance(client_id, six.string_types): client_id = None self.config_manager.update('notebook', { 'oauth_client_id': client_id, })
Use six for correct Python2/3 compatibility
Use six for correct Python2/3 compatibility
Python
mpl-2.0
mreid-moz/jupyter-notebook-gist,mozilla/jupyter-notebook-gist,mozilla/jupyter-notebook-gist,mreid-moz/jupyter-notebook-gist
+ import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id client_id = self.config.NotebookGist.oauth_client_id - if not isinstance(client_id, (str, bytes)): + if not isinstance(client_id, six.string_types): client_id = None self.config_manager.update('notebook', { 'oauth_client_id': client_id, })
Use six for correct Python2/3 compatibility
## Code Before: from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id client_id = self.config.NotebookGist.oauth_client_id if not isinstance(client_id, (str, bytes)): client_id = None self.config_manager.update('notebook', { 'oauth_client_id': client_id, }) ## Instruction: Use six for correct Python2/3 compatibility ## Code After: import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The GitHub application OAUTH client secret', ).tag(config=True) def __init__(self, *args, **kwargs): self.config_manager = kwargs.pop('config_manager') super(NotebookGist, self).__init__(*args, **kwargs) # update the frontend settings with the currently passed # OAUTH client id client_id = self.config.NotebookGist.oauth_client_id if not isinstance(client_id, six.string_types): client_id = None self.config_manager.update('notebook', { 'oauth_client_id': client_id, })
54a3cf2994b2620fc3b0e62af8c91b034290e98a
tuskar_ui/infrastructure/dashboard.py
tuskar_ui/infrastructure/dashboard.py
from django.utils.translation import ugettext_lazy as _ import horizon class BasePanels(horizon.PanelGroup): slug = "infrastructure" name = _("Infrastructure") panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', 'history', ) class Infrastructure(horizon.Dashboard): name = _("Infrastructure") slug = "infrastructure" panels = ( BasePanels, ) default_panel = 'overview' permissions = ('openstack.roles.admin',) horizon.register(Infrastructure)
from django.utils.translation import ugettext_lazy as _ import horizon class Infrastructure(horizon.Dashboard): name = _("Infrastructure") slug = "infrastructure" panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', 'history', ) default_panel = 'overview' permissions = ('openstack.roles.admin',) horizon.register(Infrastructure)
Remove the Infrastructure panel group
Remove the Infrastructure panel group Remove the Infrastructure panel group, and place the panels directly under the Infrastructure dashboard. Change-Id: I321f9a84dd885732438ad58b6c62c480c9c10e37
Python
apache-2.0
rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui
from django.utils.translation import ugettext_lazy as _ import horizon - class BasePanels(horizon.PanelGroup): + class Infrastructure(horizon.Dashboard): + name = _("Infrastructure") slug = "infrastructure" - name = _("Infrastructure") panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', 'history', ) - - - class Infrastructure(horizon.Dashboard): - name = _("Infrastructure") - slug = "infrastructure" - panels = ( - BasePanels, - ) default_panel = 'overview' permissions = ('openstack.roles.admin',) horizon.register(Infrastructure)
Remove the Infrastructure panel group
## Code Before: from django.utils.translation import ugettext_lazy as _ import horizon class BasePanels(horizon.PanelGroup): slug = "infrastructure" name = _("Infrastructure") panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', 'history', ) class Infrastructure(horizon.Dashboard): name = _("Infrastructure") slug = "infrastructure" panels = ( BasePanels, ) default_panel = 'overview' permissions = ('openstack.roles.admin',) horizon.register(Infrastructure) ## Instruction: Remove the Infrastructure panel group ## Code After: from django.utils.translation import ugettext_lazy as _ import horizon class Infrastructure(horizon.Dashboard): name = _("Infrastructure") slug = "infrastructure" panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', 'history', ) default_panel = 'overview' permissions = ('openstack.roles.admin',) horizon.register(Infrastructure)
de9a6f647d0a6082e2a473895ec61ba23b41753e
controllers/oldauth.py
controllers/oldauth.py
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if not oa: oa = OldAuth() oa.site = site oa.put() user_name = user.nickname() user_key = hashlib.md5(user.nickname() + date.today().strftime('%Y-%m-%d') + oa.salt).hexdigest() key = base64.b64encode(user_key + user_name) if oa.loginurl: self.redirect(oa.loginurl % key) class Logout(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if oa: self.redirect(users.create_logout_url(oa.logouturl)) def main(): Route([ ('/oldauth', Login), ('/oldauth_exit', Logout), ]) if __name__ == '__main__': main()
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): u = User().current() user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if not oa: oa = OldAuth() oa.site = site oa.put() user_name = user.nickname() user_key = hashlib.md5(user.nickname() + date.today().strftime('%Y-%m-%d') + oa.salt).hexdigest() key = base64.b64encode(user_key + user_name) if oa.loginurl: self.redirect(oa.loginurl % key) class Logout(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if oa: self.redirect(users.create_logout_url(oa.logouturl)) def main(): Route([ ('/oldauth', Login), ('/oldauth_exit', Logout), ]) if __name__ == '__main__': main()
Create users when they log in
Create users when they log in
Python
mit
argoroots/Entu,argoroots/Entu,argoroots/Entu
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): + + u = User().current() + user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if not oa: oa = OldAuth() oa.site = site oa.put() user_name = user.nickname() user_key = hashlib.md5(user.nickname() + date.today().strftime('%Y-%m-%d') + oa.salt).hexdigest() key = base64.b64encode(user_key + user_name) if oa.loginurl: self.redirect(oa.loginurl % key) class Logout(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if oa: self.redirect(users.create_logout_url(oa.logouturl)) def main(): Route([ ('/oldauth', Login), ('/oldauth_exit', Logout), ]) if __name__ == '__main__': main()
Create users when they log in
## Code Before: import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if not oa: oa = OldAuth() oa.site = site oa.put() user_name = user.nickname() user_key = hashlib.md5(user.nickname() + date.today().strftime('%Y-%m-%d') + oa.salt).hexdigest() key = base64.b64encode(user_key + user_name) if oa.loginurl: self.redirect(oa.loginurl % key) class Logout(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if oa: self.redirect(users.create_logout_url(oa.logouturl)) def main(): Route([ ('/oldauth', Login), ('/oldauth_exit', Logout), ]) if __name__ == '__main__': main() ## Instruction: Create users when they log in ## Code After: import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): u = User().current() user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if not oa: oa = OldAuth() oa.site = site oa.put() user_name = user.nickname() user_key = hashlib.md5(user.nickname() + date.today().strftime('%Y-%m-%d') + oa.salt).hexdigest() key = base64.b64encode(user_key + user_name) if oa.loginurl: self.redirect(oa.loginurl % key) class Logout(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth).filter('site', site).get() if oa: self.redirect(users.create_logout_url(oa.logouturl)) def main(): Route([ ('/oldauth', Login), ('/oldauth_exit', Logout), ]) if __name__ == '__main__': main()
cfabcbe0e729eeb3281c4f4b7d6182a29d35f37e
ixprofile_client/fetchers.py
ixprofile_client/fetchers.py
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import inspect import sys import urllib.request from openid.fetchers import Urllib2Fetcher class SettingsAwareFetcher(Urllib2Fetcher): """ An URL fetcher for python-openid to verify the certificates against SSL_CA_FILE in Django settings. """ @staticmethod def urlopen(*args, **kwargs): """ Provide urlopen with the trusted certificate path. """ # Old versions of urllib2 cannot verify certificates if sys.version_info >= (3, 0) or \ 'cafile' in inspect.getargspec(urllib.request.urlopen).args: from django.conf import settings if hasattr(settings, 'SSL_CA_FILE'): kwargs['cafile'] = settings.SSL_CA_FILE return urllib.request.urlopen(*args, **kwargs)
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import import inspect import sys PY3 = sys.version_info >= (3, 0) # Important: python3-open uses urllib.request, whereas (python2) openid uses # urllib2. You cannot use the compatibility layer here. if PY3: from urllib.request import urlopen else: from urllib2 import urlopen from openid.fetchers import Urllib2Fetcher class SettingsAwareFetcher(Urllib2Fetcher): """ An URL fetcher for python-openid to verify the certificates against SSL_CA_FILE in Django settings. """ @staticmethod def urlopen(*args, **kwargs): """ Provide urlopen with the trusted certificate path. """ # Old versions of urllib2 cannot verify certificates if PY3 or 'cafile' in inspect.getargspec(urlopen).args: from django.conf import settings if hasattr(settings, 'SSL_CA_FILE'): kwargs['cafile'] = settings.SSL_CA_FILE return urlopen(*args, **kwargs)
Use the correct urllib for the openid we're using
Use the correct urllib for the openid we're using
Python
mit
infoxchange/ixprofile-client,infoxchange/ixprofile-client
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import - from future import standard_library - standard_library.install_aliases() import inspect import sys - import urllib.request + + PY3 = sys.version_info >= (3, 0) + + # Important: python3-open uses urllib.request, whereas (python2) openid uses + # urllib2. You cannot use the compatibility layer here. + if PY3: + from urllib.request import urlopen + else: + from urllib2 import urlopen from openid.fetchers import Urllib2Fetcher class SettingsAwareFetcher(Urllib2Fetcher): """ An URL fetcher for python-openid to verify the certificates against SSL_CA_FILE in Django settings. """ @staticmethod def urlopen(*args, **kwargs): """ Provide urlopen with the trusted certificate path. """ # Old versions of urllib2 cannot verify certificates - if sys.version_info >= (3, 0) or \ - 'cafile' in inspect.getargspec(urllib.request.urlopen).args: + if PY3 or 'cafile' in inspect.getargspec(urlopen).args: from django.conf import settings if hasattr(settings, 'SSL_CA_FILE'): kwargs['cafile'] = settings.SSL_CA_FILE - return urllib.request.urlopen(*args, **kwargs) + return urlopen(*args, **kwargs)
Use the correct urllib for the openid we're using
## Code Before: from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import inspect import sys import urllib.request from openid.fetchers import Urllib2Fetcher class SettingsAwareFetcher(Urllib2Fetcher): """ An URL fetcher for python-openid to verify the certificates against SSL_CA_FILE in Django settings. """ @staticmethod def urlopen(*args, **kwargs): """ Provide urlopen with the trusted certificate path. """ # Old versions of urllib2 cannot verify certificates if sys.version_info >= (3, 0) or \ 'cafile' in inspect.getargspec(urllib.request.urlopen).args: from django.conf import settings if hasattr(settings, 'SSL_CA_FILE'): kwargs['cafile'] = settings.SSL_CA_FILE return urllib.request.urlopen(*args, **kwargs) ## Instruction: Use the correct urllib for the openid we're using ## Code After: from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import import inspect import sys PY3 = sys.version_info >= (3, 0) # Important: python3-open uses urllib.request, whereas (python2) openid uses # urllib2. You cannot use the compatibility layer here. if PY3: from urllib.request import urlopen else: from urllib2 import urlopen from openid.fetchers import Urllib2Fetcher class SettingsAwareFetcher(Urllib2Fetcher): """ An URL fetcher for python-openid to verify the certificates against SSL_CA_FILE in Django settings. """ @staticmethod def urlopen(*args, **kwargs): """ Provide urlopen with the trusted certificate path. """ # Old versions of urllib2 cannot verify certificates if PY3 or 'cafile' in inspect.getargspec(urlopen).args: from django.conf import settings if hasattr(settings, 'SSL_CA_FILE'): kwargs['cafile'] = settings.SSL_CA_FILE return urlopen(*args, **kwargs)
72d119ef80c4c84ae3be65c93795832a7250fc51
run.py
run.py
import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load(path)) # Generate the model embedding_model, siamese_model = model.make_mlp_models(a.shape[1], embedding_dropout=0.2) optimizer = optimizers.SGD(lr=0.00001, momentum=0.9, nesterov=True) # optimizer = optimizers.Adam(lr=0.0001) siamese_model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) print(a.shape) print(a[:10]) trace = siamese_model.fit([a, b], y, validation_split=0.2, epochs=30, batch_size=16) print(trace.history['acc'][-1]) print(trace.history['val_acc'][-1])
import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load(path)) # Generate the model embedding_model, siamese_model = model.make_linear_models(a.shape[1]) optimizer = optimizers.SGD(lr=0.00001, momentum=0.9, nesterov=True) # optimizer = optimizers.Adam(lr=0.0001) siamese_model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) print("data shapes:") print(a.shape) print(b.shape) print(y.shape) trace = siamese_model.fit([a, b], y, validation_split=0.2, epochs=30, batch_size=16, shuffle=True) print(trace.history['acc'][-1]) print(trace.history['val_acc'][-1])
Use linear models by default
Use linear models by default
Python
mit
ogrisel/brain2vec
import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load(path)) # Generate the model - embedding_model, siamese_model = model.make_mlp_models(a.shape[1], embedding_dropout=0.2) + embedding_model, siamese_model = model.make_linear_models(a.shape[1]) optimizer = optimizers.SGD(lr=0.00001, momentum=0.9, nesterov=True) # optimizer = optimizers.Adam(lr=0.0001) siamese_model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) + print("data shapes:") print(a.shape) - print(a[:10]) + print(b.shape) + print(y.shape) trace = siamese_model.fit([a, b], y, validation_split=0.2, epochs=30, - batch_size=16) + batch_size=16, shuffle=True) print(trace.history['acc'][-1]) print(trace.history['val_acc'][-1])
Use linear models by default
## Code Before: import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load(path)) # Generate the model embedding_model, siamese_model = model.make_mlp_models(a.shape[1], embedding_dropout=0.2) optimizer = optimizers.SGD(lr=0.00001, momentum=0.9, nesterov=True) # optimizer = optimizers.Adam(lr=0.0001) siamese_model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) print(a.shape) print(a[:10]) trace = siamese_model.fit([a, b], y, validation_split=0.2, epochs=30, batch_size=16) print(trace.history['acc'][-1]) print(trace.history['val_acc'][-1]) ## Instruction: Use linear models by default ## Code After: import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load(path)) # Generate the model embedding_model, siamese_model = model.make_linear_models(a.shape[1]) optimizer = optimizers.SGD(lr=0.00001, momentum=0.9, nesterov=True) # optimizer = optimizers.Adam(lr=0.0001) siamese_model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=['accuracy']) print("data shapes:") print(a.shape) print(b.shape) print(y.shape) trace = siamese_model.fit([a, b], y, validation_split=0.2, epochs=30, batch_size=16, shuffle=True) print(trace.history['acc'][-1]) print(trace.history['val_acc'][-1])
0fb5a8b5caa99b82845712703bf53f2348227f78
examples/string_expansion.py
examples/string_expansion.py
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) print() if __name__ == '__main__': filename = get_path_for('../tests/data/string_variables.bib') entries, strings = bibpy.read_file(filename, format='relaxed')[:2] print("* String entries:") print_entries(strings) print("* Without string expansion:") print_entries(entries) # Expand string variables in-place bibpy.expand_strings(entries, strings, ignore_duplicates=False) print("* With string expansion:") print_entries(entries) # Unexpand string variables in-place bibpy.unexpand_strings(entries, strings, ignore_duplicates=False) print("* And without string expansion again:") print_entries(entries)
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) print() if __name__ == '__main__': filename = get_path_for('../tests/data/string_variables.bib') result = bibpy.read_file(filename, format='relaxed') entries, strings = result.entries, result.strings print("* String entries:") print_entries(strings) print("* Without string expansion:") print_entries(entries) # Expand string variables in-place bibpy.expand_strings(entries, strings, ignore_duplicates=False) print("* With string expansion:") print_entries(entries) # Unexpand string variables in-place bibpy.unexpand_strings(entries, strings, ignore_duplicates=False) print("* And without string expansion again:") print_entries(entries)
Fix ordering in string expansion example
Fix ordering in string expansion example
Python
mit
MisanthropicBit/bibpy,MisanthropicBit/bibpy
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) print() if __name__ == '__main__': filename = get_path_for('../tests/data/string_variables.bib') - entries, strings = bibpy.read_file(filename, format='relaxed')[:2] + result = bibpy.read_file(filename, format='relaxed') + entries, strings = result.entries, result.strings print("* String entries:") print_entries(strings) print("* Without string expansion:") print_entries(entries) # Expand string variables in-place bibpy.expand_strings(entries, strings, ignore_duplicates=False) print("* With string expansion:") print_entries(entries) # Unexpand string variables in-place bibpy.unexpand_strings(entries, strings, ignore_duplicates=False) print("* And without string expansion again:") print_entries(entries)
Fix ordering in string expansion example
## Code Before: """Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) print() if __name__ == '__main__': filename = get_path_for('../tests/data/string_variables.bib') entries, strings = bibpy.read_file(filename, format='relaxed')[:2] print("* String entries:") print_entries(strings) print("* Without string expansion:") print_entries(entries) # Expand string variables in-place bibpy.expand_strings(entries, strings, ignore_duplicates=False) print("* With string expansion:") print_entries(entries) # Unexpand string variables in-place bibpy.unexpand_strings(entries, strings, ignore_duplicates=False) print("* And without string expansion again:") print_entries(entries) ## Instruction: Fix ordering in string expansion example ## Code After: """Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) print() if __name__ == '__main__': filename = get_path_for('../tests/data/string_variables.bib') result = bibpy.read_file(filename, format='relaxed') entries, strings = result.entries, result.strings print("* String entries:") print_entries(strings) print("* Without string expansion:") print_entries(entries) # Expand string variables in-place bibpy.expand_strings(entries, strings, ignore_duplicates=False) print("* With string expansion:") print_entries(entries) # Unexpand string variables in-place bibpy.unexpand_strings(entries, strings, ignore_duplicates=False) print("* And without string expansion again:") print_entries(entries)
844aff45eb1804b461460368f97af4f73a6b62f0
data_structures/union_find/weighted_quick_union.py
data_structures/union_find/weighted_quick_union.py
class WeightedQuickUnion(object): def __init__(self): self.id = [] self.weight = [] def find(self, val): p = val while self.id[p] != p: p = self.id[p] return self.id[p] def union(self, p, q): p_root = self.find(p) q_root = self.find(q) if p_root == q_root: return self.id[q_root] = p_root def is_connected(self, p, q): return self.find(p) == self.find(q)
class WeightedQuickUnion(object): def __init__(self, data=None): self.id = data self.weight = [1] * len(data) self.count = len(data) def count(self): return self.count def find(self, val): p = val while self.id[p] != p: p = self.id[p] return p def union(self, p, q): p_root = self.find(p) q_root = self.find(q) if p_root == q_root: return self.id[q_root] = p_root self.count -= 1 def is_connected(self, p, q): return self.find(p) == self.find(q)
Fix quick union functions issue
Fix quick union functions issue Missing counter Find function should return position of element Decrement counter in union
Python
mit
hongta/practice-python,hongta/practice-python
class WeightedQuickUnion(object): - def __init__(self): + def __init__(self, data=None): - self.id = [] + self.id = data - self.weight = [] + self.weight = [1] * len(data) + self.count = len(data) + + def count(self): + return self.count def find(self, val): p = val while self.id[p] != p: p = self.id[p] - return self.id[p] + return p def union(self, p, q): p_root = self.find(p) q_root = self.find(q) if p_root == q_root: return self.id[q_root] = p_root + self.count -= 1 def is_connected(self, p, q): return self.find(p) == self.find(q)
Fix quick union functions issue
## Code Before: class WeightedQuickUnion(object): def __init__(self): self.id = [] self.weight = [] def find(self, val): p = val while self.id[p] != p: p = self.id[p] return self.id[p] def union(self, p, q): p_root = self.find(p) q_root = self.find(q) if p_root == q_root: return self.id[q_root] = p_root def is_connected(self, p, q): return self.find(p) == self.find(q) ## Instruction: Fix quick union functions issue ## Code After: class WeightedQuickUnion(object): def __init__(self, data=None): self.id = data self.weight = [1] * len(data) self.count = len(data) def count(self): return self.count def find(self, val): p = val while self.id[p] != p: p = self.id[p] return p def union(self, p, q): p_root = self.find(p) q_root = self.find(q) if p_root == q_root: return self.id[q_root] = p_root self.count -= 1 def is_connected(self, p, q): return self.find(p) == self.find(q)
bddab649c6684f09870983dca97c39eb30b62c06
djangobotcfg/status.py
djangobotcfg/status.py
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth # authz = Authz( # forceBuild=True, # forceAllBuilds=True, # pingBuilder=True, # gracefulShutdown=True, # stopBuild=True, # stopAllBuilds=True, # cancelPendingBuild=True, # cleanShutdown=True, # ) def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), words.IRC( host = 'irc.freenode.net', channels = ['#revsys'], nick = 'djangobuilds', notify_events = { 'successToFailure': True, 'failureToSuccess': True, } ) ]
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), ]
Remove the IRC bot for now, and also the commented-out code.
Remove the IRC bot for now, and also the commented-out code.
Python
bsd-3-clause
hochanh/django-buildmaster,jacobian-archive/django-buildmaster
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth - - # authz = Authz( - # forceBuild=True, - # forceAllBuilds=True, - # pingBuilder=True, - # gracefulShutdown=True, - # stopBuild=True, - # stopAllBuilds=True, - # cancelPendingBuild=True, - # cleanShutdown=True, - # ) def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), - - words.IRC( - host = 'irc.freenode.net', - channels = ['#revsys'], - nick = 'djangobuilds', - notify_events = { - 'successToFailure': True, - 'failureToSuccess': True, - } - ) ]
Remove the IRC bot for now, and also the commented-out code.
## Code Before: from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth # authz = Authz( # forceBuild=True, # forceAllBuilds=True, # pingBuilder=True, # gracefulShutdown=True, # stopBuild=True, # stopAllBuilds=True, # cancelPendingBuild=True, # cleanShutdown=True, # ) def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), words.IRC( host = 'irc.freenode.net', channels = ['#revsys'], nick = 'djangobuilds', notify_events = { 'successToFailure': True, 'failureToSuccess': True, } ) ] ## Instruction: Remove the IRC bot for now, and also the commented-out code. ## Code After: from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://code.djangoproject.com/changeset/%s', changecommentlink = ( r'\b#(\d+)\b', r'http://code.djangoproject.com/ticket/\1', r'Ticket \g<0>' ) ), ]
6bb63c6133db2155c1985d6bb2827f65d5ae3555
ntm/__init__.py
ntm/__init__.py
from . import controllers from . import heads from . import init from . import memory from . import nonlinearities from . import ntm from . import similarities from . import updates
from . import controllers from . import heads from . import init from . import layers from . import memory from . import nonlinearities from . import similarities from . import updates
Fix import name from ntm to layers
Fix import name from ntm to layers
Python
mit
snipsco/ntm-lasagne
from . import controllers from . import heads from . import init + from . import layers from . import memory from . import nonlinearities - from . import ntm from . import similarities from . import updates
Fix import name from ntm to layers
## Code Before: from . import controllers from . import heads from . import init from . import memory from . import nonlinearities from . import ntm from . import similarities from . import updates ## Instruction: Fix import name from ntm to layers ## Code After: from . import controllers from . import heads from . import init from . import layers from . import memory from . import nonlinearities from . import similarities from . import updates
d7d6819e728edff997c07c6191f882a61d30f219
setup.py
setup.py
from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos, using GPS tracks or manually from a map", url="http://www.grendelman.net/wp/tag/taggert", license="Apache License version 2.0", # package_dir={'taggert': 'taggert'}, packages=['taggert'], scripts=['taggert_run'], package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg']}, data_files=[ ('glib-2.0/schemas', ['com.tinuzz.taggert.gschema.xml']), ('applications', ['taggert.desktop']), ('pixmaps', ['taggert/data/taggert.svg']), ], )
from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos, using GPS tracks or manually from a map", url="http://www.grendelman.net/wp/tag/taggert", license="Apache License version 2.0", # package_dir={'taggert': 'taggert'}, packages=['taggert'], scripts=['taggert_run'], package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg', 'data/gpx.xsd']}, data_files=[ ('glib-2.0/schemas', ['com.tinuzz.taggert.gschema.xml']), ('applications', ['taggert.desktop']), ('pixmaps', ['taggert/data/taggert.svg']), ], )
Make sure to install gpx.xsd in data directory
Make sure to install gpx.xsd in data directory
Python
apache-2.0
tinuzz/taggert
from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos, using GPS tracks or manually from a map", url="http://www.grendelman.net/wp/tag/taggert", license="Apache License version 2.0", # package_dir={'taggert': 'taggert'}, packages=['taggert'], scripts=['taggert_run'], - package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg']}, + package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg', 'data/gpx.xsd']}, data_files=[ ('glib-2.0/schemas', ['com.tinuzz.taggert.gschema.xml']), ('applications', ['taggert.desktop']), ('pixmaps', ['taggert/data/taggert.svg']), ], )
Make sure to install gpx.xsd in data directory
## Code Before: from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos, using GPS tracks or manually from a map", url="http://www.grendelman.net/wp/tag/taggert", license="Apache License version 2.0", # package_dir={'taggert': 'taggert'}, packages=['taggert'], scripts=['taggert_run'], package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg']}, data_files=[ ('glib-2.0/schemas', ['com.tinuzz.taggert.gschema.xml']), ('applications', ['taggert.desktop']), ('pixmaps', ['taggert/data/taggert.svg']), ], ) ## Instruction: Make sure to install gpx.xsd in data directory ## Code After: from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos, using GPS tracks or manually from a map", url="http://www.grendelman.net/wp/tag/taggert", license="Apache License version 2.0", # package_dir={'taggert': 'taggert'}, packages=['taggert'], scripts=['taggert_run'], package_data={'taggert': ['data/taggert.glade', 'data/taggert.svg', 'data/gpx.xsd']}, data_files=[ ('glib-2.0/schemas', ['com.tinuzz.taggert.gschema.xml']), ('applications', ['taggert.desktop']), ('pixmaps', ['taggert/data/taggert.svg']), ], )
cf30c07be85cf6408c636ffa34f984ed652cd212
setup.py
setup.py
from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ 'tracer', 'harvester', 'simuvex' ], )
from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ 'rex', 'tracer', 'harvester', 'simuvex' ], )
Add rex as a dependency
Add rex as a dependency
Python
bsd-2-clause
mechaphish/colorguard
from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ + 'rex', 'tracer', 'harvester', 'simuvex' ], )
Add rex as a dependency
## Code Before: from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ 'tracer', 'harvester', 'simuvex' ], ) ## Instruction: Add rex as a dependency ## Code After: from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ 'rex', 'tracer', 'harvester', 'simuvex' ], )
c25297735f38d1e2a6ddb6878f919d192f9faedd
GcodeParser.py
GcodeParser.py
"""Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented def box_gcode(min_xy, max_xy): """Take in min/max coordinate tuples, return G0 commands to bound it""" raise NotImplemented def mid_gcode(min_xy, max_xy): """Take in min/max coord tuples, return G0 to go to midpoint""" raise NotImplemented
"""Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented def box_gcode(min_xy, max_xy): """Take in min/max coordinate tuples, return G0 commands to bound it""" gcode = [] gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) gcode.append(GCodeLinearMove(X=max_xy[0], Y=min_xy[1])) gcode.append(GCodeLinearMove(X=max_xy[0], Y=max_xy[1])) gcode.append(GCodeLinearMove(X=min_xy[0], Y=max_xy[1])) gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) # Convert from GCodeLinearMove class to string gcode = [str(line) for line in gcode] return gcode def mid_gcode(min_xy, max_xy): """Take in min/max coord tuples, return G0 to go to midpoint""" raise NotImplemented
ADD function to return box gcode
ADD function to return box gcode
Python
mit
RootAccessHackerspace/k40-laser-scripts,RootAccessHackerspace/k40-laser-scripts
"""Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented def box_gcode(min_xy, max_xy): """Take in min/max coordinate tuples, return G0 commands to bound it""" - raise NotImplemented + gcode = [] + gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) + gcode.append(GCodeLinearMove(X=max_xy[0], Y=min_xy[1])) + gcode.append(GCodeLinearMove(X=max_xy[0], Y=max_xy[1])) + gcode.append(GCodeLinearMove(X=min_xy[0], Y=max_xy[1])) + gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) + # Convert from GCodeLinearMove class to string + gcode = [str(line) for line in gcode] + return gcode def mid_gcode(min_xy, max_xy): """Take in min/max coord tuples, return G0 to go to midpoint""" raise NotImplemented
ADD function to return box gcode
## Code Before: """Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented def box_gcode(min_xy, max_xy): """Take in min/max coordinate tuples, return G0 commands to bound it""" raise NotImplemented def mid_gcode(min_xy, max_xy): """Take in min/max coord tuples, return G0 to go to midpoint""" raise NotImplemented ## Instruction: ADD function to return box gcode ## Code After: """Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented def box_gcode(min_xy, max_xy): """Take in min/max coordinate tuples, return G0 commands to bound it""" gcode = [] gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) gcode.append(GCodeLinearMove(X=max_xy[0], Y=min_xy[1])) gcode.append(GCodeLinearMove(X=max_xy[0], Y=max_xy[1])) gcode.append(GCodeLinearMove(X=min_xy[0], Y=max_xy[1])) gcode.append(GCodeLinearMove(X=min_xy[0], Y=min_xy[1])) # Convert from GCodeLinearMove class to string gcode = [str(line) for line in gcode] return gcode def mid_gcode(min_xy, max_xy): """Take in min/max coord tuples, return G0 to go to midpoint""" raise NotImplemented
b3362c05032b66592b8592ccb94a3ec3f10f815f
project/urls.py
project/urls.py
from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")), ]
from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Add media server to dev server
Add media server to dev server
Python
bsd-2-clause
dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api
from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse + from django.conf import settings + from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")), - ] + ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Add media server to dev server
## Code Before: from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")), ] ## Instruction: Add media server to dev server ## Code After: from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", content_type="text/plain")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
d730eb0c0df2fb6784f7adcce479c4c9588764b9
spacy/ja/__init__.py
spacy/ja/__init__.py
from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): from janome.tokenizer import Tokenizer words = [x.surface for x in Tokenizer().tokenize(text)] return Doc(self.vocab, words=words, spaces=[False]*len(words))
from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): try: from janome.tokenizer import Tokenizer except ImportError: raise ImportError("The Japanese tokenizer requires the Janome library: https://github.com/mocobeta/janome") words = [x.surface for x in Tokenizer().tokenize(text)] return Doc(self.vocab, words=words, spaces=[False]*len(words))
Raise custom ImportError if importing janome fails
Raise custom ImportError if importing janome fails
Python
mit
raphael0202/spaCy,recognai/spaCy,explosion/spaCy,Gregory-Howard/spaCy,recognai/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,honnibal/spaCy,recognai/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,explosion/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,recognai/spaCy,raphael0202/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy
from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): + try: - from janome.tokenizer import Tokenizer + from janome.tokenizer import Tokenizer + except ImportError: + raise ImportError("The Japanese tokenizer requires the Janome library: https://github.com/mocobeta/janome") words = [x.surface for x in Tokenizer().tokenize(text)] return Doc(self.vocab, words=words, spaces=[False]*len(words))
Raise custom ImportError if importing janome fails
## Code Before: from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): from janome.tokenizer import Tokenizer words = [x.surface for x in Tokenizer().tokenize(text)] return Doc(self.vocab, words=words, spaces=[False]*len(words)) ## Instruction: Raise custom ImportError if importing janome fails ## Code After: from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): try: from janome.tokenizer import Tokenizer except ImportError: raise ImportError("The Japanese tokenizer requires the Janome library: https://github.com/mocobeta/janome") words = [x.surface for x in Tokenizer().tokenize(text)] return Doc(self.vocab, words=words, spaces=[False]*len(words))
223872a6f894b429b3784365fe50e139e649d233
chempy/electrochemistry/nernst.py
chempy/electrochemistry/nernst.py
from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant return (R * T) / (charge * F) * math.log(ion_conc_out / ion_conc_in)
from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol backend: module (optional, default: math) module used to calculate log using `log` method, can be substituted with sympy to get symbolic answers Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant return (R * T) / (charge * F) * backend.log(ion_conc_out / ion_conc_in)
Add keyword arg for backend for log
Add keyword arg for backend for log Can be used to switch out math module with other modules, ex. sympy for symbolic answers
Python
bsd-2-clause
bjodah/aqchem,bjodah/aqchem,bjodah/chempy,bjodah/chempy,bjodah/aqchem
from __future__ import (absolute_import, division, print_function) import math - def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None): + def nernst_potential(ion_conc_out, ion_conc_in, charge, T, + constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol + backend: module (optional, default: math) + module used to calculate log using `log` method, can be substituted + with sympy to get symbolic answers Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant - return (R * T) / (charge * F) * math.log(ion_conc_out / ion_conc_in) + return (R * T) / (charge * F) * backend.log(ion_conc_out / ion_conc_in)
Add keyword arg for backend for log
## Code Before: from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant return (R * T) / (charge * F) * math.log(ion_conc_out / ion_conc_in) ## Instruction: Add keyword arg for backend for log ## Code After: from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float with unit Extracellular concentration of ion ion_conc_in: float with unit Intracellular concentration of ion charge: integer Charge of the ion T: float with unit Absolute temperature constants: object (optional, default: None) constant attributes accessed: F - Faraday constant R - Ideal Gas constant units: object (optional, default: None) unit attributes: coulomb, joule, kelvin, mol backend: module (optional, default: math) module used to calculate log using `log` method, can be substituted with sympy to get symbolic answers Returns ------- Membrane potential """ if constants is None: F = 96485.33289 R = 8.3144598 if units is not None: F *= units.coulomb / units.mol R *= units.joule / units.kelvin / units.mol else: F = constants.Faraday_constant R = constants.ideal_gas_constant return (R * T) / (charge * F) * backend.log(ion_conc_out / ion_conc_in)
5ea19da9fdd797963a7b7f1f2fd8f7163200b4bc
easy_maps/conf.py
easy_maps/conf.py
import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information. LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages. GOOGLE_MAPS_API_KEY = None GOOGLE_KEY = None CACHE_LIFETIME = 600 # 10 minutes in seconds class Meta: prefix = 'easy_maps' holder = 'easy_maps.conf.settings' if hasattr(settings, 'EASY_MAPS_GOOGLE_MAPS_API_KEY'): warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information. LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages. GOOGLE_MAPS_API_KEY = None GOOGLE_KEY = None CACHE_LIFETIME = 600 # 10 minutes in seconds class Meta: prefix = 'easy_maps' holder = 'easy_maps.conf.settings' if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None: warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
Python
mit
kmike/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps
import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information. LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages. GOOGLE_MAPS_API_KEY = None GOOGLE_KEY = None CACHE_LIFETIME = 600 # 10 minutes in seconds class Meta: prefix = 'easy_maps' holder = 'easy_maps.conf.settings' - if hasattr(settings, 'EASY_MAPS_GOOGLE_MAPS_API_KEY'): + if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None: warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
## Code Before: import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information. LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages. GOOGLE_MAPS_API_KEY = None GOOGLE_KEY = None CACHE_LIFETIME = 600 # 10 minutes in seconds class Meta: prefix = 'easy_maps' holder = 'easy_maps.conf.settings' if hasattr(settings, 'EASY_MAPS_GOOGLE_MAPS_API_KEY'): warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning) ## Instruction: Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning. ## Code After: import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more information. LANGUAGE = 'en' # See https://developers.google.com/maps/faq#languagesupport for supported languages. GOOGLE_MAPS_API_KEY = None GOOGLE_KEY = None CACHE_LIFETIME = 600 # 10 minutes in seconds class Meta: prefix = 'easy_maps' holder = 'easy_maps.conf.settings' if settings.EASY_MAPS_GOOGLE_MAPS_API_KEY is not None: warnings.warn("EASY_MAPS_GOOGLE_MAPS_API_KEY is deprecated, use EASY_MAPS_GOOGLE_KEY", DeprecationWarning)
2d74b55a0c110a836190af819b55673bce2300a0
gaphor/ui/macosshim.py
gaphor/ui/macosshim.py
try: import gi gi.require_version("GtkosxApplication", "1.0") except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
try: import gi from gi.repository import Gtk if Gtk.get_major_version() == 3: gi.require_version("GtkosxApplication", "1.0") else: raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
Fix macos shim for gtk 4
Fix macos shim for gtk 4
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
try: import gi + from gi.repository import Gtk + if Gtk.get_major_version() == 3: - gi.require_version("GtkosxApplication", "1.0") + gi.require_version("GtkosxApplication", "1.0") + else: + raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
Fix macos shim for gtk 4
## Code Before: try: import gi gi.require_version("GtkosxApplication", "1.0") except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application ) ## Instruction: Fix macos shim for gtk 4 ## Code After: try: import gi from gi.repository import Gtk if Gtk.get_major_version() == 3: gi.require_version("GtkosxApplication", "1.0") else: raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return False app_file_manager = application.get_service("app_file_manager") app_file_manager.load(path) return True def block_termination(macos_app, application): quit = application.quit() return not quit def macos_init(application): macos_app.connect("NSApplicationOpenFile", open_file, application) macos_app.connect( "NSApplicationBlockTermination", block_termination, application )
4a84fe0c774638b7a00d37864b6d634200512f99
tests.py
tests.py
import unittest from stacklogger import srcfile class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
import inspect import unittest from stacklogger import srcfile currentframe = inspect.currentframe class FakeFrames(object): def fake_method(self): return currentframe() @property def fake_property(self): return currentframe() @classmethod def fake_classmethod(cls): return currentframe() @staticmethod def fake_staticmethod(): return currentframe() def fake_function(): return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
Build fake frames for later testing.
Build fake frames for later testing.
Python
isc
whilp/stacklogger
+ import inspect import unittest from stacklogger import srcfile + + currentframe = inspect.currentframe + + class FakeFrames(object): + + def fake_method(self): + return currentframe() + + @property + def fake_property(self): + return currentframe() + + @classmethod + def fake_classmethod(cls): + return currentframe() + + @staticmethod + def fake_staticmethod(): + return currentframe() + + def fake_function(): + return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
Build fake frames for later testing.
## Code Before: import unittest from stacklogger import srcfile class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo")) ## Instruction: Build fake frames for later testing. ## Code After: import inspect import unittest from stacklogger import srcfile currentframe = inspect.currentframe class FakeFrames(object): def fake_method(self): return currentframe() @property def fake_property(self): return currentframe() @classmethod def fake_classmethod(cls): return currentframe() @staticmethod def fake_staticmethod(): return currentframe() def fake_function(): return currentframe() class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self.assertTrue(srcfile("foo").endswith("foo"))
eba6e117c0a13b49219bb60e773f896b274b6601
tests/_support/configs/collection.py
tests/_support/configs/collection.py
from spec import eq_ from invoke import ctask, Collection @ctask def collection(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(collection) ns.configure({'run': {'echo': True}})
from spec import eq_ from invoke import ctask, Collection @ctask def go(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(go) ns.configure({'run': {'echo': True}})
Fix test fixture to match earlier test change
Fix test fixture to match earlier test change
Python
bsd-2-clause
singingwolfboy/invoke,kejbaly2/invoke,tyewang/invoke,frol/invoke,mattrobenolt/invoke,mkusz/invoke,pfmoore/invoke,mkusz/invoke,pyinvoke/invoke,kejbaly2/invoke,pfmoore/invoke,sophacles/invoke,frol/invoke,pyinvoke/invoke,mattrobenolt/invoke
from spec import eq_ from invoke import ctask, Collection @ctask - def collection(c): + def go(c): c.run('false') # Ensures a kaboom if mocking fails - ns = Collection(collection) + ns = Collection(go) ns.configure({'run': {'echo': True}})
Fix test fixture to match earlier test change
## Code Before: from spec import eq_ from invoke import ctask, Collection @ctask def collection(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(collection) ns.configure({'run': {'echo': True}}) ## Instruction: Fix test fixture to match earlier test change ## Code After: from spec import eq_ from invoke import ctask, Collection @ctask def go(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(go) ns.configure({'run': {'echo': True}})
c31c54624d7a46dfd9df96e32d2e07246868aecc
tomviz/python/DefaultITKTransform.py
tomviz/python/DefaultITKTransform.py
def transform_scalars(dataset): """Define this method for Python operators that transform the input array.""" from tomviz import utils import numpy as np import itk # Get the current volume as a numpy array. array = utils.get_array(dataset) # Set up some ITK variables itk_image_type = itk.Image.F3 itk_converter = itk.PyBuffer[itk_image_type] # Read the image into ITK itk_image = itk_converter.GetImageFromArray(array) # ITK filter (I have no idea if this is right) filter = \ itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New() filter.SetInitialNeighborhoodRadius(3) filter.SetMultiplier(3) filter.SetNumberOfIterations(25) filter.SetReplaceValue(255) filter.SetSeed((24,65,37)) filter.SetInput(itk_image) filter.Update() # Get the image back from ITK (result is a numpy image) result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput()) # This is where the transformed data is set, it will display in tomviz. utils.set_array(dataset, result)
import tomviz.operators class DefaultITKTransform(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # Add a try/except around the ITK portion. ITK exceptions are # passed up to the Python layer, so we can at least report what # went wrong with the script, e.g., unsupported image type. try: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
Change the ITK example to use a simpler ITK filter
Change the ITK example to use a simpler ITK filter
Python
bsd-3-clause
cjh1/tomviz,cryos/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,cjh1/tomviz,thewtex/tomviz,thewtex/tomviz,cryos/tomviz,mathturtle/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz
+ import tomviz.operators - def transform_scalars(dataset): - """Define this method for Python operators that - transform the input array.""" - from tomviz import utils - import numpy as np - import itk - # Get the current volume as a numpy array. - array = utils.get_array(dataset) + class DefaultITKTransform(tomviz.operators.CancelableOperator): - # Set up some ITK variables - itk_image_type = itk.Image.F3 - itk_converter = itk.PyBuffer[itk_image_type] - # Read the image into ITK - itk_image = itk_converter.GetImageFromArray(array) + def transform_scalars(self, dataset): + """Define this method for Python operators that transform the input + array. This example uses an ITK filter to add 10 to each voxel value.""" + # Try imports to make sure we have everything that is needed + try: + from tomviz import itkutils + import itk + except Exception as exc: + print("Could not import necessary module(s)") + raise exc - # ITK filter (I have no idea if this is right) - filter = \ - itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New() - filter.SetInitialNeighborhoodRadius(3) - filter.SetMultiplier(3) - filter.SetNumberOfIterations(25) - filter.SetReplaceValue(255) - filter.SetSeed((24,65,37)) - filter.SetInput(itk_image) - filter.Update() - # Get the image back from ITK (result is a numpy image) - result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput()) + self.progress.value = 0 + self.progress.maximum = 100 - # This is where the transformed data is set, it will display in tomviz. - utils.set_array(dataset, result) + # Add a try/except around the ITK portion. ITK exceptions are + # passed up to the Python layer, so we can at least report what + # went wrong with the script, e.g., unsupported image type. + try: + self.progress.value = 0 + self.progress.message = "Converting data to ITK image" + # Get the ITK image + itk_image = itkutils.convert_vtk_to_itk_image(dataset) + itk_input_image_type = type(itk_image) + self.progress.value = 30 + self.progress.message = "Running filter" + + # ITK filter + filter = itk.AddImageFilter[itk_input_image_type, # Input 1 + itk_input_image_type, # Input 2 + itk_input_image_type].New() # Output + filter.SetInput1(itk_image) + filter.SetConstant2(10) + itkutils.observe_filter_progress(self, filter, 30, 70) + + try: + filter.Update() + except RuntimeError: # Exception thrown when ITK filter is aborted + return + + self.progress.message = "Saving results" + + itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) + + self.progress.value = 100 + except Exception as exc: + print("Problem encountered while running %s" % + self.__class__.__name__) + raise exc +
Change the ITK example to use a simpler ITK filter
## Code Before: def transform_scalars(dataset): """Define this method for Python operators that transform the input array.""" from tomviz import utils import numpy as np import itk # Get the current volume as a numpy array. array = utils.get_array(dataset) # Set up some ITK variables itk_image_type = itk.Image.F3 itk_converter = itk.PyBuffer[itk_image_type] # Read the image into ITK itk_image = itk_converter.GetImageFromArray(array) # ITK filter (I have no idea if this is right) filter = \ itk.ConfidenceConnectedImageFilter[itk_image_type,itk.Image.SS3].New() filter.SetInitialNeighborhoodRadius(3) filter.SetMultiplier(3) filter.SetNumberOfIterations(25) filter.SetReplaceValue(255) filter.SetSeed((24,65,37)) filter.SetInput(itk_image) filter.Update() # Get the image back from ITK (result is a numpy image) result = itk.PyBuffer[itk.Image.SS3].GetArrayFromImage(filter.GetOutput()) # This is where the transformed data is set, it will display in tomviz. utils.set_array(dataset, result) ## Instruction: Change the ITK example to use a simpler ITK filter ## Code After: import tomviz.operators class DefaultITKTransform(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make sure we have everything that is needed try: from tomviz import itkutils import itk except Exception as exc: print("Could not import necessary module(s)") raise exc self.progress.value = 0 self.progress.maximum = 100 # Add a try/except around the ITK portion. ITK exceptions are # passed up to the Python layer, so we can at least report what # went wrong with the script, e.g., unsupported image type. try: self.progress.value = 0 self.progress.message = "Converting data to ITK image" # Get the ITK image itk_image = itkutils.convert_vtk_to_itk_image(dataset) itk_input_image_type = type(itk_image) self.progress.value = 30 self.progress.message = "Running filter" # ITK filter filter = itk.AddImageFilter[itk_input_image_type, # Input 1 itk_input_image_type, # Input 2 itk_input_image_type].New() # Output filter.SetInput1(itk_image) filter.SetConstant2(10) itkutils.observe_filter_progress(self, filter, 30, 70) try: filter.Update() except RuntimeError: # Exception thrown when ITK filter is aborted return self.progress.message = "Saving results" itkutils.set_array_from_itk_image(dataset, filter.GetOutput()) self.progress.value = 100 except Exception as exc: print("Problem encountered while running %s" % self.__class__.__name__) raise exc
8d8b122ecbb306bb53de4ee350104e7627e8b362
app/app/__init__.py
app/app/__init__.py
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('index', '/') config.add_route('request_scene', '/request/{scene_id}') config.add_route('done', '/done') config.add_route('scene_status', '/scene/{scene_id}') config.add_route('ajax', '/ajax') config.scan() return config.make_wsgi_app()
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('index', '/') config.add_route('request_scene', '/request/{scene_id}') config.add_route('request_preview', '/request_p/{scene_id}') config.add_route('done', '/done') config.add_route('scene_status', '/scene/{scene_id}') config.add_route('ajax', '/ajax') config.scan() return config.make_wsgi_app()
Add route for preview request
Add route for preview request
Python
mit
recombinators/snapsat,recombinators/snapsat,recombinators/snapsat
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('index', '/') config.add_route('request_scene', '/request/{scene_id}') + config.add_route('request_preview', '/request_p/{scene_id}') config.add_route('done', '/done') config.add_route('scene_status', '/scene/{scene_id}') config.add_route('ajax', '/ajax') config.scan() return config.make_wsgi_app()
Add route for preview request
## Code Before: import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('index', '/') config.add_route('request_scene', '/request/{scene_id}') config.add_route('done', '/done') config.add_route('scene_status', '/scene/{scene_id}') config.add_route('ajax', '/ajax') config.scan() return config.make_wsgi_app() ## Instruction: Add route for preview request ## Code After: import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('index', '/') config.add_route('request_scene', '/request/{scene_id}') config.add_route('request_preview', '/request_p/{scene_id}') config.add_route('done', '/done') config.add_route('scene_status', '/scene/{scene_id}') config.add_route('ajax', '/ajax') config.scan() return config.make_wsgi_app()
0654d962918327e5143fb9250ad344de26e284eb
electrumx_server.py
electrumx_server.py
'''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-9s %(message)-100s ' '%(name)s [%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
'''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-7s %(message)-100s ' '[%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
Remove logger name from logs
Remove logger name from logs
Python
mit
thelazier/electrumx,shsmith/electrumx,shsmith/electrumx,erasmospunk/electrumx,erasmospunk/electrumx,thelazier/electrumx
'''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, - format='%(asctime)s %(levelname)-9s %(message)-100s ' + format='%(asctime)s %(levelname)-7s %(message)-100s ' - '%(name)s [%(filename)s:%(lineno)d]') + '[%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
Remove logger name from logs
## Code Before: '''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-9s %(message)-100s ' '%(name)s [%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main() ## Instruction: Remove logger name from logs ## Code After: '''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-7s %(message)-100s ' '[%(filename)s:%(lineno)d]') logging.info('ElectrumX server starting') try: controller = Controller(Env()) controller.run() except Exception: traceback.print_exc() logging.critical('ElectrumX server terminated abnormally') else: logging.info('ElectrumX server terminated normally') if __name__ == '__main__': main()
a910cd19890ef02a08aeb05c8ba450b2c59f0352
monitoring/nagios/plugin/__init__.py
monitoring/nagios/plugin/__init__.py
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI from monitoring.nagios.plugin.http import NagiosPluginHTTP
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
Python
mit
bigbrozer/monitoring.nagios,bigbrozer/monitoring.nagios
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI + from monitoring.nagios.plugin.http import NagiosPluginHTTP
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
## Code Before: from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI ## Instruction: Make NagiosPluginHTTP available from monitoring.nagios.plugin package. ## Code After: from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI from monitoring.nagios.plugin.http import NagiosPluginHTTP
f794c6ed1f6be231d79ac35759ad76270c3e14e0
brains/mapping/admin.py
brains/mapping/admin.py
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] list_filter = ['suburb'] search_fields = ['name'] readonly_fields = ['x', 'y', 'name', 'building_type', 'suburb'] actions = None def has_add_permission(self, request): return False class ReportAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ('location', ('zombies_only', 'inside'), ('is_ruined', 'is_illuminated', 'has_tree'), ('zombies_present', 'barricade_level'), 'players', ('reported_by', 'origin', 'reported_date') )} ),) readonly_fields = ['players', 'reported_date'] admin.site.register(Location, LocationAdmin) admin.site.register(Report, ReportAdmin)
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] list_filter = ['suburb'] search_fields = ['name'] readonly_fields = ['x', 'y', 'name', 'building_type', 'suburb'] actions = None def has_add_permission(self, request): return False class ReportAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ('location', ('zombies_only', 'inside'), ('is_ruined', 'is_illuminated', 'has_tree'), ('zombies_present', 'barricade_level'), 'players', ('reported_by', 'origin'), 'reported_date', )} ),) readonly_fields = ['location', 'zombies_only', 'inside', 'is_ruined', 'is_illuminated', 'has_tree', 'zombies_present', 'barricade_level', 'players', 'reported_by', 'origin', 'reported_date'] admin.site.register(Location, LocationAdmin) admin.site.register(Report, ReportAdmin)
Set everything on the report read only.
Set everything on the report read only.
Python
bsd-3-clause
crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] list_filter = ['suburb'] search_fields = ['name'] readonly_fields = ['x', 'y', 'name', 'building_type', 'suburb'] actions = None def has_add_permission(self, request): return False class ReportAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ('location', ('zombies_only', 'inside'), ('is_ruined', 'is_illuminated', 'has_tree'), ('zombies_present', 'barricade_level'), 'players', - ('reported_by', 'origin', 'reported_date') + ('reported_by', 'origin'), + 'reported_date', )} ),) - readonly_fields = ['players', 'reported_date'] + + readonly_fields = ['location', 'zombies_only', 'inside', 'is_ruined', + 'is_illuminated', 'has_tree', 'zombies_present', 'barricade_level', + 'players', 'reported_by', 'origin', 'reported_date'] admin.site.register(Location, LocationAdmin) admin.site.register(Report, ReportAdmin)
Set everything on the report read only.
## Code Before: from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] list_filter = ['suburb'] search_fields = ['name'] readonly_fields = ['x', 'y', 'name', 'building_type', 'suburb'] actions = None def has_add_permission(self, request): return False class ReportAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ('location', ('zombies_only', 'inside'), ('is_ruined', 'is_illuminated', 'has_tree'), ('zombies_present', 'barricade_level'), 'players', ('reported_by', 'origin', 'reported_date') )} ),) readonly_fields = ['players', 'reported_date'] admin.site.register(Location, LocationAdmin) admin.site.register(Report, ReportAdmin) ## Instruction: Set everything on the report read only. ## Code After: from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] list_filter = ['suburb'] search_fields = ['name'] readonly_fields = ['x', 'y', 'name', 'building_type', 'suburb'] actions = None def has_add_permission(self, request): return False class ReportAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ('location', ('zombies_only', 'inside'), ('is_ruined', 'is_illuminated', 'has_tree'), ('zombies_present', 'barricade_level'), 'players', ('reported_by', 'origin'), 'reported_date', )} ),) readonly_fields = ['location', 'zombies_only', 'inside', 'is_ruined', 'is_illuminated', 'has_tree', 'zombies_present', 'barricade_level', 'players', 'reported_by', 'origin', 'reported_date'] admin.site.register(Location, LocationAdmin) admin.site.register(Report, ReportAdmin)
e76bd7de6a0eb7f46e9e5ce3cdaec44943b848d2
pagseguro/configs.py
pagseguro/configs.py
class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX CURRENCY = "BRL" HEADERS = { "Content-Type": "application/x-www-form-urlencoded; charset=ISO-8859-1" } REFERENCE_PREFIX = "REF%s" PAYMENT_HOST = "https://pagseguro.uol.com.br" PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s" DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" CHARSET = "UTF-8" # ISO-8859-1 NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX CURRENCY = "BRL" HEADERS = { "Content-Type": "application/x-www-form-urlencoded; charset={}".format(CHARSET) } REFERENCE_PREFIX = "REF%s" PAYMENT_HOST = "https://pagseguro.uol.com.br" PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s" DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
Fix charset default to UTF-8
Fix charset default to UTF-8
Python
mit
vintasoftware/python-pagseguro,rochacbruno/python-pagseguro,rgcarrasqueira/python-pagseguro
class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" + CHARSET = "UTF-8" # ISO-8859-1 NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX CURRENCY = "BRL" HEADERS = { - "Content-Type": "application/x-www-form-urlencoded; charset=ISO-8859-1" + "Content-Type": "application/x-www-form-urlencoded; charset={}".format(CHARSET) } REFERENCE_PREFIX = "REF%s" PAYMENT_HOST = "https://pagseguro.uol.com.br" PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s" DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
Fix charset default to UTF-8
## Code Before: class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX CURRENCY = "BRL" HEADERS = { "Content-Type": "application/x-www-form-urlencoded; charset=ISO-8859-1" } REFERENCE_PREFIX = "REF%s" PAYMENT_HOST = "https://pagseguro.uol.com.br" PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s" DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S' ## Instruction: Fix charset default to UTF-8 ## Code After: class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" CHARSET = "UTF-8" # ISO-8859-1 NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIFICATION_URL = BASE_URL + NOTIFICATION_SUFFIX TRANSACTION_URL = BASE_URL + TRANSACTION_SUFFIX CURRENCY = "BRL" HEADERS = { "Content-Type": "application/x-www-form-urlencoded; charset={}".format(CHARSET) } REFERENCE_PREFIX = "REF%s" PAYMENT_HOST = "https://pagseguro.uol.com.br" PAYMENT_URL = PAYMENT_HOST + CHECKOUT_SUFFIX + "/payment.html?code=%s" DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S'
08461a2f61b5a5981a6da9f6ef91a362eed92bfd
pycroft/__init__.py
pycroft/__init__.py
import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = (pkgutil.get_data(self._package, self._resource) or pkgutil.get_data(self._package, self._resource+".default")) if data is None: raise Exception( "Could not load config file {1} " "from package {0}".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception("Config must be a JSON object!") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception("It is not possible to set configuration entries!") config = Config()
import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = None try: data = pkgutil.get_data(self._package, self._resource) except IOError: data = pkgutil.get_data(self._package, self._resource+".default") if data is None: raise Exception( "Could not load config file {1} " "from package {0}".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception("Config must be a JSON object!") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception("It is not possible to set configuration entries!") config = Config()
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
Python
apache-2.0
lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft
import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): + data = None + try: - data = (pkgutil.get_data(self._package, self._resource) or + data = pkgutil.get_data(self._package, self._resource) + except IOError: - pkgutil.get_data(self._package, self._resource+".default")) + data = pkgutil.get_data(self._package, self._resource+".default") if data is None: raise Exception( "Could not load config file {1} " "from package {0}".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception("Config must be a JSON object!") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception("It is not possible to set configuration entries!") config = Config()
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
## Code Before: import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = (pkgutil.get_data(self._package, self._resource) or pkgutil.get_data(self._package, self._resource+".default")) if data is None: raise Exception( "Could not load config file {1} " "from package {0}".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception("Config must be a JSON object!") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception("It is not possible to set configuration entries!") config = Config() ## Instruction: Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561) ## Code After: import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = None try: data = pkgutil.get_data(self._package, self._resource) except IOError: data = pkgutil.get_data(self._package, self._resource+".default") if data is None: raise Exception( "Could not load config file {1} " "from package {0}".format(self._package, self._resource) ) self._config_data = json.loads(data) if not isinstance(self._config_data, collections.Mapping): raise Exception("Config must be a JSON object!") def __getitem__(self, key): if self._config_data is None: self.load() return self._config_data[key] def __setitem__(self, key, value): raise Exception("It is not possible to set configuration entries!") config = Config()
92595871f908aa22d353a2490f851da23f3d1f64
gitcd/Config/FilePersonal.py
gitcd/Config/FilePersonal.py
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filename = configFilename def load(self): if not os.path.isfile(self.filename): self.config = self.defaults.load() else: self.config = self.parser.load(self.filename) def write(self): self.parser.write(self.filename, self.config) def getToken(self): return self.config['token'] def setToken(self, token): self.config['token'] = token
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filename = configFilename def load(self): if not os.path.isfile(self.filename): self.config = self.defaults.load() else: self.config = self.parser.load(self.filename) def write(self): self.parser.write(self.filename, self.config) # add .gitcd-personal to .gitignore gitignore = ".gitignore" if not os.path.isfile(gitignore): gitignoreContent = self.filename else: with open(gitignore, "r") as gitignoreFile: gitignoreContent = gitignoreFile.read() # if not yet in gitignore if "\n%s\n" % (self.filename) not in gitignoreContent: # add it gitignoreContent = "%s\n%s\n" % (gitignoreContent, self.filename) with open(gitignore, "w") as gitignoreFile: gitignoreFile.write(gitignoreContent) def getToken(self): return self.config['token'] def setToken(self, token): self.config['token'] = token
Add .gitcd-personal to .gitignore automaticly
Add .gitcd-personal to .gitignore automaticly
Python
apache-2.0
claudio-walser/gitcd,claudio-walser/gitcd
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filename = configFilename def load(self): if not os.path.isfile(self.filename): self.config = self.defaults.load() else: self.config = self.parser.load(self.filename) def write(self): self.parser.write(self.filename, self.config) + # add .gitcd-personal to .gitignore + gitignore = ".gitignore" + if not os.path.isfile(gitignore): + gitignoreContent = self.filename + else: + with open(gitignore, "r") as gitignoreFile: + gitignoreContent = gitignoreFile.read() + # if not yet in gitignore + if "\n%s\n" % (self.filename) not in gitignoreContent: + # add it + gitignoreContent = "%s\n%s\n" % (gitignoreContent, self.filename) + + + with open(gitignore, "w") as gitignoreFile: + gitignoreFile.write(gitignoreContent) + + def getToken(self): return self.config['token'] def setToken(self, token): self.config['token'] = token
Add .gitcd-personal to .gitignore automaticly
## Code Before: import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filename = configFilename def load(self): if not os.path.isfile(self.filename): self.config = self.defaults.load() else: self.config = self.parser.load(self.filename) def write(self): self.parser.write(self.filename, self.config) def getToken(self): return self.config['token'] def setToken(self, token): self.config['token'] = token ## Instruction: Add .gitcd-personal to .gitignore automaticly ## Code After: import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filename = configFilename def load(self): if not os.path.isfile(self.filename): self.config = self.defaults.load() else: self.config = self.parser.load(self.filename) def write(self): self.parser.write(self.filename, self.config) # add .gitcd-personal to .gitignore gitignore = ".gitignore" if not os.path.isfile(gitignore): gitignoreContent = self.filename else: with open(gitignore, "r") as gitignoreFile: gitignoreContent = gitignoreFile.read() # if not yet in gitignore if "\n%s\n" % (self.filename) not in gitignoreContent: # add it gitignoreContent = "%s\n%s\n" % (gitignoreContent, self.filename) with open(gitignore, "w") as gitignoreFile: gitignoreFile.write(gitignoreContent) def getToken(self): return self.config['token'] def setToken(self, token): self.config['token'] = token
36da7bdc8402494b5ef3588289739e1696ad6002
docs/_ext/djangodummy/settings.py
docs/_ext/djangodummy/settings.py
STATIC_URL = '/static/'
STATIC_URL = '/static/' # Avoid error for missing the secret key SECRET_KEY = 'docs'
Fix autodoc support with Django 1.5
Fix autodoc support with Django 1.5
Python
apache-2.0
django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents
STATIC_URL = '/static/' + # Avoid error for missing the secret key + SECRET_KEY = 'docs' +
Fix autodoc support with Django 1.5
## Code Before: STATIC_URL = '/static/' ## Instruction: Fix autodoc support with Django 1.5 ## Code After: STATIC_URL = '/static/' # Avoid error for missing the secret key SECRET_KEY = 'docs'
00b5599e574740680e6c08884510ad605294fad2
tests/conftest.py
tests/conftest.py
"""Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.cypher.execute('MATCH (n) DETACH DELETE n') return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
"""Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.delete_all() return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
Use `delete_all` instead of running cypher query
Use `delete_all` instead of running cypher query
Python
mit
wcooley/python-gryaml
"""Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) - graphdb.cypher.execute('MATCH (n) DETACH DELETE n') + graphdb.delete_all() return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
Use `delete_all` instead of running cypher query
## Code Before: """Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.cypher.execute('MATCH (n) DETACH DELETE n') return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env ## Instruction: Use `delete_all` instead of running cypher query ## Code After: """Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Need NEO4J_URI environment variable set') graphdb = gryaml.connect(uri=os.environ['NEO4J_URI']) graphdb.delete_all() return graphdb @pytest.yield_fixture def graphdb_offline(): """Ensure the database is not connected.""" if py2neo_ver < 2: pytest.skip('Offline not supported in py2neo < 2') neo4j_uri_env = os.environ.get('NEO4J_URI', None) if neo4j_uri_env: del os.environ['NEO4J_URI'] old_graphdb = gryaml._py2neo.graphdb gryaml._py2neo.graphdb = None yield gryaml._py2neo.graphdb = old_graphdb if neo4j_uri_env: os.environ['NEO4J_URI'] = neo4j_uri_env
e4fde66624f74c4b0bbfae7c7c11a50884a0a73c
pyfr/readers/base.py
pyfr/readers/base.py
from abc import ABCMeta, abstractmethod import uuid class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['mesh_uuid'] = str(uuid.uuid4()) return mesh
from abc import ABCMeta, abstractmethod import uuid import numpy as np class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S') return mesh
Fix the HDF5 type of mesh_uuid for imported meshes.
Fix the HDF5 type of mesh_uuid for imported meshes.
Python
bsd-3-clause
BrianVermeire/PyFR,Aerojspark/PyFR
from abc import ABCMeta, abstractmethod import uuid + + import numpy as np class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata - mesh['mesh_uuid'] = str(uuid.uuid4()) + mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S') return mesh
Fix the HDF5 type of mesh_uuid for imported meshes.
## Code Before: from abc import ABCMeta, abstractmethod import uuid class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['mesh_uuid'] = str(uuid.uuid4()) return mesh ## Instruction: Fix the HDF5 type of mesh_uuid for imported meshes. ## Code After: from abc import ABCMeta, abstractmethod import uuid import numpy as np class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['mesh_uuid'] = np.array(str(uuid.uuid4()), dtype='S') return mesh
0af3f7ddd1912d18d502ca1795c596397d9cd495
python/triple-sum.py
python/triple-sum.py
def get_num_special_triplets(list_a, list_b, list_c): num_special_triplets = 0 for b in list_b: len_a_candidates = len([a for a in list_a if a <= b]) len_c_candidates = len([c for c in list_c if c <= b]) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_special_triplets if __name__ == '__main__': _ = input().split() list_a = list(set(map(int, input().rstrip().split()))) list_b = list(set(map(int, input().rstrip().split()))) list_c = list(set(map(int, input().rstrip().split()))) num_special_triplets = get_num_special_triplets(list_a, list_b, list_c) print(num_special_triplets)
def get_num_special_triplets(list_a, list_b, list_c): # remove duplicates and sort lists list_a = sorted(set(list_a)) list_b = sorted(set(list_b)) list_c = sorted(set(list_c)) num_special_triplets = 0 for b in list_b: len_a_candidates = num_elements_less_than(b, list_a) len_c_candidates = num_elements_less_than(b, list_c) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_special_triplets def num_elements_less_than(target, sorted_list): for index, candidate in enumerate(sorted_list): if candidate > target: return index return len(sorted_list) if __name__ == '__main__': _ = input().split() list_a = list(map(int, input().rstrip().split())) list_b = list(map(int, input().rstrip().split())) list_c = list(map(int, input().rstrip().split())) num_special_triplets = get_num_special_triplets(list_a, list_b, list_c) print(num_special_triplets)
Sort lists prior to computing len of candidates
Sort lists prior to computing len of candidates
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
def get_num_special_triplets(list_a, list_b, list_c): + # remove duplicates and sort lists + list_a = sorted(set(list_a)) + list_b = sorted(set(list_b)) + list_c = sorted(set(list_c)) + num_special_triplets = 0 for b in list_b: - len_a_candidates = len([a for a in list_a if a <= b]) - len_c_candidates = len([c for c in list_c if c <= b]) + len_a_candidates = num_elements_less_than(b, list_a) + len_c_candidates = num_elements_less_than(b, list_c) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_special_triplets + + def num_elements_less_than(target, sorted_list): + for index, candidate in enumerate(sorted_list): + if candidate > target: + return index + return len(sorted_list) + if __name__ == '__main__': _ = input().split() - list_a = list(set(map(int, input().rstrip().split()))) + list_a = list(map(int, input().rstrip().split())) - list_b = list(set(map(int, input().rstrip().split()))) + list_b = list(map(int, input().rstrip().split())) - list_c = list(set(map(int, input().rstrip().split()))) + list_c = list(map(int, input().rstrip().split())) num_special_triplets = get_num_special_triplets(list_a, list_b, list_c) print(num_special_triplets)
Sort lists prior to computing len of candidates
## Code Before: def get_num_special_triplets(list_a, list_b, list_c): num_special_triplets = 0 for b in list_b: len_a_candidates = len([a for a in list_a if a <= b]) len_c_candidates = len([c for c in list_c if c <= b]) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_special_triplets if __name__ == '__main__': _ = input().split() list_a = list(set(map(int, input().rstrip().split()))) list_b = list(set(map(int, input().rstrip().split()))) list_c = list(set(map(int, input().rstrip().split()))) num_special_triplets = get_num_special_triplets(list_a, list_b, list_c) print(num_special_triplets) ## Instruction: Sort lists prior to computing len of candidates ## Code After: def get_num_special_triplets(list_a, list_b, list_c): # remove duplicates and sort lists list_a = sorted(set(list_a)) list_b = sorted(set(list_b)) list_c = sorted(set(list_c)) num_special_triplets = 0 for b in list_b: len_a_candidates = num_elements_less_than(b, list_a) len_c_candidates = num_elements_less_than(b, list_c) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_special_triplets def num_elements_less_than(target, sorted_list): for index, candidate in enumerate(sorted_list): if candidate > target: return index return len(sorted_list) if __name__ == '__main__': _ = input().split() list_a = list(map(int, input().rstrip().split())) list_b = list(map(int, input().rstrip().split())) list_c = list(map(int, input().rstrip().split())) num_special_triplets = get_num_special_triplets(list_a, list_b, list_c) print(num_special_triplets)
2daee974533d1510a17280cddb5a4dfc147338fa
tests/level/test_map.py
tests/level/test_map.py
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4)) def test_paths_around_wall(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) for x in range(1, 5): level_map[x][1].blocks = True self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)], level_map.a_star_path(4, 0, 4, 2))
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4)) def test_paths_around_wall(self): level_map = LevelMap([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) for x in range(1, 5): level_map[x][1].blocks = True self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)], level_map.a_star_path(4, 0, 4, 2)) def tests_force_pathable_endpoint_parameter(self): level_map = LevelMap([[LevelTile(False, False)], [LevelTile(True, True)]]) self.assertEqual([(1, 0)], level_map.a_star_path(0, 0, 1, 0, True)) self.assertEqual([], level_map.a_star_path(0, 0, 1, 0, False))
Add test for force_pathable_endpoint pathfind param
Add test for force_pathable_endpoint pathfind param This parameter is intended to allow pathing to adjacent squares of an unpassable square. This is necessary because if you want to pathfind to a monster which blocks a square, you don't want to actually go *onto* the square, you just want to go next to it, presumably so you can hit it.
Python
mit
MoyTW/RL_Arena_Experiment
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): - level_map = LevelMap() - level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) + level_map = LevelMap([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4)) def test_paths_around_wall(self): - level_map = LevelMap() - level_map.set_map([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) + level_map = LevelMap([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) for x in range(1, 5): level_map[x][1].blocks = True self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)], level_map.a_star_path(4, 0, 4, 2)) + def tests_force_pathable_endpoint_parameter(self): + level_map = LevelMap([[LevelTile(False, False)], [LevelTile(True, True)]]) + + self.assertEqual([(1, 0)], level_map.a_star_path(0, 0, 1, 0, True)) + self.assertEqual([], level_map.a_star_path(0, 0, 1, 0, False)) +
Add test for force_pathable_endpoint pathfind param
## Code Before: import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4)) def test_paths_around_wall(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) for x in range(1, 5): level_map[x][1].blocks = True self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)], level_map.a_star_path(4, 0, 4, 2)) ## Instruction: Add test for force_pathable_endpoint pathfind param ## Code After: import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0, 4, 4)) def test_paths_around_wall(self): level_map = LevelMap([[LevelTile() for _ in range(0, 3)] for _ in range(0, 5)]) for x in range(1, 5): level_map[x][1].blocks = True self.assertEqual([(3, 0), (2, 0), (1, 0), (0, 1), (1, 2), (2, 2), (3, 2), (4, 2)], level_map.a_star_path(4, 0, 4, 2)) def tests_force_pathable_endpoint_parameter(self): level_map = LevelMap([[LevelTile(False, False)], [LevelTile(True, True)]]) self.assertEqual([(1, 0)], level_map.a_star_path(0, 0, 1, 0, True)) self.assertEqual([], level_map.a_star_path(0, 0, 1, 0, False))
822cc689ce44b1c43ac118b2a13c6d0024d2e194
tests/raw_text_tests.py
tests/raw_text_tests.py
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def raw_text_of_text_element_is_value(): assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello"))) @istest def raw_text_of_paragraph_is_terminated_with_newlines(): paragraph = documents.paragraph(children=[documents.Text("Hello")]) assert_equal("Hello\n\n", extract_raw_text_from_element(paragraph)) @istest def non_text_element_without_children_has_no_raw_text(): tab = documents.Tab() assert not hasattr(tab, "children") assert_equal("", extract_raw_text_from_element(documents.Tab()))
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def text_element_is_converted_to_text_content(): element = documents.Text("Hello.") result = extract_raw_text_from_element(element) assert_equal("Hello.", result) @istest def paragraphs_are_terminated_with_newlines(): element = documents.paragraph( children=[ documents.Text("Hello "), documents.Text("world."), ], ) result = extract_raw_text_from_element(element) assert_equal("Hello world.\n\n", result) @istest def children_are_recursively_converted_to_text(): element = documents.document([ documents.paragraph( [ documents.text("Hello "), documents.text("world.") ], {} ) ]) result = extract_raw_text_from_element(element) assert_equal("Hello world.\n\n", result) @istest def non_text_element_without_children_is_converted_to_empty_string(): element = documents.line_break assert not hasattr(element, "children") result = extract_raw_text_from_element(element) assert_equal("", result)
Make raw text tests consistent with mammoth.js
Make raw text tests consistent with mammoth.js
Python
bsd-2-clause
mwilliamson/python-mammoth
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest - def raw_text_of_text_element_is_value(): - assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello"))) + def text_element_is_converted_to_text_content(): + element = documents.Text("Hello.") + + result = extract_raw_text_from_element(element) + + assert_equal("Hello.", result) @istest - def raw_text_of_paragraph_is_terminated_with_newlines(): + def paragraphs_are_terminated_with_newlines(): - paragraph = documents.paragraph(children=[documents.Text("Hello")]) - assert_equal("Hello\n\n", extract_raw_text_from_element(paragraph)) + element = documents.paragraph( + children=[ + documents.Text("Hello "), + documents.Text("world."), + ], + ) + + result = extract_raw_text_from_element(element) + + assert_equal("Hello world.\n\n", result) @istest - def non_text_element_without_children_has_no_raw_text(): - tab = documents.Tab() - assert not hasattr(tab, "children") - assert_equal("", extract_raw_text_from_element(documents.Tab())) + def children_are_recursively_converted_to_text(): + element = documents.document([ + documents.paragraph( + [ + documents.text("Hello "), + documents.text("world.") + ], + {} + ) + ]) + result = extract_raw_text_from_element(element) + + assert_equal("Hello world.\n\n", result) + + + @istest + def non_text_element_without_children_is_converted_to_empty_string(): + element = documents.line_break + assert not hasattr(element, "children") + + result = extract_raw_text_from_element(element) + + assert_equal("", result) +
Make raw text tests consistent with mammoth.js
## Code Before: from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def raw_text_of_text_element_is_value(): assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello"))) @istest def raw_text_of_paragraph_is_terminated_with_newlines(): paragraph = documents.paragraph(children=[documents.Text("Hello")]) assert_equal("Hello\n\n", extract_raw_text_from_element(paragraph)) @istest def non_text_element_without_children_has_no_raw_text(): tab = documents.Tab() assert not hasattr(tab, "children") assert_equal("", extract_raw_text_from_element(documents.Tab())) ## Instruction: Make raw text tests consistent with mammoth.js ## Code After: from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def text_element_is_converted_to_text_content(): element = documents.Text("Hello.") result = extract_raw_text_from_element(element) assert_equal("Hello.", result) @istest def paragraphs_are_terminated_with_newlines(): element = documents.paragraph( children=[ documents.Text("Hello "), documents.Text("world."), ], ) result = extract_raw_text_from_element(element) assert_equal("Hello world.\n\n", result) @istest def children_are_recursively_converted_to_text(): element = documents.document([ documents.paragraph( [ documents.text("Hello "), documents.text("world.") ], {} ) ]) result = extract_raw_text_from_element(element) assert_equal("Hello world.\n\n", result) @istest def non_text_element_without_children_is_converted_to_empty_string(): element = documents.line_break assert not hasattr(element, "children") result = extract_raw_text_from_element(element) assert_equal("", result)
fd5387f1bb8ac99ed421c61fdff777316a4d3191
tests/test_publisher.py
tests/test_publisher.py
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event @pytest.mark.xfail(reason="Need RabbitMQ fixture") def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
Mark test as xfail so that releases can be cut
Mark test as xfail so that releases can be cut
Python
mit
yougov/mettle,yougov/mettle,yougov/mettle,yougov/mettle
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event + @pytest.mark.xfail(reason="Need RabbitMQ fixture") def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
Mark test as xfail so that releases can be cut
## Code Before: import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', )) ## Instruction: Mark test as xfail so that releases can be cut ## Code After: import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event @pytest.mark.xfail(reason="Need RabbitMQ fixture") def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] chan.exchange_declare(exchange=exchange, type='topic', durable=True) with pytest.raises(ValueError): publish_event(chan, exchange, dict( description=None, tablename='a' * 8000, name="foo", pipeline_names=None, id=15, updated_by='vagrant', ))
53636a17cd50d704b7b4563d0b23a474677051f4
hub/prototype/config.py
hub/prototype/config.py
HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), "some.other.game.tld": (543, "monkeyspam"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
Make sure we give an example for two servers.
Make sure we give an example for two servers.
Python
agpl-3.0
madprof/alpha-hub
HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), + "some.other.game.tld": (543, "monkeyspam"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
Make sure we give an example for two servers.
## Code Before: HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), } ## Instruction: Make sure we give an example for two servers. ## Code After: HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), "some.other.game.tld": (543, "monkeyspam"), } # the other hubs we echo to; note that we don't yet change # the packets in any way, so they'll look like they really # come from us; not good, but we'll need to define a new # packet format for forwarded userinfo strings first, then # we can fix this :-/ HUBS = { "some.hub.server.tld": (84, "anothersecret"), }
d185407ac4caf5648ef4c12eab83fec81c307407
tests/test_trackable.py
tests/test_trackable.py
import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == 'untrackable' assert user.login_count == 2
import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'}) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == '127.0.0.1' assert user.login_count == 2
Add mock X-Forwarded-For header in trackable tests
Add mock X-Forwarded-For header in trackable tests
Python
mit
pawl/flask-security,reustle/flask-security,jonafato/flask-security,asmodehn/flask-security,quokkaproject/flask-security,LeonhardPrintz/flask-security-fork,dommert/flask-security,LeonhardPrintz/flask-security-fork,fuhrysteve/flask-security,CodeSolid/flask-security,simright/flask-security,inveniosoftware/flask-security-fork,x5a/flask-security,mafrosis/flask-security,Samael500/flask-security,dlakata/flask-security,inveniosoftware/flask-security-fork,fuhrysteve/flask-security,inveniosoftware/flask-security-fork,redpandalabs/flask-security,fmerges/flask-security,wjt/flask-security,CodeSolid/flask-security,yingbo/flask-security,asmodehn/flask-security,reustle/flask-security,felix1m/flask-security,themylogin/flask-security,a-pertsev/flask-security,GregoryVigoTorres/flask-security,x5a/flask-security,quokkaproject/flask-security,tatataufik/flask-security,Samael500/flask-security,jonafato/flask-security,mik3cap/private-flask-security,a-pertsev/flask-security,guoqiao/flask-security,themylogin/flask-security,LeonhardPrintz/flask-security-fork,GregoryVigoTorres/flask-security,dommert/flask-security,fmerges/flask-security,yingbo/flask-security,mik3cap/private-flask-security,pawl/flask-security,simright/flask-security,nfvs/flask-security,tatataufik/flask-security,dlakata/flask-security,felix1m/flask-security,covertgeek/flask-security,mafrosis/flask-security,wjt/flask-security,covertgeek/flask-security,mattupstate/flask-security,redpandalabs/flask-security,guoqiao/flask-security,mattupstate/flask-security,nfvs/flask-security
import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) - authenticate(client, email=e) + authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'}) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' - assert user.current_login_ip == 'untrackable' + assert user.current_login_ip == '127.0.0.1' assert user.login_count == 2
Add mock X-Forwarded-For header in trackable tests
## Code Before: import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == 'untrackable' assert user.login_count == 2 ## Instruction: Add mock X-Forwarded-For header in trackable tests ## Code After: import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'}) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == '127.0.0.1' assert user.login_count == 2
3bd9214465547ff6cd0f7ed94edf8dacf10135b5
registration/backends/simple/urls.py
registration/backends/simple/urls.py
from django.conf.urls import include, url from django.views.generic.base import TemplateView from registration.backends.simple.views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( template_name='registration/registration_closed.html'), name='registration_disallowed'), url(r'', include('registration.auth_urls')), ]
from django.conf.urls import include, url from django.views.generic.base import TemplateView from .views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( template_name='registration/registration_closed.html'), name='registration_disallowed'), url(r'', include('registration.auth_urls')), ]
Clean up an import in simple backend URLs.
Clean up an import in simple backend URLs.
Python
bsd-3-clause
dirtycoder/django-registration,ubernostrum/django-registration,myimages/django-registration,tdruez/django-registration,awakeup/django-registration
from django.conf.urls import include, url from django.views.generic.base import TemplateView - from registration.backends.simple.views import RegistrationView + from .views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( template_name='registration/registration_closed.html'), name='registration_disallowed'), url(r'', include('registration.auth_urls')), ]
Clean up an import in simple backend URLs.
## Code Before: from django.conf.urls import include, url from django.views.generic.base import TemplateView from registration.backends.simple.views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( template_name='registration/registration_closed.html'), name='registration_disallowed'), url(r'', include('registration.auth_urls')), ] ## Instruction: Clean up an import in simple backend URLs. ## Code After: from django.conf.urls import include, url from django.views.generic.base import TemplateView from .views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( template_name='registration/registration_closed.html'), name='registration_disallowed'), url(r'', include('registration.auth_urls')), ]
4dfbe6ea079b32644c9086351f911ce1a2b2b0e1
easy_maps/geocode.py
easy_maps/geocode.py
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) return g.geocode(address, exactly_one=False)[0] except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) results = g.geocode(address, exactly_one=False) if results is not None: return results[0] raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
Resolve the 500 error when google send a no results info
Resolve the 500 error when google send a no results info
Python
mit
duixteam/django-easy-maps,kmike/django-easy-maps,Gonzasestopal/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps,Gonzasestopal/django-easy-maps
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError + class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) - return g.geocode(address, exactly_one=False)[0] + results = g.geocode(address, exactly_one=False) + if results is not None: + return results[0] + raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
Resolve the 500 error when google send a no results info
## Code Before: from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) return g.geocode(address, exactly_one=False)[0] except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e) ## Instruction: Resolve the 500 error when google send a no results info ## Code After: from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) results = g.geocode(address, exactly_one=False) if results is not None: return results[0] raise Error('No results found') except (UnboundLocalError, ValueError, GeocoderServiceError) as e: raise Error(e)
25993238cb18212a2b83b2d6b0aa98939d38f192
scripts/lwtnn-split-keras-network.py
scripts/lwtnn-split-keras-network.py
import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', default='architecture.json', help=d) return parser.parse_args() def run(): args = get_args() import keras m = keras.models.load_model(args.model) m.save_weights(args.weight_file_name) with open(args.architecture_file_name,'w') as arch: arch.write(m.to_json(indent=2)) if __name__ == '__main__': run()
import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', default='architecture.json', help=d) return parser.parse_args() def run(): args = get_args() from h5py import File import json m = File(args.model,'r') with File(args.weight_file_name,'w') as w: for name, wt in w.items(): w.copy(wt, name) arch = json.loads(m.attrs['model_config']) with open(args.architecture_file_name,'w') as arch_file: arch_file.write(json.dumps(arch,indent=2)) if __name__ == '__main__': run()
Remove Keras from network splitter
Remove Keras from network splitter Keras isn't as stable as h5py and json. This commit removes the keras dependency from the network splitting function.
Python
mit
lwtnn/lwtnn,lwtnn/lwtnn,lwtnn/lwtnn
import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', default='architecture.json', help=d) return parser.parse_args() def run(): args = get_args() + from h5py import File - import keras + import json - m = keras.models.load_model(args.model) - m.save_weights(args.weight_file_name) + m = File(args.model,'r') + with File(args.weight_file_name,'w') as w: + for name, wt in w.items(): + w.copy(wt, name) + + arch = json.loads(m.attrs['model_config']) - with open(args.architecture_file_name,'w') as arch: + with open(args.architecture_file_name,'w') as arch_file: - arch.write(m.to_json(indent=2)) + arch_file.write(json.dumps(arch,indent=2)) if __name__ == '__main__': run()
Remove Keras from network splitter
## Code Before: import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', default='architecture.json', help=d) return parser.parse_args() def run(): args = get_args() import keras m = keras.models.load_model(args.model) m.save_weights(args.weight_file_name) with open(args.architecture_file_name,'w') as arch: arch.write(m.to_json(indent=2)) if __name__ == '__main__': run() ## Instruction: Remove Keras from network splitter ## Code After: import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', default='architecture.json', help=d) return parser.parse_args() def run(): args = get_args() from h5py import File import json m = File(args.model,'r') with File(args.weight_file_name,'w') as w: for name, wt in w.items(): w.copy(wt, name) arch = json.loads(m.attrs['model_config']) with open(args.architecture_file_name,'w') as arch_file: arch_file.write(json.dumps(arch,indent=2)) if __name__ == '__main__': run()
3916efe4a017fe9e0fb1c5fe09b99f374d7a4060
instana/__init__.py
instana/__init__.py
__author__ = 'Instana Inc.' __copyright__ = 'Copyright 2016 Instana Inc.' __credits__ = ['Pavlo Baron'] __license__ = 'MIT' __version__ = '0.0.1' __maintainer__ = 'Pavlo Baron' __email__ = 'pavlo.baron@instana.com' __all__ = ['sensor', 'tracer']
__author__ = 'Instana Inc.' __copyright__ = 'Copyright 2017 Instana Inc.' __credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo'] __license__ = 'MIT' __version__ = '0.6.6' __maintainer__ = 'Peter Giacomo Lombardo' __email__ = 'peter.lombardo@instana.com' __all__ = ['sensor', 'tracer']
Update module init file; begin version stamping here.
Update module init file; begin version stamping here.
Python
mit
instana/python-sensor,instana/python-sensor
__author__ = 'Instana Inc.' - __copyright__ = 'Copyright 2016 Instana Inc.' + __copyright__ = 'Copyright 2017 Instana Inc.' - __credits__ = ['Pavlo Baron'] + __credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo'] __license__ = 'MIT' - __version__ = '0.0.1' + __version__ = '0.6.6' - __maintainer__ = 'Pavlo Baron' + __maintainer__ = 'Peter Giacomo Lombardo' - __email__ = 'pavlo.baron@instana.com' + __email__ = 'peter.lombardo@instana.com' __all__ = ['sensor', 'tracer']
Update module init file; begin version stamping here.
## Code Before: __author__ = 'Instana Inc.' __copyright__ = 'Copyright 2016 Instana Inc.' __credits__ = ['Pavlo Baron'] __license__ = 'MIT' __version__ = '0.0.1' __maintainer__ = 'Pavlo Baron' __email__ = 'pavlo.baron@instana.com' __all__ = ['sensor', 'tracer'] ## Instruction: Update module init file; begin version stamping here. ## Code After: __author__ = 'Instana Inc.' __copyright__ = 'Copyright 2017 Instana Inc.' __credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo'] __license__ = 'MIT' __version__ = '0.6.6' __maintainer__ = 'Peter Giacomo Lombardo' __email__ = 'peter.lombardo@instana.com' __all__ = ['sensor', 'tracer']
67fd73f8f035ac0e13a64971d9d54662df46a77f
karm/test/__karmutil.py
karm/test/__karmutil.py
import sys import os def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None try: ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise "Only one instance of karm may be running." l = stdout.readline() if not id: raise "No karm instance found. Try running dcop at command-line to verify it works." except: if stdin: stdin.close() if stdout: stdout.close() print sys.exc_info()[0] sys.exit(1) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise "%s: expected '%s', got '%s'" % ( scriptname, goal, actual )
import sys import os class KarmTestError( Exception ): pass def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise KarmTestError( "Only one instance of karm may be running." ) l = stdout.readline() if not id: raise KarmTestError( "No karm instance found. Try running dcop at command-line to verify it works." ) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise KarmTestError( "%s: expected '%s', got '%s'" % ( scriptname, goal, actual ) )
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that.
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that. svn path=/trunk/kdepim/; revision=367066
Python
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
import sys import os + + class KarmTestError( Exception ): pass def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None - try: - ( stdin, stdout ) = os.popen2( "dcop" ) + ( stdin, stdout ) = os.popen2( "dcop" ) + l = stdout.readline() + while l: + if l.startswith( "karm" ): + if not id: id = l + else: raise KarmTestError( "Only one instance of karm may be running." ) l = stdout.readline() - while l: - if l.startswith( "karm" ): - if not id: id = l - else: raise "Only one instance of karm may be running." - l = stdout.readline() - if not id: + if not id: - raise "No karm instance found. Try running dcop at command-line to verify it works." + raise KarmTestError( "No karm instance found. Try running dcop at command-line to verify it works." ) - except: - if stdin: stdin.close() - if stdout: stdout.close() - print sys.exc_info()[0] - sys.exit(1) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) - raise "%s: expected '%s', got '%s'" % ( scriptname, goal, actual ) + raise KarmTestError( "%s: expected '%s', got '%s'" % ( scriptname, goal, actual ) )
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that.
## Code Before: import sys import os def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None try: ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise "Only one instance of karm may be running." l = stdout.readline() if not id: raise "No karm instance found. Try running dcop at command-line to verify it works." except: if stdin: stdin.close() if stdout: stdout.close() print sys.exc_info()[0] sys.exit(1) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise "%s: expected '%s', got '%s'" % ( scriptname, goal, actual ) ## Instruction: Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that. ## Code After: import sys import os class KarmTestError( Exception ): pass def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise KarmTestError( "Only one instance of karm may be running." ) l = stdout.readline() if not id: raise KarmTestError( "No karm instance found. Try running dcop at command-line to verify it works." ) stdin.close() stdout.close() # strip trailing newline return id.strip() def test( goal, actual ): '''Raise exception if goal != actual.''' if goal != actual: path, scriptname = os.path.split( sys.argv[0] ) raise KarmTestError( "%s: expected '%s', got '%s'" % ( scriptname, goal, actual ) )
d237c121955b7249e0e2ab5580d2abc2d19b0f25
noveltorpedo/models.py
noveltorpedo/models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=255) contents = models.TextField(default='') def __str__(self): return self.title
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): authors = models.ManyToManyField(Author) title = models.CharField(max_length=255) contents = models.TextField(default='') def __str__(self): return self.title
Allow a story to have many authors
Allow a story to have many authors
Python
mit
NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): - author = models.ForeignKey(Author, on_delete=models.CASCADE) + authors = models.ManyToManyField(Author) title = models.CharField(max_length=255) contents = models.TextField(default='') def __str__(self): return self.title
Allow a story to have many authors
## Code Before: from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=255) contents = models.TextField(default='') def __str__(self): return self.title ## Instruction: Allow a story to have many authors ## Code After: from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): authors = models.ManyToManyField(Author) title = models.CharField(max_length=255) contents = models.TextField(default='') def __str__(self): return self.title
43905a102092bdd50de1f8997cd19cb617b348b3
tests/cart_tests.py
tests/cart_tests.py
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) if __name__ == '__main__': unittest.main()
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) startAddr = cpu.ReadMemWord(cpu.reset) firstByte = cpu.ReadMemory(startAddr) self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
Use the reset adder from the banks properly
Use the reset adder from the banks properly
Python
bsd-2-clause
pusscat/refNes
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) + startAddr = cpu.ReadMemWord(cpu.reset) + firstByte = cpu.ReadMemory(startAddr) + self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
Use the reset adder from the banks properly
## Code Before: import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) if __name__ == '__main__': unittest.main() ## Instruction: Use the reset adder from the banks properly ## Code After: import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom != None, True) def testRomBanks(self): cpu = MOS6502.CPU() cpu.loadRom("../smb1.nes") self.assertEqual(cpu.rom.numRomBanks, 2) self.assertEqual(cpu.rom.numVromBanks, 1) startAddr = cpu.ReadMemWord(cpu.reset) firstByte = cpu.ReadMemory(startAddr) self.assertEqual(firstByte, 0x78) if __name__ == '__main__': unittest.main()
f0e8999ad139a8da8d3762ee1d318f23928edd9c
tests/modelstest.py
tests/modelstest.py
import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), models.ImageFile(title="i2", sha1="s2"), ]) metadata = models.ImageMetadata(owner="me") files.append(metadata) self.failUnlessEqual(files.toXml(), '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file><metadata><owner>me</owner></metadata></files>') testsuite.main()
import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), models.ImageFile(title="i2", sha1="s2"), ]) self.failUnlessEqual(files.toXml(), '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file></files>') testsuite.main()
Fix test after metadata changes
Fix test after metadata changes
Python
apache-2.0
sassoftware/rpath-repeater
import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), models.ImageFile(title="i2", sha1="s2"), ]) - metadata = models.ImageMetadata(owner="me") - files.append(metadata) self.failUnlessEqual(files.toXml(), - '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file><metadata><owner>me</owner></metadata></files>') + '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file></files>') testsuite.main()
Fix test after metadata changes
## Code Before: import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), models.ImageFile(title="i2", sha1="s2"), ]) metadata = models.ImageMetadata(owner="me") files.append(metadata) self.failUnlessEqual(files.toXml(), '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file><metadata><owner>me</owner></metadata></files>') testsuite.main() ## Instruction: Fix test after metadata changes ## Code After: import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), models.ImageFile(title="i2", sha1="s2"), ]) self.failUnlessEqual(files.toXml(), '<files><file><title>i1</title><size>1</size><sha1>s1</sha1></file><file><title>i2</title><sha1>s2</sha1></file></files>') testsuite.main()
3a5fb18a385ffd0533da94632d917e3c0bcfb051
tests/test_nulls.py
tests/test_nulls.py
from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None correctly reloaded = EventWithNulls.objects.get(pk=event.pk) assert reloaded.recurs is None @pytest.mark.django_db def test_recurs_cannot_be_explicitly_none_if_none_is_disallowed(): with pytest.raises(ValueError): EventWithNoNulls.objects.create(recurs=None)
from recurrence import Recurrence from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None correctly reloaded = EventWithNulls.objects.get(pk=event.pk) assert reloaded.recurs is None @pytest.mark.django_db def test_recurs_cannot_be_explicitly_none_if_none_is_disallowed(): with pytest.raises(ValueError): EventWithNoNulls.objects.create(recurs=None) @pytest.mark.django_db def test_recurs_can_be_empty_even_if_none_is_disallowed(): event = EventWithNoNulls.objects.create(recurs=Recurrence()) assert event.recurs == Recurrence()
Add a test for saving an empty recurrence object
Add a test for saving an empty recurrence object I wasn't sure whether this would fail on models which don't accept null values. Turns out it's allowed, so we should make sure it stays allowed.
Python
bsd-3-clause
linux2400/django-recurrence,linux2400/django-recurrence,django-recurrence/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,django-recurrence/django-recurrence
+ from recurrence import Recurrence from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None correctly reloaded = EventWithNulls.objects.get(pk=event.pk) assert reloaded.recurs is None @pytest.mark.django_db def test_recurs_cannot_be_explicitly_none_if_none_is_disallowed(): with pytest.raises(ValueError): EventWithNoNulls.objects.create(recurs=None) + + @pytest.mark.django_db + def test_recurs_can_be_empty_even_if_none_is_disallowed(): + event = EventWithNoNulls.objects.create(recurs=Recurrence()) + assert event.recurs == Recurrence() +
Add a test for saving an empty recurrence object
## Code Before: from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None correctly reloaded = EventWithNulls.objects.get(pk=event.pk) assert reloaded.recurs is None @pytest.mark.django_db def test_recurs_cannot_be_explicitly_none_if_none_is_disallowed(): with pytest.raises(ValueError): EventWithNoNulls.objects.create(recurs=None) ## Instruction: Add a test for saving an empty recurrence object ## Code After: from recurrence import Recurrence from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None correctly reloaded = EventWithNulls.objects.get(pk=event.pk) assert reloaded.recurs is None @pytest.mark.django_db def test_recurs_cannot_be_explicitly_none_if_none_is_disallowed(): with pytest.raises(ValueError): EventWithNoNulls.objects.create(recurs=None) @pytest.mark.django_db def test_recurs_can_be_empty_even_if_none_is_disallowed(): event = EventWithNoNulls.objects.create(recurs=Recurrence()) assert event.recurs == Recurrence()
d8c1c7da47e2568cecc1fd6dff0fec7661b39125
turbosms/routers.py
turbosms/routers.py
class SMSRouter(object): app_label = 'sms' db_name = 'sms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or \ obj2._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == self.app_label: return False return None
class TurboSMSRouter(object): app_label = 'turbosms' db_name = 'turbosms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or \ obj2._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == self.app_label: return False return None
Fix bug in sms router.
Fix bug in sms router.
Python
isc
pmaigutyak/mp-turbosms
- class SMSRouter(object): + class TurboSMSRouter(object): - app_label = 'sms' + app_label = 'turbosms' - db_name = 'sms' + db_name = 'turbosms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or \ obj2._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == self.app_label: return False return None
Fix bug in sms router.
## Code Before: class SMSRouter(object): app_label = 'sms' db_name = 'sms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or \ obj2._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == self.app_label: return False return None ## Instruction: Fix bug in sms router. ## Code After: class TurboSMSRouter(object): app_label = 'turbosms' db_name = 'turbosms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.app_label or \ obj2._meta.app_label == self.app_label: return False return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == self.app_label: return False return None
5fade4bc26c2637a479a69051cee37a1a859c71a
load_hilma.py
load_hilma.py
import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getroot() notices = list(root.iterfind('WRAPPED_NOTICE')) notices = map(hilma_to_dict, notices) collection.ensure_index('ID', unique=True) for n in notices: # Use the ID as primary key n.update('_id', n['ID']) collection.save(n) def sync_hilma_xml_directory(directory, mongo_uri=None, mongo_db='openhilma'): if mongo_uri is None: client = pymongo.MongoClient() else: client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] collection = db.notices paths = sorted(Path(directory).glob("*.xml")) for fpath in paths: load_hilma_xml(fpath.open(), collection) if __name__ == '__main__': argh.dispatch_command(sync_hilma_xml_directory)
import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getroot() notices = list(root.iterfind('WRAPPED_NOTICE')) notices = map(hilma_to_dict, notices) for n in notices: # Use the ID as primary key n.update({'_id': n['ID']}) collection.save(n) def sync_hilma_xml_directory(directory, mongo_uri=None, mongo_db='openhilma'): if mongo_uri is None: client = pymongo.MongoClient() else: client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] collection = db.notices paths = sorted(Path(directory).glob("*.xml")) for fpath in paths: load_hilma_xml(fpath.open(), collection) if __name__ == '__main__': argh.dispatch_command(sync_hilma_xml_directory)
Use the notice ID as priary key
Use the notice ID as priary key Gentlemen, drop your DBs!
Python
agpl-3.0
jampekka/openhilma
import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getroot() notices = list(root.iterfind('WRAPPED_NOTICE')) notices = map(hilma_to_dict, notices) - collection.ensure_index('ID', unique=True) - for n in notices: # Use the ID as primary key - n.update('_id', n['ID']) + n.update({'_id': n['ID']}) collection.save(n) def sync_hilma_xml_directory(directory, mongo_uri=None, mongo_db='openhilma'): if mongo_uri is None: client = pymongo.MongoClient() else: client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] collection = db.notices paths = sorted(Path(directory).glob("*.xml")) for fpath in paths: load_hilma_xml(fpath.open(), collection) if __name__ == '__main__': argh.dispatch_command(sync_hilma_xml_directory)
Use the notice ID as priary key
## Code Before: import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getroot() notices = list(root.iterfind('WRAPPED_NOTICE')) notices = map(hilma_to_dict, notices) collection.ensure_index('ID', unique=True) for n in notices: # Use the ID as primary key n.update('_id', n['ID']) collection.save(n) def sync_hilma_xml_directory(directory, mongo_uri=None, mongo_db='openhilma'): if mongo_uri is None: client = pymongo.MongoClient() else: client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] collection = db.notices paths = sorted(Path(directory).glob("*.xml")) for fpath in paths: load_hilma_xml(fpath.open(), collection) if __name__ == '__main__': argh.dispatch_command(sync_hilma_xml_directory) ## Instruction: Use the notice ID as priary key ## Code After: import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getroot() notices = list(root.iterfind('WRAPPED_NOTICE')) notices = map(hilma_to_dict, notices) for n in notices: # Use the ID as primary key n.update({'_id': n['ID']}) collection.save(n) def sync_hilma_xml_directory(directory, mongo_uri=None, mongo_db='openhilma'): if mongo_uri is None: client = pymongo.MongoClient() else: client = pymongo.MongoClient(mongo_uri) db = client[mongo_db] collection = db.notices paths = sorted(Path(directory).glob("*.xml")) for fpath in paths: load_hilma_xml(fpath.open(), collection) if __name__ == '__main__': argh.dispatch_command(sync_hilma_xml_directory)
8bc2b19e9aef410832555fb9962c243f0d4aef96
brink/decorators.py
brink/decorators.py
def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model): return 200, model """ def decorator(handler): async def new_handler(request): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, *args, model, **kwargs) return new_handler return decorator
import asyncio def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model): return 200, model """ def decorator(handler): async def new_handler(request): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, *args, model, **kwargs) return new_handler return decorator def use_ws_subhandlers(handler): """ Allows the handler to return any number of **subhandlers** that will be run in parallel. This makes it much cleaner and easier to write a handler that both listens for incoming messages on the socket connection, while also watching a changefeed from RethinkDB. Example usage :: @use_ws_subhandlers async def handle_feed(request, ws): async def handle_incoming(_, ws): async for msg in ws: await Item(value=msg.data).save() async def handle_change(_, ws): async for item in await Item.changes(): ws.send_json(item) return [handle_incoming, handle_change] """ async def new_handler(request, ws): handlers = await handler(request, ws) tasks = [request.app.loop.create_task(h(request, ws)) for h in handlers] try: await asyncio.gather(*tasks) finally: for task in tasks: task.cancel() await ws.close() return new_handler
Add decorator for using websocket subhandlers
Add decorator for using websocket subhandlers
Python
bsd-3-clause
brinkframework/brink
+ import asyncio + + def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model): return 200, model """ def decorator(handler): async def new_handler(request): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, *args, model, **kwargs) return new_handler return decorator + + def use_ws_subhandlers(handler): + """ + Allows the handler to return any number of **subhandlers** that will be + run in parallel. This makes it much cleaner and easier to write a handler + that both listens for incoming messages on the socket connection, while + also watching a changefeed from RethinkDB. + + Example usage :: + + @use_ws_subhandlers + async def handle_feed(request, ws): + async def handle_incoming(_, ws): + async for msg in ws: + await Item(value=msg.data).save() + + async def handle_change(_, ws): + async for item in await Item.changes(): + ws.send_json(item) + + return [handle_incoming, handle_change] + """ + async def new_handler(request, ws): + handlers = await handler(request, ws) + tasks = [request.app.loop.create_task(h(request, ws)) + for h in handlers] + + try: + await asyncio.gather(*tasks) + finally: + for task in tasks: + task.cancel() + + await ws.close() + return new_handler +
Add decorator for using websocket subhandlers
## Code Before: def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model): return 200, model """ def decorator(handler): async def new_handler(request): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, *args, model, **kwargs) return new_handler return decorator ## Instruction: Add decorator for using websocket subhandlers ## Code After: import asyncio def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the handler as the last positional argument. :: @require_request_model(Model) async def handle_model(request, model): return 200, model """ def decorator(handler): async def new_handler(request): body = await request.json() model = cls(**body) if validate: model.validate() return await handler(request, *args, model, **kwargs) return new_handler return decorator def use_ws_subhandlers(handler): """ Allows the handler to return any number of **subhandlers** that will be run in parallel. This makes it much cleaner and easier to write a handler that both listens for incoming messages on the socket connection, while also watching a changefeed from RethinkDB. Example usage :: @use_ws_subhandlers async def handle_feed(request, ws): async def handle_incoming(_, ws): async for msg in ws: await Item(value=msg.data).save() async def handle_change(_, ws): async for item in await Item.changes(): ws.send_json(item) return [handle_incoming, handle_change] """ async def new_handler(request, ws): handlers = await handler(request, ws) tasks = [request.app.loop.create_task(h(request, ws)) for h in handlers] try: await asyncio.gather(*tasks) finally: for task in tasks: task.cancel() await ws.close() return new_handler
2501bb03e836ac29cc1defa8591446ff217771b2
tests/test_model.py
tests/test_model.py
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = 'example@example.com' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, 'example@example.com') self.assertEqual(user.first_name, u'John') self.assertEqual(user.last_name, u'Smith') self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = 'example@example.com' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, 'example@example.com') self.assertEqual(user.first_name, unicode('John')) self.assertEqual(user.last_name, unicode('Smith')) self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
Fix of tests with unicode strings
Fix of tests with unicode strings
Python
bsd-3-clause
ets-labs/domain_models,ets-labs/python-domain-models,rmk135/domain_models
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = 'example@example.com' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, 'example@example.com') - self.assertEqual(user.first_name, u'John') + self.assertEqual(user.first_name, unicode('John')) - self.assertEqual(user.last_name, u'Smith') + self.assertEqual(user.last_name, unicode('Smith')) self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
Fix of tests with unicode strings
## Code Before: """Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = 'example@example.com' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, 'example@example.com') self.assertEqual(user.first_name, u'John') self.assertEqual(user.last_name, u'Smith') self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988') ## Instruction: Fix of tests with unicode strings ## Code After: """Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender = fields.String() birth_date = fields.String() __view_key__ = [id, email] __unique_key__ = id class SampleTests(unittest.TestCase): """Sample tests tests.""" def test_set_and_get_attrs(self): """Test setting and getting of domain model attributes.""" user = User() user.id = 1 user.email = 'example@example.com' user.first_name = 'John' user.last_name = 'Smith' user.gender = 'male' user.birth_date = '05/04/1988' self.assertEqual(user.id, 1) self.assertEqual(user.email, 'example@example.com') self.assertEqual(user.first_name, unicode('John')) self.assertEqual(user.last_name, unicode('Smith')) self.assertEqual(user.gender, 'male') self.assertEqual(user.birth_date, '05/04/1988')
cb798ae8f7f6e810a87137a56cd04be76596a2dd
photutils/tests/test_psfs.py
photutils/tests/test_psfs.py
from __future__ import division import numpy as np from astropy.tests.helper import pytest from photutils.psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('width'), widths) def test_subpixel_gauss_psf(width): """ Test subpixel accuracy of Gaussian PSF by checking the sum o pixels. """ gauss_psf = GaussianPSF(width) y, x = np.mgrid[-10:11, -10:11] assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12 @pytest.mark.skipif('not HAS_SCIPY') def test_gaussian_PSF_integral(): """ Test if Gaussian PSF integrates to unity on larger scales. """ psf = GaussianPSF(10) y, x = np.mgrid[-100:101, -100:101] assert np.abs(psf(y, x).sum() - 1) < 1E-12
from __future__ import division import numpy as np from astropy.tests.helper import pytest from ..psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('width'), widths) def test_subpixel_gauss_psf(width): """ Test subpixel accuracy of Gaussian PSF by checking the sum o pixels. """ gauss_psf = GaussianPSF(width) y, x = np.mgrid[-10:11, -10:11] assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12 @pytest.mark.skipif('not HAS_SCIPY') def test_gaussian_PSF_integral(): """ Test if Gaussian PSF integrates to unity on larger scales. """ psf = GaussianPSF(10) y, x = np.mgrid[-100:101, -100:101] assert np.abs(psf(y, x).sum() - 1) < 1E-12
Use relative imports for consistency; pep8
Use relative imports for consistency; pep8
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
from __future__ import division - import numpy as np - from astropy.tests.helper import pytest - from photutils.psf import GaussianPSF + from ..psf import GaussianPSF - try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] + @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('width'), widths) def test_subpixel_gauss_psf(width): """ Test subpixel accuracy of Gaussian PSF by checking the sum o pixels. """ gauss_psf = GaussianPSF(width) y, x = np.mgrid[-10:11, -10:11] assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12 - + + - @pytest.mark.skipif('not HAS_SCIPY') + @pytest.mark.skipif('not HAS_SCIPY') def test_gaussian_PSF_integral(): """ Test if Gaussian PSF integrates to unity on larger scales. """ psf = GaussianPSF(10) y, x = np.mgrid[-100:101, -100:101] - assert np.abs(psf(y, x).sum() - 1) < 1E-12 + assert np.abs(psf(y, x).sum() - 1) < 1E-12 - -
Use relative imports for consistency; pep8
## Code Before: from __future__ import division import numpy as np from astropy.tests.helper import pytest from photutils.psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('width'), widths) def test_subpixel_gauss_psf(width): """ Test subpixel accuracy of Gaussian PSF by checking the sum o pixels. """ gauss_psf = GaussianPSF(width) y, x = np.mgrid[-10:11, -10:11] assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12 @pytest.mark.skipif('not HAS_SCIPY') def test_gaussian_PSF_integral(): """ Test if Gaussian PSF integrates to unity on larger scales. """ psf = GaussianPSF(10) y, x = np.mgrid[-100:101, -100:101] assert np.abs(psf(y, x).sum() - 1) < 1E-12 ## Instruction: Use relative imports for consistency; pep8 ## Code After: from __future__ import division import numpy as np from astropy.tests.helper import pytest from ..psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('width'), widths) def test_subpixel_gauss_psf(width): """ Test subpixel accuracy of Gaussian PSF by checking the sum o pixels. """ gauss_psf = GaussianPSF(width) y, x = np.mgrid[-10:11, -10:11] assert np.abs(gauss_psf(x, y).sum() - 1) < 1E-12 @pytest.mark.skipif('not HAS_SCIPY') def test_gaussian_PSF_integral(): """ Test if Gaussian PSF integrates to unity on larger scales. """ psf = GaussianPSF(10) y, x = np.mgrid[-100:101, -100:101] assert np.abs(psf(y, x).sum() - 1) < 1E-12
65fd070a88e06bb040e8c96babc6b4c86ca29730
validatish/error.py
validatish/error.py
class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ = __str__ def __repr__(self): if self.exceptions: return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator) else: return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator) @property def errors(self): return list(_flatten(self._fetch_errors(), _keepstrings)) def _fetch_errors(self): if self.exceptions is None: yield self.message else: for e in self.exceptions: yield e._fetch_errors() def _flatten(s, toiter=iter): try: it = toiter(s) except TypeError: yield s else: for elem in it: for subelem in _flatten(elem, toiter): yield subelem def _keepstrings(seq): if isinstance(seq, basestring): raise TypeError return iter(seq)
class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ = __str__ def __repr__(self): if self.exceptions: return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator) else: return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator) @property def errors(self): return list(_flatten(self._fetch_errors(), _keepstrings)) def _fetch_errors(self): if self.exceptions is None: yield self.message else: for e in self.exceptions: yield e._fetch_errors() # Hide Python 2.6 deprecation warning. def _get_message(self): return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) def _flatten(s, toiter=iter): try: it = toiter(s) except TypeError: yield s else: for elem in it: for subelem in _flatten(elem, toiter): yield subelem def _keepstrings(seq): if isinstance(seq, basestring): raise TypeError return iter(seq)
Hide Python 2.6 Exception.message deprecation warnings
Hide Python 2.6 Exception.message deprecation warnings
Python
bsd-3-clause
ish/validatish,ish/validatish
class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ = __str__ def __repr__(self): if self.exceptions: return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator) else: return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator) - @property def errors(self): return list(_flatten(self._fetch_errors(), _keepstrings)) def _fetch_errors(self): if self.exceptions is None: yield self.message else: for e in self.exceptions: yield e._fetch_errors() + + # Hide Python 2.6 deprecation warning. + def _get_message(self): return self._message + def _set_message(self, message): self._message = message + message = property(_get_message, _set_message) def _flatten(s, toiter=iter): try: it = toiter(s) except TypeError: yield s else: for elem in it: for subelem in _flatten(elem, toiter): yield subelem def _keepstrings(seq): if isinstance(seq, basestring): raise TypeError return iter(seq)
Hide Python 2.6 Exception.message deprecation warnings
## Code Before: class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ = __str__ def __repr__(self): if self.exceptions: return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator) else: return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator) @property def errors(self): return list(_flatten(self._fetch_errors(), _keepstrings)) def _fetch_errors(self): if self.exceptions is None: yield self.message else: for e in self.exceptions: yield e._fetch_errors() def _flatten(s, toiter=iter): try: it = toiter(s) except TypeError: yield s else: for elem in it: for subelem in _flatten(elem, toiter): yield subelem def _keepstrings(seq): if isinstance(seq, basestring): raise TypeError return iter(seq) ## Instruction: Hide Python 2.6 Exception.message deprecation warnings ## Code After: class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ = __str__ def __repr__(self): if self.exceptions: return 'validatish.Invalid("%s", exceptions=%s, validator=%s)' % (self.message, self.exceptions, self.validator) else: return 'validatish.Invalid("%s", validator=%s)' % (self.message, self.validator) @property def errors(self): return list(_flatten(self._fetch_errors(), _keepstrings)) def _fetch_errors(self): if self.exceptions is None: yield self.message else: for e in self.exceptions: yield e._fetch_errors() # Hide Python 2.6 deprecation warning. def _get_message(self): return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) def _flatten(s, toiter=iter): try: it = toiter(s) except TypeError: yield s else: for elem in it: for subelem in _flatten(elem, toiter): yield subelem def _keepstrings(seq): if isinstance(seq, basestring): raise TypeError return iter(seq)
356dd5294280db3334f86354202f0d68881254b9
joerd/check.py
joerd/check.py
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) tmp_member.seek(0) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False return func def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
Python
mit
mapzen/joerd,tilezen/joerd
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) + tmp_member.seek(0) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False + + return func def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
## Code Before: import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False ## Instruction: Return verifier function, not None. Also reset the temporary file to the beginning before verifying it. ## Code After: import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.testzip() return test_result is None except: pass return False def tar_gz_has_gdal(member_name): """ Returns a function which, when called with a NamedTemporaryFile, returns True if that file is a GZip-encoded TAR file containing a `member_name` member which can be opened with GDAL. """ def func(tmp): try: tar = tarfile.open(tmp.name, mode='r:gz', errorlevel=2) with tempfile.NamedTemporaryFile() as tmp_member: shutil.copyfileobj(tar.extractfile(member_name), tmp_member) tmp_member.seek(0) return is_gdal(tmp_member) except (tarfile.TarError, IOError, OSError) as e: return False return func def is_gdal(tmp): """ Returns true if the NamedTemporaryFile given as the argument appears to be a well-formed GDAL raster file. """ try: ds = gdal.Open(tmp.name) band = ds.GetRasterBand(1) band.ComputeBandStats() return True except: pass return False
d84e6aa022ef5e256807738c35e5069a0a1380d7
app/main/forms/frameworks.py
app/main/forms/frameworks.py
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] )
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] ) class AcceptAgreementVariationForm(Form): accept_changes = BooleanField( 'I accept these proposed changes', validators=[ DataRequired(message="If you agree to the proposed changes then you must check the box before saving.") ] )
Add form for accepting contract variation
Add form for accepting contract variation
Python
mit
alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] ) + + class AcceptAgreementVariationForm(Form): + accept_changes = BooleanField( + 'I accept these proposed changes', + validators=[ + DataRequired(message="If you agree to the proposed changes then you must check the box before saving.") + ] + ) +
Add form for accepting contract variation
## Code Before: from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] ) ## Instruction: Add form for accepting contract variation ## Code After: from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide the full name of the person signing on behalf of the company."), Length(max=255, message="You must provide a name under 256 characters.") ]) signerRole = StripWhitespaceStringField( 'Role at the company', validators=[ DataRequired(message="You must provide the role of the person signing on behalf of the company."), Length(max=255, message="You must provide a role under 256 characters.") ], description='The person signing must have the authority to agree to the framework terms, ' 'eg director or company secretary.' ) class ContractReviewForm(Form): authorisation = BooleanField( 'Authorisation', validators=[DataRequired(message="You must confirm you have the authority to return the agreement.")] ) class AcceptAgreementVariationForm(Form): accept_changes = BooleanField( 'I accept these proposed changes', validators=[ DataRequired(message="If you agree to the proposed changes then you must check the box before saving.") ] )
75171ed80079630d22463685768072ad7323e653
boundary/action_installed.py
boundary/action_installed.py
from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions associated with the Boundary account"
from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions configured within a Boundary account"
Change code to be PEP-8 compliant
Change code to be PEP-8 compliant
Python
apache-2.0
boundary/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/boundary-api-cli,jdgwartney/pulse-api-cli,wcainboundary/boundary-api-cli,wcainboundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/pulse-api-cli
from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): - return "Returns the actions associated with the Boundary account" + return "Returns the actions configured within a Boundary account" - +
Change code to be PEP-8 compliant
## Code Before: from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions associated with the Boundary account" ## Instruction: Change code to be PEP-8 compliant ## Code After: from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions configured within a Boundary account"
57bc8b3c40bbafda6f69b23c230ad73750e881ab
hashable/helpers.py
hashable/helpers.py
from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', 'equality_comparable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls = equality_comparable(cls, attributes, methods) cls.__hash__ = HashCodeBuilder.auto_generate(cls, attributes, methods) return cls return decorator if cls is None else decorator(cls) def equality_comparable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls.__eq__ = EqualsBuilder.auto_generate(cls, attributes, methods) cls.__ne__ = EqualsBuilder.auto_ne_from_eq() return cls return decorator if cls is None else decorator(cls) def _validate_attributes_and_methods(attributes, methods): assert not isinstance(attributes, basestring), 'attributes must be list' assert not isinstance(methods, basestring), 'methods must be list' assert attributes or methods, 'attributes or methods must be NOT empty'
from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', 'equalable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls = equalable(cls, attributes, methods) cls.__hash__ = HashCodeBuilder.auto_generate(cls, attributes, methods) return cls return decorator if cls is None else decorator(cls) def equalable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls.__eq__ = EqualsBuilder.auto_generate(cls, attributes, methods) cls.__ne__ = EqualsBuilder.auto_ne_from_eq() return cls return decorator if cls is None else decorator(cls) def _validate_attributes_and_methods(attributes, methods): assert not isinstance(attributes, basestring), 'attributes must be list' assert not isinstance(methods, basestring), 'methods must be list' assert attributes or methods, 'attributes or methods must be NOT empty'
Rename decorator equality_comparable to equalable
Rename decorator equality_comparable to equalable
Python
mit
minmax/hashable
from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', - 'equality_comparable', + 'equalable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): - cls = equality_comparable(cls, attributes, methods) + cls = equalable(cls, attributes, methods) cls.__hash__ = HashCodeBuilder.auto_generate(cls, attributes, methods) return cls return decorator if cls is None else decorator(cls) - def equality_comparable(cls=None, attributes=None, methods=None): + def equalable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls.__eq__ = EqualsBuilder.auto_generate(cls, attributes, methods) cls.__ne__ = EqualsBuilder.auto_ne_from_eq() return cls return decorator if cls is None else decorator(cls) def _validate_attributes_and_methods(attributes, methods): assert not isinstance(attributes, basestring), 'attributes must be list' assert not isinstance(methods, basestring), 'methods must be list' assert attributes or methods, 'attributes or methods must be NOT empty'
Rename decorator equality_comparable to equalable
## Code Before: from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', 'equality_comparable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls = equality_comparable(cls, attributes, methods) cls.__hash__ = HashCodeBuilder.auto_generate(cls, attributes, methods) return cls return decorator if cls is None else decorator(cls) def equality_comparable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls.__eq__ = EqualsBuilder.auto_generate(cls, attributes, methods) cls.__ne__ = EqualsBuilder.auto_ne_from_eq() return cls return decorator if cls is None else decorator(cls) def _validate_attributes_and_methods(attributes, methods): assert not isinstance(attributes, basestring), 'attributes must be list' assert not isinstance(methods, basestring), 'methods must be list' assert attributes or methods, 'attributes or methods must be NOT empty' ## Instruction: Rename decorator equality_comparable to equalable ## Code After: from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', 'equalable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls = equalable(cls, attributes, methods) cls.__hash__ = HashCodeBuilder.auto_generate(cls, attributes, methods) return cls return decorator if cls is None else decorator(cls) def equalable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls.__eq__ = EqualsBuilder.auto_generate(cls, attributes, methods) cls.__ne__ = EqualsBuilder.auto_ne_from_eq() return cls return decorator if cls is None else decorator(cls) def _validate_attributes_and_methods(attributes, methods): assert not isinstance(attributes, basestring), 'attributes must be list' assert not isinstance(methods, basestring), 'methods must be list' assert attributes or methods, 'attributes or methods must be NOT empty'
4f6e27a6bbc2bbdb19c165f21d47d1491bffd70e
scripts/mc_check_lib_file.py
scripts/mc_check_lib_file.py
import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] for pathname in args.files: filename = os.path.basename(pathname) with db.sessionmaker() as session: out = session.get_lib_files(filename) if len(out) > 0: print(pathname) # if we have a file, say so
import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] with db.sessionmaker() as session: for pathname in args.files: filename = os.path.basename(pathname) out = session.get_lib_files(filename) if len(out) > 0: print(pathname) # if we have a file, say so
Move sessionmaker outside of loop
Move sessionmaker outside of loop
Python
bsd-2-clause
HERA-Team/hera_mc,HERA-Team/hera_mc
import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] + with db.sessionmaker() as session: - for pathname in args.files: + for pathname in args.files: - filename = os.path.basename(pathname) + filename = os.path.basename(pathname) - with db.sessionmaker() as session: out = session.get_lib_files(filename) if len(out) > 0: print(pathname) # if we have a file, say so
Move sessionmaker outside of loop
## Code Before: import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] for pathname in args.files: filename = os.path.basename(pathname) with db.sessionmaker() as session: out = session.get_lib_files(filename) if len(out) > 0: print(pathname) # if we have a file, say so ## Instruction: Move sessionmaker outside of loop ## Code After: import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] with db.sessionmaker() as session: for pathname in args.files: filename = os.path.basename(pathname) out = session.get_lib_files(filename) if len(out) > 0: print(pathname) # if we have a file, say so
a3213788d0d8591b235359d4b17886ce3f50ab37
tests/test_plugin.py
tests/test_plugin.py
import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) with open('./datajoint.pub', "r") as f: assert(f.read() == pubkey_meta) def test_normal_djerror(): try: raise djerr.DataJointError except djerr.DataJointError as e: assert(e.__cause__ is None) def test_verified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=True, plugon='example')) raise djerr.DataJointError except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(e.__cause__ is None) def test_unverified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=False, plugon='example')) raise djerr.DataJointError("hello") except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(isinstance(e.__cause__, djerr.PluginWarning))
import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources from os import path def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) with open(path.join(path.abspath( path.dirname(__file__)), '..', 'datajoint.pub'), "r") as f: assert(f.read() == pubkey_meta) def test_normal_djerror(): try: raise djerr.DataJointError except djerr.DataJointError as e: assert(e.__cause__ is None) def test_verified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=True, plugon='example')) raise djerr.DataJointError except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(e.__cause__ is None) def test_unverified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=False, plugon='example')) raise djerr.DataJointError("hello") except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(isinstance(e.__cause__, djerr.PluginWarning))
Make pubkey test more portable.
Make pubkey test more portable.
Python
lgpl-2.1
datajoint/datajoint-python,dimitri-yatsenko/datajoint-python
import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources + from os import path def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) - with open('./datajoint.pub', "r") as f: + with open(path.join(path.abspath( + path.dirname(__file__)), '..', 'datajoint.pub'), "r") as f: assert(f.read() == pubkey_meta) def test_normal_djerror(): try: raise djerr.DataJointError except djerr.DataJointError as e: assert(e.__cause__ is None) def test_verified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=True, plugon='example')) raise djerr.DataJointError except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(e.__cause__ is None) def test_unverified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=False, plugon='example')) raise djerr.DataJointError("hello") except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(isinstance(e.__cause__, djerr.PluginWarning))
Make pubkey test more portable.
## Code Before: import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) with open('./datajoint.pub', "r") as f: assert(f.read() == pubkey_meta) def test_normal_djerror(): try: raise djerr.DataJointError except djerr.DataJointError as e: assert(e.__cause__ is None) def test_verified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=True, plugon='example')) raise djerr.DataJointError except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(e.__cause__ is None) def test_unverified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=False, plugon='example')) raise djerr.DataJointError("hello") except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(isinstance(e.__cause__, djerr.PluginWarning)) ## Instruction: Make pubkey test more portable. ## Code After: import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources from os import path def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) with open(path.join(path.abspath( path.dirname(__file__)), '..', 'datajoint.pub'), "r") as f: assert(f.read() == pubkey_meta) def test_normal_djerror(): try: raise djerr.DataJointError except djerr.DataJointError as e: assert(e.__cause__ is None) def test_verified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=True, plugon='example')) raise djerr.DataJointError except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(e.__cause__ is None) def test_unverified_djerror(): try: curr_plugins = p.discovered_plugins p.discovered_plugins = dict(test_plugin_module=dict(verified=False, plugon='example')) raise djerr.DataJointError("hello") except djerr.DataJointError as e: p.discovered_plugins = curr_plugins assert(isinstance(e.__cause__, djerr.PluginWarning))
bc5475bcc3608de75c42d24c5c74e416b41b873f
pages/base.py
pages/base.py
from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator).click() from pages.login import LoginPage return LoginPage(self.testsetup) def click_logout(self): self.selenium.find_element(*self._logout_locator).click() def login(self, username=None, password=None): login_page = self.click_login() return login_page.login(username, password) def logout(self): self.click_logout() @property def notification(self): return self.selenium.find_element(*self._notification_locator).text
from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator).click() from pages.login import LoginPage return LoginPage(self.testsetup) def click_logout(self): self.selenium.find_element(*self._logout_locator).click() def login(self, username, password): login_page = self.click_login() return login_page.login(username, password) def logout(self): self.click_logout() @property def notification(self): return self.selenium.find_element(*self._notification_locator).text
Make username and password required arguments
Make username and password required arguments
Python
mpl-2.0
mozilla/mozwebqa-examples,davehunt/mozwebqa-examples,mozilla/mozwebqa-examples,davehunt/mozwebqa-examples
from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator).click() from pages.login import LoginPage return LoginPage(self.testsetup) def click_logout(self): self.selenium.find_element(*self._logout_locator).click() - def login(self, username=None, password=None): + def login(self, username, password): login_page = self.click_login() return login_page.login(username, password) def logout(self): self.click_logout() @property def notification(self): return self.selenium.find_element(*self._notification_locator).text
Make username and password required arguments
## Code Before: from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator).click() from pages.login import LoginPage return LoginPage(self.testsetup) def click_logout(self): self.selenium.find_element(*self._logout_locator).click() def login(self, username=None, password=None): login_page = self.click_login() return login_page.login(username, password) def logout(self): self.click_logout() @property def notification(self): return self.selenium.find_element(*self._notification_locator).text ## Instruction: Make username and password required arguments ## Code After: from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator).click() from pages.login import LoginPage return LoginPage(self.testsetup) def click_logout(self): self.selenium.find_element(*self._logout_locator).click() def login(self, username, password): login_page = self.click_login() return login_page.login(username, password) def logout(self): self.click_logout() @property def notification(self): return self.selenium.find_element(*self._notification_locator).text
54bce2a224843ec9c1c8b7eb35cdc6bf19d5726b
expensonator/api.py
expensonator/api.py
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() def save(self, bundle, skip_errors=False): bundle = super(ExpenseResource, self).save(bundle, skip_errors) bundle.obj.reset_tags_from_string(bundle.data["tags"]) return bundle class Meta: queryset = Expense.objects.all() excludes = ["created", "updated"] # WARNING: Tastypie docs say that this is VERY INSECURE! # For development only! authorization = Authorization()
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() def save(self, bundle, skip_errors=False): bundle = super(ExpenseResource, self).save(bundle, skip_errors) if "tags" in bundle.data: bundle.obj.reset_tags_from_string(bundle.data["tags"]) return bundle class Meta: queryset = Expense.objects.all() excludes = ["created", "updated"] # WARNING: Tastypie docs say that this is VERY INSECURE! # For development only! authorization = Authorization()
Fix key error when no tags are specified
Fix key error when no tags are specified
Python
mit
matt-haigh/expensonator
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() def save(self, bundle, skip_errors=False): bundle = super(ExpenseResource, self).save(bundle, skip_errors) + if "tags" in bundle.data: - bundle.obj.reset_tags_from_string(bundle.data["tags"]) + bundle.obj.reset_tags_from_string(bundle.data["tags"]) return bundle class Meta: queryset = Expense.objects.all() excludes = ["created", "updated"] # WARNING: Tastypie docs say that this is VERY INSECURE! # For development only! authorization = Authorization()
Fix key error when no tags are specified
## Code Before: from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() def save(self, bundle, skip_errors=False): bundle = super(ExpenseResource, self).save(bundle, skip_errors) bundle.obj.reset_tags_from_string(bundle.data["tags"]) return bundle class Meta: queryset = Expense.objects.all() excludes = ["created", "updated"] # WARNING: Tastypie docs say that this is VERY INSECURE! # For development only! authorization = Authorization() ## Instruction: Fix key error when no tags are specified ## Code After: from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() def save(self, bundle, skip_errors=False): bundle = super(ExpenseResource, self).save(bundle, skip_errors) if "tags" in bundle.data: bundle.obj.reset_tags_from_string(bundle.data["tags"]) return bundle class Meta: queryset = Expense.objects.all() excludes = ["created", "updated"] # WARNING: Tastypie docs say that this is VERY INSECURE! # For development only! authorization = Authorization()
dfdeaf536466cfa8003af4cd5341d1d7127ea6b7
py/_test_py2go.py
py/_test_py2go.py
import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
Update python script for pep8 style
Update python script for pep8 style
Python
mit
sensorbee/py,sensorbee/py
import datetime + def return_true(): return True + def return_false(): return False + def return_int(): return 123 + def return_float(): return 1.0 + def return_string(): return "ABC" + def return_bytearray(): return bytearray('abcdefg') + def return_array(): return [1, 2, {"key": 3}] + def return_map(): return {"key1": 123, "key2": "str"} + def return_nested_map(): return {"key1": {"key2": 123}} + def return_none(): return None + def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
Update python script for pep8 style
## Code Before: import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None) ## Instruction: Update python script for pep8 style ## Code After: import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_map(): return {"key1": 123, "key2": "str"} def return_nested_map(): return {"key1": {"key2": 123}} def return_none(): return None def return_timestamp(): return datetime.datetime(2015, 4, 1, 14, 27, 0, 500*1000, None)
caf9795cf0f775442bd0c3e06cd550a6e8d0206b
virtool/labels/db.py
virtool/labels/db.py
async def count_samples(db, label_id): return await db.samples.count_documents({"labels": {"$in": [label_id]}})
async def attach_sample_count(db, document, label_id): document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})})
Rewrite function for sample count
Rewrite function for sample count
Python
mit
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
- async def count_samples(db, label_id): + async def attach_sample_count(db, document, label_id): - return await db.samples.count_documents({"labels": {"$in": [label_id]}}) + document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})})
Rewrite function for sample count
## Code Before: async def count_samples(db, label_id): return await db.samples.count_documents({"labels": {"$in": [label_id]}}) ## Instruction: Rewrite function for sample count ## Code After: async def attach_sample_count(db, document, label_id): document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})})
51e7cd3bc5a9a56fb53a5b0a8328d0b9d58848dd
modder/utils/desktop_notification.py
modder/utils/desktop_notification.py
import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def desktop_notify(text, title='Modder', sound=False): notification = NSUserNotification.alloc().init() notification.setTitle_(title.decode('utf-8')) notification.setInformativeText_(text.decode('utf-8')) if sound: notification.setSoundName_(NSUserNotificationDefaultSoundName) center = NSUserNotificationCenter.defaultUserNotificationCenter() center.deliverNotification_(notification) elif platform.system() == 'Windows': def desktop_notify(text, title='Modder', sound=False): pass elif platform.system() == 'Linux': def desktop_notify(text, title='Modder', sound=False): pass
import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def desktop_notify(text, title=None, sound=False): title = title or 'Modder' notification = NSUserNotification.alloc().init() notification.setTitle_(title.decode('utf-8')) notification.setInformativeText_(text.decode('utf-8')) if sound: notification.setSoundName_(NSUserNotificationDefaultSoundName) center = NSUserNotificationCenter.defaultUserNotificationCenter() center.deliverNotification_(notification) elif platform.system() == 'Windows': def desktop_notify(text, title=None, sound=False): title = title or 'Modder' pass elif platform.system() == 'Linux': def desktop_notify(text, title=None, sound=False): title = title or 'Modder' pass
Fix title for desktop notification
Fix title for desktop notification
Python
mit
JokerQyou/Modder2
import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') - def desktop_notify(text, title='Modder', sound=False): + def desktop_notify(text, title=None, sound=False): + title = title or 'Modder' + notification = NSUserNotification.alloc().init() notification.setTitle_(title.decode('utf-8')) notification.setInformativeText_(text.decode('utf-8')) if sound: notification.setSoundName_(NSUserNotificationDefaultSoundName) center = NSUserNotificationCenter.defaultUserNotificationCenter() center.deliverNotification_(notification) elif platform.system() == 'Windows': - def desktop_notify(text, title='Modder', sound=False): + def desktop_notify(text, title=None, sound=False): + title = title or 'Modder' + pass elif platform.system() == 'Linux': - def desktop_notify(text, title='Modder', sound=False): + def desktop_notify(text, title=None, sound=False): + title = title or 'Modder' + pass
Fix title for desktop notification
## Code Before: import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def desktop_notify(text, title='Modder', sound=False): notification = NSUserNotification.alloc().init() notification.setTitle_(title.decode('utf-8')) notification.setInformativeText_(text.decode('utf-8')) if sound: notification.setSoundName_(NSUserNotificationDefaultSoundName) center = NSUserNotificationCenter.defaultUserNotificationCenter() center.deliverNotification_(notification) elif platform.system() == 'Windows': def desktop_notify(text, title='Modder', sound=False): pass elif platform.system() == 'Linux': def desktop_notify(text, title='Modder', sound=False): pass ## Instruction: Fix title for desktop notification ## Code After: import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def desktop_notify(text, title=None, sound=False): title = title or 'Modder' notification = NSUserNotification.alloc().init() notification.setTitle_(title.decode('utf-8')) notification.setInformativeText_(text.decode('utf-8')) if sound: notification.setSoundName_(NSUserNotificationDefaultSoundName) center = NSUserNotificationCenter.defaultUserNotificationCenter() center.deliverNotification_(notification) elif platform.system() == 'Windows': def desktop_notify(text, title=None, sound=False): title = title or 'Modder' pass elif platform.system() == 'Linux': def desktop_notify(text, title=None, sound=False): title = title or 'Modder' pass
8a7837a8ce7b35c3141374c6a5c99361261fa70a
Cura/avr_isp/chipDB.py
Cura/avr_isp/chipDB.py
avrChipDB = { 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
avrChipDB = { 'ATMega1280': { 'signature': [0x1E, 0x97, 0x03], 'pageSize': 128, 'pageCount': 512, }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
Add ATMega1280 chip to programmer chips.
Add ATMega1280 chip to programmer chips.
Python
agpl-3.0
MolarAmbiguity/OctoPrint,EZ3-India/EZ-Remote,JackGavin13/octoprint-test-not-finished,spapadim/OctoPrint,dragondgold/OctoPrint,hudbrog/OctoPrint,CapnBry/OctoPrint,Javierma/OctoPrint-TFG,chriskoz/OctoPrint,javivi001/OctoPrint,shohei/Octoprint,eddieparker/OctoPrint,MolarAmbiguity/OctoPrint,mayoff/OctoPrint,uuv/OctoPrint,C-o-r-E/OctoPrint,Mikk36/OctoPrint,DanLipsitt/OctoPrint,shohei/Octoprint,beeverycreative/BEEweb,alex1818/OctoPrint,EZ3-India/EZ-Remote,alex1818/OctoPrint,shohei/Octoprint,markwal/OctoPrint,beeverycreative/BEEweb,aerickson/OctoPrint,beeverycreative/BEEweb,aerickson/OctoPrint,nicanor-romero/OctoPrint,punkkeks/OctoPrint,d42/octoprint-fork,Javierma/OctoPrint-TFG,3dprintcanalhouse/octoprint2,ErikDeBruijn/OctoPrint,punkkeks/OctoPrint,masterhou/OctoPrint,shaggythesheep/OctoPrint,chriskoz/OctoPrint,madhuni/AstroBox,Catrodigious/OctoPrint-TAM,alephobjects/Cura,javivi001/OctoPrint,uuv/OctoPrint,leductan-nguyen/RaionPi,MoonshineSG/OctoPrint,eliasbakken/OctoPrint,nicanor-romero/OctoPrint,Skeen/OctoPrint,javivi001/OctoPrint,Salandora/OctoPrint,jneves/OctoPrint,hudbrog/OctoPrint,shaggythesheep/OctoPrint,MoonshineSG/OctoPrint,skieast/OctoPrint,abinashk-inf/AstroBox,nickverschoor/OctoPrint,eddieparker/OctoPrint,EZ3-India/EZ-Remote,EZ3-India/EZ-Remote,abinashk-inf/AstroBox,mrbeam/OctoPrint,abinashk-inf/AstroBox,mrbeam/OctoPrint,Voxel8/OctoPrint,sstocker46/OctoPrint,bicephale/OctoPrint,dragondgold/OctoPrint,Jaesin/OctoPrint,mcanes/OctoPrint,ryanneufeld/OctoPrint,Salandora/OctoPrint,CapnBry/OctoPrint,foosel/OctoPrint,nickverschoor/OctoPrint,alephobjects/Cura,mcanes/OctoPrint,markwal/OctoPrint,sstocker46/OctoPrint,Jaesin/OctoPrint,3dprintcanalhouse/octoprint1,skieast/OctoPrint,madhuni/AstroBox,markwal/OctoPrint,Mikk36/OctoPrint,AstroPrint/AstroBox,ymilord/OctoPrint-MrBeam,dansantee/OctoPrint,Jaesin/OctoPrint,punkkeks/OctoPrint,ymilord/OctoPrint-MrBeam,rurkowce/octoprint-fork,foosel/OctoPrint,Salandora/OctoPrint,spapadim/OctoPrint,MoonshineSG/OctoPrint,spapadim/OctoPrint,madhuni/AstroBox,masterhou/OctoPrint,ymilord/OctoPrint-MrBeam,alephobjects/Cura,ryanneufeld/OctoPrint,chriskoz/OctoPrint,hudbrog/OctoPrint,Mikk36/OctoPrint,eddieparker/OctoPrint,leductan-nguyen/RaionPi,JackGavin13/octoprint-test-not-finished,beeverycreative/BEEweb,bicephale/OctoPrint,nicanor-romero/OctoPrint,jneves/OctoPrint,JackGavin13/octoprint-test-not-finished,ErikDeBruijn/OctoPrint,leductan-nguyen/RaionPi,CapnBry/OctoPrint,chriskoz/OctoPrint,ryanneufeld/OctoPrint,3dprintcanalhouse/octoprint1,mrbeam/OctoPrint,senttech/OctoPrint,Javierma/OctoPrint-TFG,dansantee/OctoPrint,Voxel8/OctoPrint,bicephale/OctoPrint,MolarAmbiguity/OctoPrint,MaxOLydian/OctoPrint,eliasbakken/OctoPrint,DanLipsitt/OctoPrint,mayoff/OctoPrint,Skeen/OctoPrint,Jaesin/OctoPrint,rurkowce/octoprint-fork,CapnBry/OctoPrint,AstroPrint/AstroBox,madhuni/AstroBox,uuv/OctoPrint,abinashk-inf/AstroBox,JackGavin13/octoprint-test-not-finished,SeveQ/OctoPrint,sstocker46/OctoPrint,dansantee/OctoPrint,skieast/OctoPrint,mayoff/OctoPrint,C-o-r-E/OctoPrint,eliasbakken/OctoPrint,ryanneufeld/OctoPrint,foosel/OctoPrint,nickverschoor/OctoPrint,bicephale/OctoPrint,SeveQ/OctoPrint,MoonshineSG/OctoPrint,SeveQ/OctoPrint,senttech/OctoPrint,shohei/Octoprint,ymilord/OctoPrint-MrBeam,3dprintcanalhouse/octoprint2,d42/octoprint-fork,mcanes/OctoPrint,Voxel8/OctoPrint,senttech/OctoPrint,ymilord/OctoPrint-MrBeam,leductan-nguyen/RaionPi,Javierma/OctoPrint-TFG,Salandora/OctoPrint,C-o-r-E/OctoPrint,alex1818/OctoPrint,MaxOLydian/OctoPrint,shaggythesheep/OctoPrint,masterhou/OctoPrint,shohei/Octoprint,ErikDeBruijn/OctoPrint,jneves/OctoPrint,Catrodigious/OctoPrint-TAM,foosel/OctoPrint,dragondgold/OctoPrint,senttech/OctoPrint,aerickson/OctoPrint,MaxOLydian/OctoPrint,nickverschoor/OctoPrint,Skeen/OctoPrint,Catrodigious/OctoPrint-TAM,AstroPrint/AstroBox
avrChipDB = { + 'ATMega1280': { + 'signature': [0x1E, 0x97, 0x03], + 'pageSize': 128, + 'pageCount': 512, + }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
Add ATMega1280 chip to programmer chips.
## Code Before: avrChipDB = { 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False ## Instruction: Add ATMega1280 chip to programmer chips. ## Code After: avrChipDB = { 'ATMega1280': { 'signature': [0x1E, 0x97, 0x03], 'pageSize': 128, 'pageCount': 512, }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
ef96000b01c50a77b3500fc4071f83f96d7b2458
mrbelvedereci/api/views/cumulusci.py
mrbelvedereci/api/views/cumulusci.py
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter from mrbelvedereci.cumulusci.filters import ServiceFilter from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import ScratchOrgInstance from mrbelvedereci.cumulusci.models import Service from rest_framework import viewsets class OrgViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Orgs """ serializer_class = OrgSerializer queryset = Org.objects.all() filter_class = OrgFilter class ScratchOrgInstanceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing ScratchOrgInstances """ serializer_class = ScratchOrgInstanceSerializer queryset = ScratchOrgInstance.objects.all() filter_class = ScratchOrgInstanceFilter class ServiceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Services """ serializer_class = ServiceSerializer queryset = Service.objects.all() filter_class = ServiceFilter
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import ScratchOrgInstance from mrbelvedereci.cumulusci.models import Service from rest_framework import viewsets class OrgViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Orgs """ serializer_class = OrgSerializer queryset = Org.objects.all() filter_class = OrgFilter class ScratchOrgInstanceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing ScratchOrgInstances """ serializer_class = ScratchOrgInstanceSerializer queryset = ScratchOrgInstance.objects.all() filter_class = ScratchOrgInstanceFilter class ServiceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Services """ serializer_class = ServiceSerializer queryset = Service.objects.all()
Remove ServiceFilter from view since it's not needed. Service only has name and json
Remove ServiceFilter from view since it's not needed. Service only has name and json
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter - from mrbelvedereci.cumulusci.filters import ServiceFilter from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import ScratchOrgInstance from mrbelvedereci.cumulusci.models import Service from rest_framework import viewsets class OrgViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Orgs """ serializer_class = OrgSerializer queryset = Org.objects.all() filter_class = OrgFilter class ScratchOrgInstanceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing ScratchOrgInstances """ serializer_class = ScratchOrgInstanceSerializer queryset = ScratchOrgInstance.objects.all() filter_class = ScratchOrgInstanceFilter class ServiceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Services """ serializer_class = ServiceSerializer queryset = Service.objects.all() - filter_class = ServiceFilter
Remove ServiceFilter from view since it's not needed. Service only has name and json
## Code Before: from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter from mrbelvedereci.cumulusci.filters import ServiceFilter from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import ScratchOrgInstance from mrbelvedereci.cumulusci.models import Service from rest_framework import viewsets class OrgViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Orgs """ serializer_class = OrgSerializer queryset = Org.objects.all() filter_class = OrgFilter class ScratchOrgInstanceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing ScratchOrgInstances """ serializer_class = ScratchOrgInstanceSerializer queryset = ScratchOrgInstance.objects.all() filter_class = ScratchOrgInstanceFilter class ServiceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Services """ serializer_class = ServiceSerializer queryset = Service.objects.all() filter_class = ServiceFilter ## Instruction: Remove ServiceFilter from view since it's not needed. Service only has name and json ## Code After: from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelvedereci.cumulusci.filters import ScratchOrgInstanceFilter from mrbelvedereci.cumulusci.models import Org from mrbelvedereci.cumulusci.models import ScratchOrgInstance from mrbelvedereci.cumulusci.models import Service from rest_framework import viewsets class OrgViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Orgs """ serializer_class = OrgSerializer queryset = Org.objects.all() filter_class = OrgFilter class ScratchOrgInstanceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing ScratchOrgInstances """ serializer_class = ScratchOrgInstanceSerializer queryset = ScratchOrgInstance.objects.all() filter_class = ScratchOrgInstanceFilter class ServiceViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing Services """ serializer_class = ServiceSerializer queryset = Service.objects.all()
24f0402e27ce7e51f370e82aa74c783438875d02
oslo_db/tests/sqlalchemy/__init__.py
oslo_db/tests/sqlalchemy/__init__.py
from oslo_db.sqlalchemy import test_base load_tests = test_base.optimize_db_test_loader(__file__)
from oslo_db.sqlalchemy import test_fixtures load_tests = test_fixtures.optimize_package_test_loader(__file__)
Remove deprecation warning when loading tests/sqlalchemy
Remove deprecation warning when loading tests/sqlalchemy /home/sam/Work/ironic/.tox/py27/local/lib/python2.7/site-packages/oslo_db/tests/sqlalchemy/__init__.py:20: DeprecationWarning: Function 'oslo_db.sqlalchemy.test_base.optimize_db_test_loader()' has moved to 'oslo_db.sqlalchemy.test_fixtures.optimize_package_test_loader()' Change-Id: I7fb4e776cedb8adcf97c9a43210049c60f796873
Python
apache-2.0
openstack/oslo.db,openstack/oslo.db
- from oslo_db.sqlalchemy import test_base + from oslo_db.sqlalchemy import test_fixtures - load_tests = test_base.optimize_db_test_loader(__file__) + load_tests = test_fixtures.optimize_package_test_loader(__file__)
Remove deprecation warning when loading tests/sqlalchemy
## Code Before: from oslo_db.sqlalchemy import test_base load_tests = test_base.optimize_db_test_loader(__file__) ## Instruction: Remove deprecation warning when loading tests/sqlalchemy ## Code After: from oslo_db.sqlalchemy import test_fixtures load_tests = test_fixtures.optimize_package_test_loader(__file__)
db6cb95d5d4261780482b4051f556fcbb2d9f237
rest_api/forms.py
rest_api/forms.py
from django.forms import ModelForm from rest_api.models import Url class UrlForm(ModelForm): class Meta: model = Url
from django.forms import ModelForm from gateway_backend.models import Url class UrlForm(ModelForm): class Meta: model = Url
Remove Url model from admin
Remove Url model from admin
Python
bsd-2-clause
victorpoluceno/shortener_frontend,victorpoluceno/shortener_frontend
from django.forms import ModelForm + - from rest_api.models import Url + from gateway_backend.models import Url class UrlForm(ModelForm): class Meta: model = Url
Remove Url model from admin
## Code Before: from django.forms import ModelForm from rest_api.models import Url class UrlForm(ModelForm): class Meta: model = Url ## Instruction: Remove Url model from admin ## Code After: from django.forms import ModelForm from gateway_backend.models import Url class UrlForm(ModelForm): class Meta: model = Url
3410fba1c8a39156def029eac9c7ff9f779832e6
dev/ci.py
dev/ci.py
from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) # In case any of the deps are installed system-wide sys.path.insert(0, deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
Fix CI to ignore system install of asn1crypto
Fix CI to ignore system install of asn1crypto
Python
mit
wbond/oscrypto
from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) + # In case any of the deps are installed system-wide + sys.path.insert(0, deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
Fix CI to ignore system install of asn1crypto
## Code Before: from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result ## Instruction: Fix CI to ignore system install of asn1crypto ## Code After: from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) # In case any of the deps are installed system-wide sys.path.insert(0, deps_dir) if sys.version_info[0:2] not in [(2, 6), (3, 2)]: from .lint import run as run_lint else: run_lint = None if sys.version_info[0:2] != (3, 2): from .coverage import run as run_coverage from .coverage import coverage run_tests = None else: from .tests import run as run_tests run_coverage = None def run(): """ Runs the linter and tests :return: A bool - if the linter and tests ran successfully """ _preload(requires_oscrypto, True) if run_lint: print('') lint_result = run_lint() else: lint_result = True if run_coverage: print('\nRunning tests (via coverage.py %s)' % coverage.__version__) sys.stdout.flush() tests_result = run_coverage(ci=True) else: print('\nRunning tests') sys.stdout.flush() tests_result = run_tests(ci=True) sys.stdout.flush() return lint_result and tests_result
502d99042428175b478e796c067e41995a0ae5bf
picoCTF-web/api/apps/v1/__init__.py
picoCTF-web/api/apps/v1/__init__.py
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from .settings import ns as settings_ns from .bundles import ns as bundles_ns from .submissions import ns as submissions_ns from .feedback import ns as feedback_ns blueprint = Blueprint('v1_api', __name__) api = Api( app=blueprint, title='picoCTF API', version='1.0', ) api.add_namespace(achievements_ns) api.add_namespace(problems_ns) api.add_namespace(shell_servers_ns) api.add_namespace(exceptions_ns) api.add_namespace(settings_ns) api.add_namespace(bundles_ns) api.add_namespace(submissions_ns) api.add_namespace(feedback_ns) @api.errorhandler(PicoException) def handle_pico_exception(e): """Handle exceptions.""" response = jsonify(e.to_dict()) response.status_code = 203 return response
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from .settings import ns as settings_ns from .bundles import ns as bundles_ns from .submissions import ns as submissions_ns from .feedback import ns as feedback_ns blueprint = Blueprint('v1_api', __name__) api = Api( app=blueprint, title='picoCTF API', version='1.0', ) api.add_namespace(achievements_ns) api.add_namespace(problems_ns) api.add_namespace(shell_servers_ns) api.add_namespace(exceptions_ns) api.add_namespace(settings_ns) api.add_namespace(bundles_ns) api.add_namespace(submissions_ns) api.add_namespace(feedback_ns) @api.errorhandler(PicoException) def handle_pico_exception(e): """Handle exceptions.""" response = jsonify(e.to_dict()) response.status_code = e.status_code return response
Fix PicoException response code bug
Fix PicoException response code bug
Python
mit
royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from .settings import ns as settings_ns from .bundles import ns as bundles_ns from .submissions import ns as submissions_ns from .feedback import ns as feedback_ns blueprint = Blueprint('v1_api', __name__) api = Api( app=blueprint, title='picoCTF API', version='1.0', ) api.add_namespace(achievements_ns) api.add_namespace(problems_ns) api.add_namespace(shell_servers_ns) api.add_namespace(exceptions_ns) api.add_namespace(settings_ns) api.add_namespace(bundles_ns) api.add_namespace(submissions_ns) api.add_namespace(feedback_ns) @api.errorhandler(PicoException) def handle_pico_exception(e): """Handle exceptions.""" response = jsonify(e.to_dict()) - response.status_code = 203 + response.status_code = e.status_code return response
Fix PicoException response code bug
## Code Before: """picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from .settings import ns as settings_ns from .bundles import ns as bundles_ns from .submissions import ns as submissions_ns from .feedback import ns as feedback_ns blueprint = Blueprint('v1_api', __name__) api = Api( app=blueprint, title='picoCTF API', version='1.0', ) api.add_namespace(achievements_ns) api.add_namespace(problems_ns) api.add_namespace(shell_servers_ns) api.add_namespace(exceptions_ns) api.add_namespace(settings_ns) api.add_namespace(bundles_ns) api.add_namespace(submissions_ns) api.add_namespace(feedback_ns) @api.errorhandler(PicoException) def handle_pico_exception(e): """Handle exceptions.""" response = jsonify(e.to_dict()) response.status_code = 203 return response ## Instruction: Fix PicoException response code bug ## Code After: """picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from .settings import ns as settings_ns from .bundles import ns as bundles_ns from .submissions import ns as submissions_ns from .feedback import ns as feedback_ns blueprint = Blueprint('v1_api', __name__) api = Api( app=blueprint, title='picoCTF API', version='1.0', ) api.add_namespace(achievements_ns) api.add_namespace(problems_ns) api.add_namespace(shell_servers_ns) api.add_namespace(exceptions_ns) api.add_namespace(settings_ns) api.add_namespace(bundles_ns) api.add_namespace(submissions_ns) api.add_namespace(feedback_ns) @api.errorhandler(PicoException) def handle_pico_exception(e): """Handle exceptions.""" response = jsonify(e.to_dict()) response.status_code = e.status_code return response
5d71215645683a059a51407a3768054c9ea77406
pisite/logs/forms.py
pisite/logs/forms.py
from django import forms from logs.models import Log class LineCountForm(forms.Form): linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow)
from django import forms from logs.models import Log class LineCountForm(forms.Form): linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.defaultLinesToShow)
Add to the label that 0 lines will result in the entire file being downloaded
Add to the label that 0 lines will result in the entire file being downloaded
Python
mit
sizlo/RPiFun,sizlo/RPiFun
from django import forms from logs.models import Log class LineCountForm(forms.Form): - linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow) + linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.defaultLinesToShow)
Add to the label that 0 lines will result in the entire file being downloaded
## Code Before: from django import forms from logs.models import Log class LineCountForm(forms.Form): linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow) ## Instruction: Add to the label that 0 lines will result in the entire file being downloaded ## Code After: from django import forms from logs.models import Log class LineCountForm(forms.Form): linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.defaultLinesToShow)
a389f20c7f2c8811a5c2f50c43a9ce5c7f3c8387
jobs_backend/vacancies/serializers.py
jobs_backend/vacancies/serializers.py
from rest_framework import serializers from .models import Vacancy class VacancySerializer(serializers.HyperlinkedModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_on', 'modified_on' ) extra_kwargs = { 'url': {'view_name': 'vacancies:vacancy-detail', 'read_only': True} }
from rest_framework import serializers from .models import Vacancy class VacancySerializer(serializers.ModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_on', 'modified_on' ) extra_kwargs = { 'url': {'view_name': 'api:vacancies:vacancy-detail', 'read_only': True} }
Fix for correct resolve URL
jobs-010: Fix for correct resolve URL
Python
mit
pyshopml/jobs-backend,pyshopml/jobs-backend
from rest_framework import serializers from .models import Vacancy - class VacancySerializer(serializers.HyperlinkedModelSerializer): + class VacancySerializer(serializers.ModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_on', 'modified_on' ) extra_kwargs = { - 'url': {'view_name': 'vacancies:vacancy-detail', 'read_only': True} + 'url': {'view_name': 'api:vacancies:vacancy-detail', 'read_only': True} }
Fix for correct resolve URL
## Code Before: from rest_framework import serializers from .models import Vacancy class VacancySerializer(serializers.HyperlinkedModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_on', 'modified_on' ) extra_kwargs = { 'url': {'view_name': 'vacancies:vacancy-detail', 'read_only': True} } ## Instruction: Fix for correct resolve URL ## Code After: from rest_framework import serializers from .models import Vacancy class VacancySerializer(serializers.ModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_on', 'modified_on' ) extra_kwargs = { 'url': {'view_name': 'api:vacancies:vacancy-detail', 'read_only': True} }
441a1b85f6ab954ab89f32977e4f00293270aac6
sphinxcontrib/multilatex/__init__.py
sphinxcontrib/multilatex/__init__.py
import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #=========================================================================== # Setup and register extension def setup(app): app.add_node(directive.latex_document, html=passthrough) app.add_directive("latex-document", directive.LatexDocumentDirective) app.add_builder(builder.MultiLatexBuilder) return {"version": "0.0"}
import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #=========================================================================== # Setup and register extension def setup(app): app.add_node(directive.latex_document, latex=passthrough, html=passthrough) app.add_directive("latex-document", directive.LatexDocumentDirective) app.add_builder(builder.MultiLatexBuilder) return {"version": "0.0"}
Set LaTeX builder to skip latex_document nodes
Set LaTeX builder to skip latex_document nodes This stops Sphinx' built-in LaTeX builder from complaining about unknown latex_document node type.
Python
apache-2.0
t4ngo/sphinxcontrib-multilatex,t4ngo/sphinxcontrib-multilatex
import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #=========================================================================== # Setup and register extension def setup(app): app.add_node(directive.latex_document, + latex=passthrough, html=passthrough) app.add_directive("latex-document", directive.LatexDocumentDirective) app.add_builder(builder.MultiLatexBuilder) return {"version": "0.0"}
Set LaTeX builder to skip latex_document nodes
## Code Before: import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #=========================================================================== # Setup and register extension def setup(app): app.add_node(directive.latex_document, html=passthrough) app.add_directive("latex-document", directive.LatexDocumentDirective) app.add_builder(builder.MultiLatexBuilder) return {"version": "0.0"} ## Instruction: Set LaTeX builder to skip latex_document nodes ## Code After: import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #=========================================================================== # Setup and register extension def setup(app): app.add_node(directive.latex_document, latex=passthrough, html=passthrough) app.add_directive("latex-document", directive.LatexDocumentDirective) app.add_builder(builder.MultiLatexBuilder) return {"version": "0.0"}
5c11a65af1d51794133895ebe2de92861b0894cf
flask_limiter/errors.py
flask_limiter/errors.py
"""errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions werkzeug_exception = None werkzeug_version = get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pragma: no cover # sorry, for touching your internals :). import werkzeug._internal werkzeug._internal.HTTP_STATUS_CODES[429] = "Too Many Requests" werkzeug_exception = exceptions.HTTPException else: # Werkzeug 0.9 and up have an existing exception for 429 werkzeug_exception = exceptions.TooManyRequests class RateLimitExceeded(werkzeug_exception): """exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 limit = None def __init__(self, limit): self.limit = limit if limit.error_message: description = ( limit.error_message if not callable(limit.error_message) else limit.error_message() ) else: description = text_type(limit.limit) super(RateLimitExceeded, self).__init__(description=description)
"""errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions class RateLimitExceeded(exceptions.TooManyRequests): """exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 limit = None def __init__(self, limit): self.limit = limit if limit.error_message: description = ( limit.error_message if not callable(limit.error_message) else limit.error_message() ) else: description = text_type(limit.limit) super(RateLimitExceeded, self).__init__(description=description)
Remove backward compatibility hack for exception subclass
Remove backward compatibility hack for exception subclass
Python
mit
alisaifee/flask-limiter,alisaifee/flask-limiter
"""errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions - werkzeug_exception = None - werkzeug_version = get_distribution("werkzeug").version - if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pragma: no cover - # sorry, for touching your internals :). - import werkzeug._internal + class RateLimitExceeded(exceptions.TooManyRequests): - werkzeug._internal.HTTP_STATUS_CODES[429] = "Too Many Requests" - werkzeug_exception = exceptions.HTTPException - else: - # Werkzeug 0.9 and up have an existing exception for 429 - werkzeug_exception = exceptions.TooManyRequests - - - class RateLimitExceeded(werkzeug_exception): """exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 limit = None def __init__(self, limit): self.limit = limit + if limit.error_message: description = ( limit.error_message + if not callable(limit.error_message) else limit.error_message() ) else: description = text_type(limit.limit) super(RateLimitExceeded, self).__init__(description=description)
Remove backward compatibility hack for exception subclass
## Code Before: """errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions werkzeug_exception = None werkzeug_version = get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pragma: no cover # sorry, for touching your internals :). import werkzeug._internal werkzeug._internal.HTTP_STATUS_CODES[429] = "Too Many Requests" werkzeug_exception = exceptions.HTTPException else: # Werkzeug 0.9 and up have an existing exception for 429 werkzeug_exception = exceptions.TooManyRequests class RateLimitExceeded(werkzeug_exception): """exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 limit = None def __init__(self, limit): self.limit = limit if limit.error_message: description = ( limit.error_message if not callable(limit.error_message) else limit.error_message() ) else: description = text_type(limit.limit) super(RateLimitExceeded, self).__init__(description=description) ## Instruction: Remove backward compatibility hack for exception subclass ## Code After: """errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions class RateLimitExceeded(exceptions.TooManyRequests): """exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 limit = None def __init__(self, limit): self.limit = limit if limit.error_message: description = ( limit.error_message if not callable(limit.error_message) else limit.error_message() ) else: description = text_type(limit.limit) super(RateLimitExceeded, self).__init__(description=description)
b3979a46a7bcd71aa9b40892167910fdeed5ad97
frigg/projects/admin.py
frigg/projects/admin.py
from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, obj=None): if obj: return 'key', 'value', 'is_secret' class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline): model = EnvironmentVariable extra = 0 @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): list_display = ('__str__', 'queue_name', 'approved', 'number_of_members', 'average_time', 'last_build_number', 'can_deploy') list_filter = ['owner', 'queue_name', 'approved', 'can_deploy'] actions = ['sync_members'] inlines = [EnvironmentVariableInline] def sync_members(self, request, queryset): for project in queryset: project.update_members() self.message_user( request, '{} project{} was synced'.format(len(queryset), pluralize(len(queryset))) ) sync_members.short_description = 'Sync members of selected projects' @admin.register(EnvironmentVariable) class EnvironmentVariableAdmin(EnvironmentVariableMixin, admin.ModelAdmin): list_display = ( '__str__', 'is_secret', )
from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, obj=None): if obj: return 'key', 'value', 'is_secret' return tuple() class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline): model = EnvironmentVariable extra = 0 @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): list_display = ('__str__', 'queue_name', 'approved', 'number_of_members', 'average_time', 'last_build_number', 'can_deploy') list_filter = ['owner', 'queue_name', 'approved', 'can_deploy'] actions = ['sync_members'] inlines = [EnvironmentVariableInline] def sync_members(self, request, queryset): for project in queryset: project.update_members() self.message_user( request, '{} project{} was synced'.format(len(queryset), pluralize(len(queryset))) ) sync_members.short_description = 'Sync members of selected projects' @admin.register(EnvironmentVariable) class EnvironmentVariableAdmin(EnvironmentVariableMixin, admin.ModelAdmin): list_display = ( '__str__', 'is_secret', )
Return empty tuple in get_readonly_fields
fix: Return empty tuple in get_readonly_fields
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, obj=None): if obj: return 'key', 'value', 'is_secret' + return tuple() class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline): model = EnvironmentVariable extra = 0 @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): list_display = ('__str__', 'queue_name', 'approved', 'number_of_members', 'average_time', 'last_build_number', 'can_deploy') list_filter = ['owner', 'queue_name', 'approved', 'can_deploy'] actions = ['sync_members'] inlines = [EnvironmentVariableInline] def sync_members(self, request, queryset): for project in queryset: project.update_members() self.message_user( request, '{} project{} was synced'.format(len(queryset), pluralize(len(queryset))) ) sync_members.short_description = 'Sync members of selected projects' @admin.register(EnvironmentVariable) class EnvironmentVariableAdmin(EnvironmentVariableMixin, admin.ModelAdmin): list_display = ( '__str__', 'is_secret', )
Return empty tuple in get_readonly_fields
## Code Before: from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, obj=None): if obj: return 'key', 'value', 'is_secret' class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline): model = EnvironmentVariable extra = 0 @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): list_display = ('__str__', 'queue_name', 'approved', 'number_of_members', 'average_time', 'last_build_number', 'can_deploy') list_filter = ['owner', 'queue_name', 'approved', 'can_deploy'] actions = ['sync_members'] inlines = [EnvironmentVariableInline] def sync_members(self, request, queryset): for project in queryset: project.update_members() self.message_user( request, '{} project{} was synced'.format(len(queryset), pluralize(len(queryset))) ) sync_members.short_description = 'Sync members of selected projects' @admin.register(EnvironmentVariable) class EnvironmentVariableAdmin(EnvironmentVariableMixin, admin.ModelAdmin): list_display = ( '__str__', 'is_secret', ) ## Instruction: Return empty tuple in get_readonly_fields ## Code After: from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, obj=None): if obj: return 'key', 'value', 'is_secret' return tuple() class EnvironmentVariableInline(EnvironmentVariableMixin, admin.TabularInline): model = EnvironmentVariable extra = 0 @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): list_display = ('__str__', 'queue_name', 'approved', 'number_of_members', 'average_time', 'last_build_number', 'can_deploy') list_filter = ['owner', 'queue_name', 'approved', 'can_deploy'] actions = ['sync_members'] inlines = [EnvironmentVariableInline] def sync_members(self, request, queryset): for project in queryset: project.update_members() self.message_user( request, '{} project{} was synced'.format(len(queryset), pluralize(len(queryset))) ) sync_members.short_description = 'Sync members of selected projects' @admin.register(EnvironmentVariable) class EnvironmentVariableAdmin(EnvironmentVariableMixin, admin.ModelAdmin): list_display = ( '__str__', 'is_secret', )
0d7c0b045c4a2e930fe0d7aa68b96d5a99916a34
scripts/document_path_handlers.py
scripts/document_path_handlers.py
from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the description for all the supported kinds. """) for k in sorted(n.path_handlers.keys()): v = n.path_handlers[k] print(k) print('\n'.join(' '+l.strip() for l in v.__doc__.splitlines())) print()
from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the description for all the supported kinds. .. class:: dl-horizontal """) for k in sorted(n.path_handlers.keys()): v = n.path_handlers[k] print(k) print('\n'.join(' '+l.strip() for l in v.__doc__.splitlines())) print()
Make path handlers list horizontal
Make path handlers list horizontal Signed-off-by: Chris Warrick <de6f931166e131a07f31c96c765aee08f061d1a5@gmail.com>
Python
mit
s2hc-johan/nikola,wcmckee/nikola,gwax/nikola,x1101/nikola,okin/nikola,masayuko/nikola,xuhdev/nikola,wcmckee/nikola,gwax/nikola,knowsuchagency/nikola,atiro/nikola,andredias/nikola,gwax/nikola,xuhdev/nikola,atiro/nikola,x1101/nikola,okin/nikola,knowsuchagency/nikola,wcmckee/nikola,okin/nikola,getnikola/nikola,masayuko/nikola,okin/nikola,getnikola/nikola,masayuko/nikola,andredias/nikola,atiro/nikola,xuhdev/nikola,xuhdev/nikola,s2hc-johan/nikola,getnikola/nikola,knowsuchagency/nikola,getnikola/nikola,x1101/nikola,andredias/nikola,s2hc-johan/nikola
from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the description for all the supported kinds. + .. class:: dl-horizontal """) for k in sorted(n.path_handlers.keys()): v = n.path_handlers[k] print(k) print('\n'.join(' '+l.strip() for l in v.__doc__.splitlines())) print()
Make path handlers list horizontal
## Code Before: from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the description for all the supported kinds. """) for k in sorted(n.path_handlers.keys()): v = n.path_handlers[k] print(k) print('\n'.join(' '+l.strip() for l in v.__doc__.splitlines())) print() ## Instruction: Make path handlers list horizontal ## Code After: from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the description for all the supported kinds. .. class:: dl-horizontal """) for k in sorted(n.path_handlers.keys()): v = n.path_handlers[k] print(k) print('\n'.join(' '+l.strip() for l in v.__doc__.splitlines())) print()
c6d50c3feed444f8f450c5c140e8470c6897f2bf
societies/models.py
societies/models.py
from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the society's url #: ..versionadded:: 0.1 link = models.URLField(max_length=255) #: The country in which the society resides #: .. versionadded:: 0.1 country = CountryField() #: A free form "city" or "region" field used to display where #: exactly the society is within a country #: .. versionadded:: 0.1 region = models.CharField(max_length=512, null=True, default=None, blank=True) def __str__(self): return 'GuitarSociety(name="{}", link="{}")'.format(self.name, self.link)
from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the society's url #: ..versionadded:: 0.1 link = models.URLField(max_length=255) #: The country in which the society resides #: .. versionadded:: 0.1 country = CountryField() #: A free form "city" or "region" field used to display where #: exactly the society is within a country #: .. versionadded:: 0.1 region = models.CharField(max_length=512, null=True, default=None, blank=True) def __str__(self): return self.name def __repr__(self): return 'GuitarSociety("{}")'.format(self.name)
Make the Guitar Society __str__ Method a bit more Logical
Make the Guitar Society __str__ Method a bit more Logical
Python
bsd-3-clause
chrisguitarguy/GuitarSocieties.org,chrisguitarguy/GuitarSocieties.org
from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the society's url #: ..versionadded:: 0.1 link = models.URLField(max_length=255) #: The country in which the society resides #: .. versionadded:: 0.1 country = CountryField() #: A free form "city" or "region" field used to display where #: exactly the society is within a country #: .. versionadded:: 0.1 region = models.CharField(max_length=512, null=True, default=None, blank=True) def __str__(self): - return 'GuitarSociety(name="{}", link="{}")'.format(self.name, self.link) + return self.name + def __repr__(self): + return 'GuitarSociety("{}")'.format(self.name) +
Make the Guitar Society __str__ Method a bit more Logical
## Code Before: from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the society's url #: ..versionadded:: 0.1 link = models.URLField(max_length=255) #: The country in which the society resides #: .. versionadded:: 0.1 country = CountryField() #: A free form "city" or "region" field used to display where #: exactly the society is within a country #: .. versionadded:: 0.1 region = models.CharField(max_length=512, null=True, default=None, blank=True) def __str__(self): return 'GuitarSociety(name="{}", link="{}")'.format(self.name, self.link) ## Instruction: Make the Guitar Society __str__ Method a bit more Logical ## Code After: from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the society's url #: ..versionadded:: 0.1 link = models.URLField(max_length=255) #: The country in which the society resides #: .. versionadded:: 0.1 country = CountryField() #: A free form "city" or "region" field used to display where #: exactly the society is within a country #: .. versionadded:: 0.1 region = models.CharField(max_length=512, null=True, default=None, blank=True) def __str__(self): return self.name def __repr__(self): return 'GuitarSociety("{}")'.format(self.name)
c7a209d2c4455325f1d215ca1c12074b394ae00e
gitdir/host/__init__.py
gitdir/host/__init__.py
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: print('[ ** ] updating {}'.format(repo_dir)) subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))
Add status messages to `gitdir update`
Add status messages to `gitdir update`
Python
mit
fenhl/gitdir
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: + print('[ ** ] updating {}'.format(repo_dir)) subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))
Add status messages to `gitdir update`
## Code Before: import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname)) ## Instruction: Add status messages to `gitdir update` ## Code After: import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not support cloning'.format(self)) @property def dir(self): return gitdir.GITDIR / str(self) def update(self): for repo_dir in self: print('[ ** ] updating {}'.format(repo_dir)) subprocess.check_call(['git', 'pull'], cwd=str(repo_dir / 'master')) def all(): for host_dir in gitdir.GITDIR.iterdir(): yield by_name(host_dir.name) def by_name(hostname): if hostname == 'github.com': import gitdir.host.github return gitdir.host.github.GitHub() else: raise ValueError('Unsupported hostname: {}'.format(hostname))