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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
89225ed0c7ec627ee32fd973d5f1fb95da173be2 | djangae/contrib/locking/memcache.py | djangae/contrib/locking/memcache.py | import random
import time
from datetime import datetime
from django.core.cache import cache
class MemcacheLock(object):
def __init__(self, identifier, cache, unique_value):
self.identifier = identifier
self._cache = cache
self.unique_value = unique_value
@classmethod
def acquire(cls, identifier, wait=True, steal_after_ms=None):
start_time = datetime.utcnow()
unique_value = random.randint(1, 100000)
while True:
acquired = cache.add(identifier, unique_value)
if acquired:
return cls(identifier, cache, unique_value)
elif not wait:
return None
else:
# We are waiting for the lock
if steal_after_ms and (datetime.utcnow() - start_time).total_seconds() * 1000 > steal_after_ms:
# Steal anyway
cache.set(identifier, unique_value)
return cls(identifier, cache, unique_value)
time.sleep(0)
def release(self):
cache = self._cache
# Delete the key if it was ours. There is a race condition here
# if something steals the lock between the if and the delete...
if cache.get(self.identifier) == self.unique_value:
cache.delete(self.identifier)
| import random
import time
from datetime import datetime
from django.core.cache import cache
class MemcacheLock(object):
def __init__(self, identifier, unique_value):
self.identifier = identifier
self.unique_value = unique_value
@classmethod
def acquire(cls, identifier, wait=True, steal_after_ms=None):
start_time = datetime.utcnow()
unique_value = random.randint(1, 100000)
while True:
acquired = cache.add(identifier, unique_value)
if acquired:
return cls(identifier, unique_value)
elif not wait:
return None
else:
# We are waiting for the lock
if steal_after_ms and (datetime.utcnow() - start_time).total_seconds() * 1000 > steal_after_ms:
# Steal anyway
cache.set(identifier, unique_value)
return cls(identifier, unique_value)
time.sleep(0)
def release(self):
# Delete the key if it was ours. There is a race condition here
# if something steals the lock between the if and the delete...
if cache.get(self.identifier) == self.unique_value:
cache.delete(self.identifier)
| Remove pointless `_cache` attribute on MemcacheLock class. | Remove pointless `_cache` attribute on MemcacheLock class.
If this was doing anything useful, I have no idea what it was.
| Python | bsd-3-clause | potatolondon/djangae,potatolondon/djangae | import random
import time
from datetime import datetime
from django.core.cache import cache
class MemcacheLock(object):
- def __init__(self, identifier, cache, unique_value):
+ def __init__(self, identifier, unique_value):
self.identifier = identifier
- self._cache = cache
self.unique_value = unique_value
@classmethod
def acquire(cls, identifier, wait=True, steal_after_ms=None):
start_time = datetime.utcnow()
unique_value = random.randint(1, 100000)
while True:
acquired = cache.add(identifier, unique_value)
if acquired:
- return cls(identifier, cache, unique_value)
+ return cls(identifier, unique_value)
elif not wait:
return None
else:
# We are waiting for the lock
if steal_after_ms and (datetime.utcnow() - start_time).total_seconds() * 1000 > steal_after_ms:
# Steal anyway
cache.set(identifier, unique_value)
- return cls(identifier, cache, unique_value)
+ return cls(identifier, unique_value)
time.sleep(0)
def release(self):
- cache = self._cache
-
# Delete the key if it was ours. There is a race condition here
# if something steals the lock between the if and the delete...
if cache.get(self.identifier) == self.unique_value:
cache.delete(self.identifier)
| Remove pointless `_cache` attribute on MemcacheLock class. | ## Code Before:
import random
import time
from datetime import datetime
from django.core.cache import cache
class MemcacheLock(object):
def __init__(self, identifier, cache, unique_value):
self.identifier = identifier
self._cache = cache
self.unique_value = unique_value
@classmethod
def acquire(cls, identifier, wait=True, steal_after_ms=None):
start_time = datetime.utcnow()
unique_value = random.randint(1, 100000)
while True:
acquired = cache.add(identifier, unique_value)
if acquired:
return cls(identifier, cache, unique_value)
elif not wait:
return None
else:
# We are waiting for the lock
if steal_after_ms and (datetime.utcnow() - start_time).total_seconds() * 1000 > steal_after_ms:
# Steal anyway
cache.set(identifier, unique_value)
return cls(identifier, cache, unique_value)
time.sleep(0)
def release(self):
cache = self._cache
# Delete the key if it was ours. There is a race condition here
# if something steals the lock between the if and the delete...
if cache.get(self.identifier) == self.unique_value:
cache.delete(self.identifier)
## Instruction:
Remove pointless `_cache` attribute on MemcacheLock class.
## Code After:
import random
import time
from datetime import datetime
from django.core.cache import cache
class MemcacheLock(object):
def __init__(self, identifier, unique_value):
self.identifier = identifier
self.unique_value = unique_value
@classmethod
def acquire(cls, identifier, wait=True, steal_after_ms=None):
start_time = datetime.utcnow()
unique_value = random.randint(1, 100000)
while True:
acquired = cache.add(identifier, unique_value)
if acquired:
return cls(identifier, unique_value)
elif not wait:
return None
else:
# We are waiting for the lock
if steal_after_ms and (datetime.utcnow() - start_time).total_seconds() * 1000 > steal_after_ms:
# Steal anyway
cache.set(identifier, unique_value)
return cls(identifier, unique_value)
time.sleep(0)
def release(self):
# Delete the key if it was ours. There is a race condition here
# if something steals the lock between the if and the delete...
if cache.get(self.identifier) == self.unique_value:
cache.delete(self.identifier)
|
a715821c75521e25172805c98d204fc4e24a4641 | CodeFights/circleOfNumbers.py | CodeFights/circleOfNumbers.py |
def circleOfNumbers(n, firstNumber):
pass
def main():
tests = [
["crazy", "dsbaz"],
["z", "a"]
]
for t in tests:
res = circleOfNumbers(t[0], t[1])
if t[2] == res:
print("PASSED: circleOfNumbers({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
def circleOfNumbers(n, firstNumber):
mid = n / 2
return (mid + firstNumber if firstNumber < mid else firstNumber - mid)
def main():
tests = [
[10, 2, 7],
[10, 7, 2],
[4, 1, 3],
[6, 3, 0]
]
for t in tests:
res = circleOfNumbers(t[0], t[1])
if t[2] == res:
print("PASSED: circleOfNumbers({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
| Solve Code Fights circle of numbers problem | Solve Code Fights circle of numbers problem
| Python | mit | HKuz/Test_Code |
def circleOfNumbers(n, firstNumber):
- pass
+ mid = n / 2
+ return (mid + firstNumber if firstNumber < mid else firstNumber - mid)
def main():
tests = [
- ["crazy", "dsbaz"],
- ["z", "a"]
+ [10, 2, 7],
+ [10, 7, 2],
+ [4, 1, 3],
+ [6, 3, 0]
]
for t in tests:
res = circleOfNumbers(t[0], t[1])
if t[2] == res:
print("PASSED: circleOfNumbers({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
| Solve Code Fights circle of numbers problem | ## Code Before:
def circleOfNumbers(n, firstNumber):
pass
def main():
tests = [
["crazy", "dsbaz"],
["z", "a"]
]
for t in tests:
res = circleOfNumbers(t[0], t[1])
if t[2] == res:
print("PASSED: circleOfNumbers({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
## Instruction:
Solve Code Fights circle of numbers problem
## Code After:
def circleOfNumbers(n, firstNumber):
mid = n / 2
return (mid + firstNumber if firstNumber < mid else firstNumber - mid)
def main():
tests = [
[10, 2, 7],
[10, 7, 2],
[4, 1, 3],
[6, 3, 0]
]
for t in tests:
res = circleOfNumbers(t[0], t[1])
if t[2] == res:
print("PASSED: circleOfNumbers({}, {}) returned {}"
.format(t[0], t[1], res))
else:
print("FAILED: circleOfNumbers({}, {}) returned {}, answer: {}"
.format(t[0], t[1], res, t[2]))
if __name__ == '__main__':
main()
|
93a95afe231910d9f683909994692fadaf107057 | readme_renderer/markdown.py | readme_renderer/markdown.py | from __future__ import absolute_import, division, print_function
import markdown
from .clean import clean
def render(raw):
rendered = markdown.markdown(
raw,
extensions=[
'markdown.extensions.codehilite',
'markdown.extensions.fenced_code',
'markdown.extensions.smart_strong',
])
return clean(rendered or raw), bool(rendered)
| from __future__ import absolute_import, division, print_function
import markdown
from .clean import clean
def render(raw):
rendered = markdown.markdown(
raw,
extensions=[
'markdown.extensions.codehilite',
'markdown.extensions.fenced_code',
'markdown.extensions.smart_strong',
])
if rendered:
return clean(rendered)
else:
return None
| Make md.render have the same API as rst.render | Make md.render have the same API as rst.render
| Python | apache-2.0 | pypa/readme,pypa/readme_renderer | from __future__ import absolute_import, division, print_function
import markdown
from .clean import clean
def render(raw):
rendered = markdown.markdown(
raw,
extensions=[
'markdown.extensions.codehilite',
'markdown.extensions.fenced_code',
'markdown.extensions.smart_strong',
])
- return clean(rendered or raw), bool(rendered)
+ if rendered:
+ return clean(rendered)
+ else:
+ return None
| Make md.render have the same API as rst.render | ## Code Before:
from __future__ import absolute_import, division, print_function
import markdown
from .clean import clean
def render(raw):
rendered = markdown.markdown(
raw,
extensions=[
'markdown.extensions.codehilite',
'markdown.extensions.fenced_code',
'markdown.extensions.smart_strong',
])
return clean(rendered or raw), bool(rendered)
## Instruction:
Make md.render have the same API as rst.render
## Code After:
from __future__ import absolute_import, division, print_function
import markdown
from .clean import clean
def render(raw):
rendered = markdown.markdown(
raw,
extensions=[
'markdown.extensions.codehilite',
'markdown.extensions.fenced_code',
'markdown.extensions.smart_strong',
])
if rendered:
return clean(rendered)
else:
return None
|
22b697729d1ee43d322aa1187b3a5f6101f836a5 | odin/__init__.py | odin/__init__.py | __authors__ = "Tim Savage"
__author_email__ = "tim@savage.company"
__copyright__ = "Copyright (C) 2014 Tim Savage"
__version__ = "1.0"
# Disable logging if an explicit handler is not added
try:
import logging
logging.getLogger('odin').addHandler(logging.NullHandler())
except AttributeError:
pass # Fallback for python 2.6
from odin.fields import * # noqa
from odin.fields.composite import * # noqa
from odin.fields.virtual import * # noqa
from odin.mapping import * # noqa
from odin.resources import Resource # noqa
from odin.adapters import ResourceAdapter # noqa
| import logging
logging.getLogger('odin.registration').addHandler(logging.NullHandler())
__authors__ = "Tim Savage"
__author_email__ = "tim@savage.company"
__copyright__ = "Copyright (C) 2014 Tim Savage"
__version__ = "1.0"
from odin.fields import * # noqa
from odin.fields.composite import * # noqa
from odin.fields.virtual import * # noqa
from odin.mapping import * # noqa
from odin.resources import Resource # noqa
from odin.adapters import ResourceAdapter # noqa
| Remove Python 2.6 backwards compatibility | Remove Python 2.6 backwards compatibility
| Python | bsd-3-clause | python-odin/odin | + import logging
+ logging.getLogger('odin.registration').addHandler(logging.NullHandler())
+
__authors__ = "Tim Savage"
__author_email__ = "tim@savage.company"
__copyright__ = "Copyright (C) 2014 Tim Savage"
__version__ = "1.0"
-
- # Disable logging if an explicit handler is not added
- try:
- import logging
- logging.getLogger('odin').addHandler(logging.NullHandler())
- except AttributeError:
- pass # Fallback for python 2.6
from odin.fields import * # noqa
from odin.fields.composite import * # noqa
from odin.fields.virtual import * # noqa
from odin.mapping import * # noqa
from odin.resources import Resource # noqa
from odin.adapters import ResourceAdapter # noqa
| Remove Python 2.6 backwards compatibility | ## Code Before:
__authors__ = "Tim Savage"
__author_email__ = "tim@savage.company"
__copyright__ = "Copyright (C) 2014 Tim Savage"
__version__ = "1.0"
# Disable logging if an explicit handler is not added
try:
import logging
logging.getLogger('odin').addHandler(logging.NullHandler())
except AttributeError:
pass # Fallback for python 2.6
from odin.fields import * # noqa
from odin.fields.composite import * # noqa
from odin.fields.virtual import * # noqa
from odin.mapping import * # noqa
from odin.resources import Resource # noqa
from odin.adapters import ResourceAdapter # noqa
## Instruction:
Remove Python 2.6 backwards compatibility
## Code After:
import logging
logging.getLogger('odin.registration').addHandler(logging.NullHandler())
__authors__ = "Tim Savage"
__author_email__ = "tim@savage.company"
__copyright__ = "Copyright (C) 2014 Tim Savage"
__version__ = "1.0"
from odin.fields import * # noqa
from odin.fields.composite import * # noqa
from odin.fields.virtual import * # noqa
from odin.mapping import * # noqa
from odin.resources import Resource # noqa
from odin.adapters import ResourceAdapter # noqa
|
59daf205869c42b3797aa9dbaaa97930cbca2417 | nanshe_workflow/ipy.py | nanshe_workflow/ipy.py | __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Nov 10, 2015 17:09$"
try:
from IPython.utils.shimmodule import ShimWarning
except ImportError:
class ShimWarning(Warning):
"""Warning issued by IPython 4.x regarding deprecated API."""
pass
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error', '', ShimWarning)
try:
# IPython 3
from IPython.html.widgets import FloatProgress
from IPython.parallel import Client
except ShimWarning:
# IPython 4
from ipywidgets import FloatProgress
from ipyparallel import Client
from IPython.display import display
| __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Nov 10, 2015 17:09$"
import json
import re
try:
from IPython.utils.shimmodule import ShimWarning
except ImportError:
class ShimWarning(Warning):
"""Warning issued by IPython 4.x regarding deprecated API."""
pass
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error', '', ShimWarning)
try:
# IPython 3
from IPython.html.widgets import FloatProgress
from IPython.parallel import Client
except ShimWarning:
# IPython 4
from ipywidgets import FloatProgress
from ipyparallel import Client
from IPython.display import display
import ipykernel
import notebook.notebookapp
import requests
def check_nbserverproxy():
"""
Return the url of the current jupyter notebook server.
"""
kernel_id = re.search(
"kernel-(.*).json",
ipykernel.connect.get_connection_file()
).group(1)
servers = notebook.notebookapp.list_running_servers()
for s in servers:
response = requests.get(
requests.compat.urljoin(s["url"], "api/sessions"),
params={"token": s.get("token", "")}
)
for n in json.loads(response.text):
if n["kernel"]["id"] == kernel_id:
# Found server that is running this Jupyter Notebook.
# Try to requests this servers port through nbserverproxy.
url = requests.compat.urljoin(
s["url"], "proxy/%i" % s["port"]
)
# If the proxy is running, it will redirect.
# If not, it will error out.
try:
requests.get(url).raise_for_status()
except requests.HTTPError:
return False
else:
return True
| Add function to check if nbserverproxy is running | Add function to check if nbserverproxy is running
Provides a simple check to see if the `nbserverproxy` is installed and
running. As this is a Jupyter server extension and this code is run from
the notebook, we can't simply import `nbserverproxy`. In fact that
wouldn't even work when using the Python 2 kernel even though the proxy
server could be running.
Instead to solve this problem try to identify the Jupyter Notebook
server we are running under. Once identified, attempt to query the proxy
server with the port of the Jupyter Notebook server. If the proxy server
is running, this will merely redirect to the Jupyter Notebook server and
return an HTTP 200 status. However if the proxy server is not running,
this will return a HTTP 404 error. There may be other errors that it
could raise. In any event, if the proxy redirects us, we know it is
working and if not we know it doesn't work.
| Python | apache-2.0 | nanshe-org/nanshe_workflow,DudLab/nanshe_workflow | __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Nov 10, 2015 17:09$"
+
+ import json
+ import re
try:
from IPython.utils.shimmodule import ShimWarning
except ImportError:
class ShimWarning(Warning):
"""Warning issued by IPython 4.x regarding deprecated API."""
pass
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error', '', ShimWarning)
try:
# IPython 3
from IPython.html.widgets import FloatProgress
from IPython.parallel import Client
except ShimWarning:
# IPython 4
from ipywidgets import FloatProgress
from ipyparallel import Client
from IPython.display import display
+ import ipykernel
+ import notebook.notebookapp
+
+ import requests
+
+
+ def check_nbserverproxy():
+ """
+ Return the url of the current jupyter notebook server.
+ """
+ kernel_id = re.search(
+ "kernel-(.*).json",
+ ipykernel.connect.get_connection_file()
+ ).group(1)
+ servers = notebook.notebookapp.list_running_servers()
+ for s in servers:
+ response = requests.get(
+ requests.compat.urljoin(s["url"], "api/sessions"),
+ params={"token": s.get("token", "")}
+ )
+ for n in json.loads(response.text):
+ if n["kernel"]["id"] == kernel_id:
+ # Found server that is running this Jupyter Notebook.
+ # Try to requests this servers port through nbserverproxy.
+ url = requests.compat.urljoin(
+ s["url"], "proxy/%i" % s["port"]
+ )
+ # If the proxy is running, it will redirect.
+ # If not, it will error out.
+ try:
+ requests.get(url).raise_for_status()
+ except requests.HTTPError:
+ return False
+ else:
+ return True
+ | Add function to check if nbserverproxy is running | ## Code Before:
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Nov 10, 2015 17:09$"
try:
from IPython.utils.shimmodule import ShimWarning
except ImportError:
class ShimWarning(Warning):
"""Warning issued by IPython 4.x regarding deprecated API."""
pass
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error', '', ShimWarning)
try:
# IPython 3
from IPython.html.widgets import FloatProgress
from IPython.parallel import Client
except ShimWarning:
# IPython 4
from ipywidgets import FloatProgress
from ipyparallel import Client
from IPython.display import display
## Instruction:
Add function to check if nbserverproxy is running
## Code After:
__author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>"
__date__ = "$Nov 10, 2015 17:09$"
import json
import re
try:
from IPython.utils.shimmodule import ShimWarning
except ImportError:
class ShimWarning(Warning):
"""Warning issued by IPython 4.x regarding deprecated API."""
pass
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error', '', ShimWarning)
try:
# IPython 3
from IPython.html.widgets import FloatProgress
from IPython.parallel import Client
except ShimWarning:
# IPython 4
from ipywidgets import FloatProgress
from ipyparallel import Client
from IPython.display import display
import ipykernel
import notebook.notebookapp
import requests
def check_nbserverproxy():
"""
Return the url of the current jupyter notebook server.
"""
kernel_id = re.search(
"kernel-(.*).json",
ipykernel.connect.get_connection_file()
).group(1)
servers = notebook.notebookapp.list_running_servers()
for s in servers:
response = requests.get(
requests.compat.urljoin(s["url"], "api/sessions"),
params={"token": s.get("token", "")}
)
for n in json.loads(response.text):
if n["kernel"]["id"] == kernel_id:
# Found server that is running this Jupyter Notebook.
# Try to requests this servers port through nbserverproxy.
url = requests.compat.urljoin(
s["url"], "proxy/%i" % s["port"]
)
# If the proxy is running, it will redirect.
# If not, it will error out.
try:
requests.get(url).raise_for_status()
except requests.HTTPError:
return False
else:
return True
|
c35e004ae3b2b9b8338673078f8ee523ac79e005 | alg_shell_sort.py | alg_shell_sort.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _gap_insertion_sort(a_list, start, gap):
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while (position >= gap) and (a_list[position - gap] > current_value):
a_list[position] = a_list[position - gap]
position = position - gap
a_list[position] = current_value
def shell_sort(a_list):
"""Shell Sort algortihm."""
sublist_count = len(a_list) // 2
while sublist_count > 0:
for start_pos in range(sublist_count):
_gap_insertion_sort(a_list, start_pos, sublist_count)
print('After increments of size {0}, a_list is \n{1}'
.format(sublist_count, a_list))
sublist_count = sublist_count // 2
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: \n{}'.format(a_list))
print('By Shell Sort: ')
shell_sort(a_list)
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _gap_insertion_sort(a_list, start, gap):
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while (position >= gap) and (a_list[position - gap] > current_value):
a_list[position] = a_list[position - gap]
position = position - gap
a_list[position] = current_value
def shell_sort(a_list):
"""Shell Sort algortihm."""
sublist_count = len(a_list) // 2
while sublist_count > 0:
for start_pos in range(sublist_count):
_gap_insertion_sort(a_list, start_pos, sublist_count)
print('After increments of size {0}:\n{1}'
.format(sublist_count, a_list))
sublist_count = sublist_count // 2
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By Shell Sort: ')
shell_sort(a_list)
if __name__ == '__main__':
main()
| Revise print() in shell_sort() & main() | Revise print() in shell_sort() & main()
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _gap_insertion_sort(a_list, start, gap):
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while (position >= gap) and (a_list[position - gap] > current_value):
a_list[position] = a_list[position - gap]
position = position - gap
a_list[position] = current_value
def shell_sort(a_list):
"""Shell Sort algortihm."""
sublist_count = len(a_list) // 2
while sublist_count > 0:
for start_pos in range(sublist_count):
_gap_insertion_sort(a_list, start_pos, sublist_count)
- print('After increments of size {0}, a_list is \n{1}'
+ print('After increments of size {0}:\n{1}'
.format(sublist_count, a_list))
sublist_count = sublist_count // 2
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
- print('a_list: \n{}'.format(a_list))
+ print('a_list: {}'.format(a_list))
print('By Shell Sort: ')
shell_sort(a_list)
if __name__ == '__main__':
main()
| Revise print() in shell_sort() & main() | ## Code Before:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _gap_insertion_sort(a_list, start, gap):
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while (position >= gap) and (a_list[position - gap] > current_value):
a_list[position] = a_list[position - gap]
position = position - gap
a_list[position] = current_value
def shell_sort(a_list):
"""Shell Sort algortihm."""
sublist_count = len(a_list) // 2
while sublist_count > 0:
for start_pos in range(sublist_count):
_gap_insertion_sort(a_list, start_pos, sublist_count)
print('After increments of size {0}, a_list is \n{1}'
.format(sublist_count, a_list))
sublist_count = sublist_count // 2
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: \n{}'.format(a_list))
print('By Shell Sort: ')
shell_sort(a_list)
if __name__ == '__main__':
main()
## Instruction:
Revise print() in shell_sort() & main()
## Code After:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _gap_insertion_sort(a_list, start, gap):
for i in range(start + gap, len(a_list), gap):
current_value = a_list[i]
position = i
while (position >= gap) and (a_list[position - gap] > current_value):
a_list[position] = a_list[position - gap]
position = position - gap
a_list[position] = current_value
def shell_sort(a_list):
"""Shell Sort algortihm."""
sublist_count = len(a_list) // 2
while sublist_count > 0:
for start_pos in range(sublist_count):
_gap_insertion_sort(a_list, start_pos, sublist_count)
print('After increments of size {0}:\n{1}'
.format(sublist_count, a_list))
sublist_count = sublist_count // 2
def main():
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print('a_list: {}'.format(a_list))
print('By Shell Sort: ')
shell_sort(a_list)
if __name__ == '__main__':
main()
|
29061254e99f8e02e8285c3ebc965866c8c9d378 | testing/chess_engine_fight.py | testing/chess_engine_fight.py |
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
|
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
if os.path.isfile(game_file):
print('Could not delete output file:', game_file)
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
| Check that engine fight files are deleted before test | Check that engine fight files are deleted before test
| Python | mit | MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess |
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
+
+ if os.path.isfile(game_file):
+ print('Could not delete output file:', game_file)
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
| Check that engine fight files are deleted before test | ## Code Before:
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
## Instruction:
Check that engine fight files are deleted before test
## Code After:
import subprocess, os, sys
if len(sys.argv) < 2:
print('Must specify file names of 2 chess engines')
for i in range(len(sys.argv)):
print(str(i) + ': ' + sys.argv[i])
sys.exit(1)
generator = './' + sys.argv[-2]
checker = './' + sys.argv[-1]
game_file = 'game.pgn'
count = 0
while True:
try:
os.remove(game_file)
except OSError:
pass
if os.path.isfile(game_file):
print('Could not delete output file:', game_file)
count += 1
print('Game #' + str(count))
out = subprocess.run([generator, '-random', '-random'])
if not os.path.isfile(game_file):
print('Game file not produced: ' + game_file)
print('generator = ' + generator)
print(out.returncode)
print(out.stdout)
print(out.stderr)
sys.exit()
result = subprocess.run([checker, '-confirm', game_file])
if result.returncode != 0:
print('Found discrepancy. See ' + game_file)
print('generator = ' + generator)
print('checker = ' + checker)
sys.exit()
generator, checker = checker, generator
|
2a724872cba5c48ddbd336f06460aa2ad851c6d0 | Pilot3/P3B5/p3b5.py | Pilot3/P3B5/p3b5.py | import os
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unrolled',
'batch_size',
'epochs',
]
class BenchmarkP3B5(candle.Benchmark):
""" Benchmark for P3B5 """
def set_locals(self):
""" Set parameters for the benchmark.
Args:
required: set of required parameters for the benchmark.
"""
if REQUIRED is not None:
self.required = set(REQUIRED)
| import os
import sys
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unrolled',
'batch_size',
'epochs',
]
class BenchmarkP3B5(candle.Benchmark):
""" Benchmark for P3B5 """
def set_locals(self):
""" Set parameters for the benchmark.
Args:
required: set of required parameters for the benchmark.
"""
if REQUIRED is not None:
self.required = set(REQUIRED)
| Fix missing import for sys | Fix missing import for sys
| Python | mit | ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks,ECP-CANDLE/Benchmarks | import os
+ import sys
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unrolled',
'batch_size',
'epochs',
]
class BenchmarkP3B5(candle.Benchmark):
""" Benchmark for P3B5 """
def set_locals(self):
""" Set parameters for the benchmark.
Args:
required: set of required parameters for the benchmark.
"""
if REQUIRED is not None:
self.required = set(REQUIRED)
| Fix missing import for sys | ## Code Before:
import os
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unrolled',
'batch_size',
'epochs',
]
class BenchmarkP3B5(candle.Benchmark):
""" Benchmark for P3B5 """
def set_locals(self):
""" Set parameters for the benchmark.
Args:
required: set of required parameters for the benchmark.
"""
if REQUIRED is not None:
self.required = set(REQUIRED)
## Instruction:
Fix missing import for sys
## Code After:
import os
import sys
import candle
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
REQUIRED = [
'learning_rate',
'learning_rate_min',
'momentum',
'weight_decay',
'grad_clip',
'seed',
'unrolled',
'batch_size',
'epochs',
]
class BenchmarkP3B5(candle.Benchmark):
""" Benchmark for P3B5 """
def set_locals(self):
""" Set parameters for the benchmark.
Args:
required: set of required parameters for the benchmark.
"""
if REQUIRED is not None:
self.required = set(REQUIRED)
|
7729c90679a74f268d7b0fd88c954fb583830794 | parser.py | parser.py | import webquery
from lxml import etree
import inspect
from expression import Expression
from collections import defaultdict
class Parser(object):
registry = defaultdict(dict)
@classmethod
def __init_subclass__(cls):
for name, member in inspect.getmembers(cls):
if isinstance(member, Expression):
cls.registry[cls.__name__][name] = member
@property
def fields(self):
cls = self.__class__
return cls.registry[cls.__name__]
def parse(self, url):
content = webquery.urlcontent(url)
root = etree.HTML(content, base_url=url)
data = {name: expr.parse(root) for name, expr in self.fields.items()}
data['url'] = url
return data
| import webquery
from lxml import etree
import inspect
from expression import Expression
from collections import defaultdict
class Parser(object):
registry = defaultdict(dict)
@classmethod
def __init_subclass__(cls):
for name, member in inspect.getmembers(cls):
if isinstance(member, Expression):
cls.registry[cls.__name__][name] = member
@property
def fields(self):
cls = self.__class__
return cls.registry[cls.__name__]
def canonical_url(self, url):
"""By overriding this method canonical url can be used"""
return url
def parse(self, url):
canonical_url = self.canonical_url(url)
content = webquery.urlcontent(canonical_url)
root = etree.HTML(content, base_url=canonical_url)
data = {name: expr.parse(root) for name, expr in self.fields.items()}
data['url'] = canonical_url
return data
| Add ability to customize URL | Add ability to customize URL
| Python | apache-2.0 | shiplu/webxpath | import webquery
from lxml import etree
import inspect
from expression import Expression
from collections import defaultdict
class Parser(object):
registry = defaultdict(dict)
@classmethod
def __init_subclass__(cls):
for name, member in inspect.getmembers(cls):
if isinstance(member, Expression):
cls.registry[cls.__name__][name] = member
@property
def fields(self):
cls = self.__class__
return cls.registry[cls.__name__]
+ def canonical_url(self, url):
+ """By overriding this method canonical url can be used"""
+ return url
+
def parse(self, url):
+ canonical_url = self.canonical_url(url)
- content = webquery.urlcontent(url)
+ content = webquery.urlcontent(canonical_url)
- root = etree.HTML(content, base_url=url)
+ root = etree.HTML(content, base_url=canonical_url)
data = {name: expr.parse(root) for name, expr in self.fields.items()}
- data['url'] = url
+ data['url'] = canonical_url
return data
| Add ability to customize URL | ## Code Before:
import webquery
from lxml import etree
import inspect
from expression import Expression
from collections import defaultdict
class Parser(object):
registry = defaultdict(dict)
@classmethod
def __init_subclass__(cls):
for name, member in inspect.getmembers(cls):
if isinstance(member, Expression):
cls.registry[cls.__name__][name] = member
@property
def fields(self):
cls = self.__class__
return cls.registry[cls.__name__]
def parse(self, url):
content = webquery.urlcontent(url)
root = etree.HTML(content, base_url=url)
data = {name: expr.parse(root) for name, expr in self.fields.items()}
data['url'] = url
return data
## Instruction:
Add ability to customize URL
## Code After:
import webquery
from lxml import etree
import inspect
from expression import Expression
from collections import defaultdict
class Parser(object):
registry = defaultdict(dict)
@classmethod
def __init_subclass__(cls):
for name, member in inspect.getmembers(cls):
if isinstance(member, Expression):
cls.registry[cls.__name__][name] = member
@property
def fields(self):
cls = self.__class__
return cls.registry[cls.__name__]
def canonical_url(self, url):
"""By overriding this method canonical url can be used"""
return url
def parse(self, url):
canonical_url = self.canonical_url(url)
content = webquery.urlcontent(canonical_url)
root = etree.HTML(content, base_url=canonical_url)
data = {name: expr.parse(root) for name, expr in self.fields.items()}
data['url'] = canonical_url
return data
|
b6813731696a03e04367ea3286092320391080e9 | puresnmp/__init__.py | puresnmp/__init__.py |
from x690.types import ObjectIdentifier
# !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP
# Types and thus populates the Registry. If this is not included, Non x.690
# SNMP types will not be properly detected!
import puresnmp.types
from puresnmp.api.pythonic import PyWrapper
from puresnmp.api.raw import Client
from puresnmp.credentials import V1, V2C, V3
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata # type: ignore
__version__ = importlib_metadata.version("puresnmp")
__all__ = [
"Client",
"ObjectIdentifier",
"PyWrapper",
"V1",
"V2C",
"V3",
"__version__",
]
|
from x690.types import ObjectIdentifier
# !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP
# Types and thus populates the Registry. If this is not included, Non x.690
# SNMP types will not be properly detected!
import puresnmp.types
from puresnmp.api.pythonic import PyWrapper
from puresnmp.api.raw import Client
from puresnmp.credentials import V1, V2C, V3
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata # type: ignore
__version__ = importlib_metadata.version("puresnmp") # type: ignore
__all__ = [
"Client",
"ObjectIdentifier",
"PyWrapper",
"V1",
"V2C",
"V3",
"__version__",
]
| Fix false-positive of a type-check | Fix false-positive of a type-check
| Python | mit | exhuma/puresnmp,exhuma/puresnmp |
from x690.types import ObjectIdentifier
# !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP
# Types and thus populates the Registry. If this is not included, Non x.690
# SNMP types will not be properly detected!
import puresnmp.types
from puresnmp.api.pythonic import PyWrapper
from puresnmp.api.raw import Client
from puresnmp.credentials import V1, V2C, V3
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata # type: ignore
- __version__ = importlib_metadata.version("puresnmp")
+ __version__ = importlib_metadata.version("puresnmp") # type: ignore
__all__ = [
"Client",
"ObjectIdentifier",
"PyWrapper",
"V1",
"V2C",
"V3",
"__version__",
]
| Fix false-positive of a type-check | ## Code Before:
from x690.types import ObjectIdentifier
# !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP
# Types and thus populates the Registry. If this is not included, Non x.690
# SNMP types will not be properly detected!
import puresnmp.types
from puresnmp.api.pythonic import PyWrapper
from puresnmp.api.raw import Client
from puresnmp.credentials import V1, V2C, V3
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata # type: ignore
__version__ = importlib_metadata.version("puresnmp")
__all__ = [
"Client",
"ObjectIdentifier",
"PyWrapper",
"V1",
"V2C",
"V3",
"__version__",
]
## Instruction:
Fix false-positive of a type-check
## Code After:
from x690.types import ObjectIdentifier
# !!! DO NOT REMOVE !!! The following import triggers the processing of SNMP
# Types and thus populates the Registry. If this is not included, Non x.690
# SNMP types will not be properly detected!
import puresnmp.types
from puresnmp.api.pythonic import PyWrapper
from puresnmp.api.raw import Client
from puresnmp.credentials import V1, V2C, V3
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata # type: ignore
__version__ = importlib_metadata.version("puresnmp") # type: ignore
__all__ = [
"Client",
"ObjectIdentifier",
"PyWrapper",
"V1",
"V2C",
"V3",
"__version__",
]
|
030e64d7aee6c3f0b3a0d0508ac1d5ece0bf4a40 | astroquery/fermi/__init__.py | astroquery/fermi/__init__.py | from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
| from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
del ConfigurationItem # clean up namespace - prevents doc warnings
| Clean up namespace to get rid of sphinx warnings | Clean up namespace to get rid of sphinx warnings
| Python | bsd-3-clause | imbasimba/astroquery,imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery | from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
+ del ConfigurationItem # clean up namespace - prevents doc warnings
+ | Clean up namespace to get rid of sphinx warnings | ## Code Before:
from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
## Instruction:
Clean up namespace to get rid of sphinx warnings
## Code After:
from astropy.config import ConfigurationItem
FERMI_URL = ConfigurationItem('fermi_url',
['http://fermi.gsfc.nasa.gov/cgi-bin/ssc/LAT/LATDataQuery.cgi'],
"Fermi query URL")
FERMI_TIMEOUT = ConfigurationItem('timeout', 60, 'time limit for connecting to FERMI server')
FERMI_RETRIEVAL_TIMEOUT = ConfigurationItem('retrieval_timeout', 120, 'time limit for retrieving a data file once it has been located')
from .core import FermiLAT, GetFermilatDatafile, get_fermilat_datafile
import warnings
warnings.warn("Experimental: Fermi-LAT has not yet been refactored to have its API match the rest of astroquery.")
del ConfigurationItem # clean up namespace - prevents doc warnings
|
ef98ba0f2aa660b85a4116d46679bf30321f2a05 | scipy/spatial/transform/__init__.py | scipy/spatial/transform/__init__.py | from __future__ import division, print_function, absolute_import
from .rotation import Rotation, Slerp
from ._rotation_spline import RotationSpline
__all__ = ['Rotation', 'Slerp']
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
| from __future__ import division, print_function, absolute_import
from .rotation import Rotation, Slerp
from ._rotation_spline import RotationSpline
__all__ = ['Rotation', 'Slerp', 'RotationSpline']
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
| Add RotationSpline into __all__ of spatial.transform | MAINT: Add RotationSpline into __all__ of spatial.transform
| Python | bsd-3-clause | grlee77/scipy,pizzathief/scipy,endolith/scipy,Eric89GXL/scipy,gertingold/scipy,aeklant/scipy,anntzer/scipy,tylerjereddy/scipy,ilayn/scipy,scipy/scipy,matthew-brett/scipy,jor-/scipy,endolith/scipy,ilayn/scipy,person142/scipy,Eric89GXL/scipy,nmayorov/scipy,lhilt/scipy,arokem/scipy,endolith/scipy,ilayn/scipy,WarrenWeckesser/scipy,gertingold/scipy,e-q/scipy,vigna/scipy,arokem/scipy,perimosocordiae/scipy,Eric89GXL/scipy,jor-/scipy,zerothi/scipy,anntzer/scipy,lhilt/scipy,zerothi/scipy,jor-/scipy,anntzer/scipy,Stefan-Endres/scipy,tylerjereddy/scipy,arokem/scipy,zerothi/scipy,gertingold/scipy,aarchiba/scipy,Eric89GXL/scipy,WarrenWeckesser/scipy,ilayn/scipy,lhilt/scipy,vigna/scipy,e-q/scipy,arokem/scipy,perimosocordiae/scipy,lhilt/scipy,mdhaber/scipy,e-q/scipy,grlee77/scipy,nmayorov/scipy,rgommers/scipy,mdhaber/scipy,person142/scipy,aeklant/scipy,endolith/scipy,anntzer/scipy,Stefan-Endres/scipy,matthew-brett/scipy,WarrenWeckesser/scipy,jor-/scipy,aeklant/scipy,scipy/scipy,tylerjereddy/scipy,Eric89GXL/scipy,andyfaff/scipy,scipy/scipy,perimosocordiae/scipy,aeklant/scipy,mdhaber/scipy,WarrenWeckesser/scipy,scipy/scipy,jamestwebber/scipy,jamestwebber/scipy,Stefan-Endres/scipy,jamestwebber/scipy,aarchiba/scipy,pizzathief/scipy,person142/scipy,mdhaber/scipy,matthew-brett/scipy,lhilt/scipy,rgommers/scipy,e-q/scipy,pizzathief/scipy,zerothi/scipy,rgommers/scipy,andyfaff/scipy,vigna/scipy,rgommers/scipy,anntzer/scipy,matthew-brett/scipy,WarrenWeckesser/scipy,aarchiba/scipy,aarchiba/scipy,Stefan-Endres/scipy,arokem/scipy,rgommers/scipy,tylerjereddy/scipy,jamestwebber/scipy,e-q/scipy,person142/scipy,ilayn/scipy,ilayn/scipy,jamestwebber/scipy,aeklant/scipy,andyfaff/scipy,scipy/scipy,Stefan-Endres/scipy,scipy/scipy,vigna/scipy,Eric89GXL/scipy,grlee77/scipy,pizzathief/scipy,andyfaff/scipy,gertingold/scipy,andyfaff/scipy,anntzer/scipy,vigna/scipy,perimosocordiae/scipy,grlee77/scipy,grlee77/scipy,andyfaff/scipy,WarrenWeckesser/scipy,perimosocordiae/scipy,aarchiba/scipy,endolith/scipy,zerothi/scipy,zerothi/scipy,nmayorov/scipy,gertingold/scipy,mdhaber/scipy,Stefan-Endres/scipy,matthew-brett/scipy,jor-/scipy,pizzathief/scipy,tylerjereddy/scipy,perimosocordiae/scipy,mdhaber/scipy,nmayorov/scipy,nmayorov/scipy,endolith/scipy,person142/scipy | from __future__ import division, print_function, absolute_import
from .rotation import Rotation, Slerp
from ._rotation_spline import RotationSpline
- __all__ = ['Rotation', 'Slerp']
+ __all__ = ['Rotation', 'Slerp', 'RotationSpline']
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
| Add RotationSpline into __all__ of spatial.transform | ## Code Before:
from __future__ import division, print_function, absolute_import
from .rotation import Rotation, Slerp
from ._rotation_spline import RotationSpline
__all__ = ['Rotation', 'Slerp']
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
## Instruction:
Add RotationSpline into __all__ of spatial.transform
## Code After:
from __future__ import division, print_function, absolute_import
from .rotation import Rotation, Slerp
from ._rotation_spline import RotationSpline
__all__ = ['Rotation', 'Slerp', 'RotationSpline']
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester
|
4c85300c5458053ac08a393b00513c80baf28031 | reqon/deprecated/__init__.py | reqon/deprecated/__init__.py | import rethinkdb as r
from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError
def query(query):
try:
reql = r.db(query['$db']).table(query['$table'])
except KeyError:
try:
reql = r.table(query['$table'])
except KeyError:
raise ReqonError('The query descriptor requires a $table key.')
return build_terms(query['$query'], reql)
def build_terms(reql, query):
for sequence in query:
term = sequence[0]
try:
reql = TERMS[term](reql, *sequence[1:])
except ReqonError:
raise
except r.ReqlError:
message = 'Invalid values for {0} with args {1}'
raise ReqonError(message.format(term, sequence[1:]))
except Exception:
message = 'Unknown exception, {0}: {1}'
raise ReqonError(message.format(term, sequence[1:]))
return reql
| import rethinkdb as r
from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError
def query(query):
try:
reql = r.db(query['$db']).table(query['$table'])
except KeyError:
try:
reql = r.table(query['$table'])
except KeyError:
raise ReqonError('The query descriptor requires a $table key.')
return build_terms(reql, query['$query'])
def build_terms(reql, query):
for sequence in query:
term = sequence[0]
try:
reql = TERMS[term](reql, *sequence[1:])
except ReqonError:
raise
except r.ReqlError:
message = 'Invalid values for {0} with args {1}'
raise ReqonError(message.format(term, sequence[1:]))
except Exception:
message = 'Unknown exception, {0}: {1}'
raise ReqonError(message.format(term, sequence[1:]))
return reql
| Fix arguments order of reqon.deprecated.build_terms(). | Fix arguments order of reqon.deprecated.build_terms().
| Python | mit | dmpayton/reqon | import rethinkdb as r
from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError
def query(query):
try:
reql = r.db(query['$db']).table(query['$table'])
except KeyError:
try:
reql = r.table(query['$table'])
except KeyError:
raise ReqonError('The query descriptor requires a $table key.')
- return build_terms(query['$query'], reql)
+ return build_terms(reql, query['$query'])
def build_terms(reql, query):
for sequence in query:
term = sequence[0]
try:
reql = TERMS[term](reql, *sequence[1:])
except ReqonError:
raise
except r.ReqlError:
message = 'Invalid values for {0} with args {1}'
raise ReqonError(message.format(term, sequence[1:]))
except Exception:
message = 'Unknown exception, {0}: {1}'
raise ReqonError(message.format(term, sequence[1:]))
return reql
| Fix arguments order of reqon.deprecated.build_terms(). | ## Code Before:
import rethinkdb as r
from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError
def query(query):
try:
reql = r.db(query['$db']).table(query['$table'])
except KeyError:
try:
reql = r.table(query['$table'])
except KeyError:
raise ReqonError('The query descriptor requires a $table key.')
return build_terms(query['$query'], reql)
def build_terms(reql, query):
for sequence in query:
term = sequence[0]
try:
reql = TERMS[term](reql, *sequence[1:])
except ReqonError:
raise
except r.ReqlError:
message = 'Invalid values for {0} with args {1}'
raise ReqonError(message.format(term, sequence[1:]))
except Exception:
message = 'Unknown exception, {0}: {1}'
raise ReqonError(message.format(term, sequence[1:]))
return reql
## Instruction:
Fix arguments order of reqon.deprecated.build_terms().
## Code After:
import rethinkdb as r
from . import coerce, geo, operators, terms
from .coerce import COERSIONS
from .operators import BOOLEAN, EXPRESSIONS, MODIFIERS
from .terms import TERMS
from .exceptions import ReqonError, InvalidTypeError, InvalidFilterError
def query(query):
try:
reql = r.db(query['$db']).table(query['$table'])
except KeyError:
try:
reql = r.table(query['$table'])
except KeyError:
raise ReqonError('The query descriptor requires a $table key.')
return build_terms(reql, query['$query'])
def build_terms(reql, query):
for sequence in query:
term = sequence[0]
try:
reql = TERMS[term](reql, *sequence[1:])
except ReqonError:
raise
except r.ReqlError:
message = 'Invalid values for {0} with args {1}'
raise ReqonError(message.format(term, sequence[1:]))
except Exception:
message = 'Unknown exception, {0}: {1}'
raise ReqonError(message.format(term, sequence[1:]))
return reql
|
05715aca84152c78cf0b4d5d7b751ecfa3a9f35a | tinyblog/views/__init__.py | tinyblog/views/__init__.py | from datetime import datetime
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.generic import (
ArchiveIndexView,
YearArchiveView,
MonthArchiveView,
)
from tinyblog.models import Post
def post(request, year, month, slug):
post = get_object_or_404(Post, created__year=year, created__month=month,
slug=slug)
if post.created > datetime.now():
if not request.user.is_staff:
raise Http404
return render_to_response('tinyblog/post.html',
{'post': post},
context_instance=RequestContext(request))
class TinyBlogIndexView(ArchiveIndexView):
date_field = 'created'
def get_queryset(self):
return Post.published_objects.all()
index_view = TinyBlogIndexView.as_view()
class TinyBlogYearView(YearArchiveView):
date_field = 'created'
make_object_list = True
def get_queryset(self):
return Post.published_objects.all()
year_view = TinyBlogYearView.as_view()
class TinyBlogMonthView(MonthArchiveView):
date_field = 'created'
month_format = '%m'
def get_queryset(self):
return Post.published_objects.all()
month_view = TinyBlogMonthView.as_view()
| from datetime import datetime
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.views.generic import (
ArchiveIndexView,
YearArchiveView,
MonthArchiveView,
DetailView,
)
from tinyblog.models import Post
class TinyBlogPostView(DetailView):
template_name = 'tinyblog/post.html'
def get_object(self):
post = get_object_or_404(
Post,
created__year=int(self.kwargs['year']),
created__month=int(self.kwargs['month']),
slug=self.kwargs['slug']
)
if post.created > datetime.now():
if not self.request.user.is_staff:
raise Http404
return post
post = TinyBlogPostView.as_view()
class TinyBlogIndexView(ArchiveIndexView):
date_field = 'created'
def get_queryset(self):
return Post.published_objects.all()
index_view = TinyBlogIndexView.as_view()
class TinyBlogYearView(YearArchiveView):
date_field = 'created'
make_object_list = True
def get_queryset(self):
return Post.published_objects.all()
year_view = TinyBlogYearView.as_view()
class TinyBlogMonthView(MonthArchiveView):
date_field = 'created'
month_format = '%m'
def get_queryset(self):
return Post.published_objects.all()
month_view = TinyBlogMonthView.as_view()
| Switch the main post detail view to a CBV | Switch the main post detail view to a CBV
| Python | bsd-3-clause | dominicrodger/tinyblog,dominicrodger/tinyblog | from datetime import datetime
from django.http import Http404
- from django.shortcuts import render_to_response, get_object_or_404
+ from django.shortcuts import get_object_or_404
- from django.template import RequestContext
from django.views.generic import (
ArchiveIndexView,
YearArchiveView,
MonthArchiveView,
+ DetailView,
)
from tinyblog.models import Post
+ class TinyBlogPostView(DetailView):
+ template_name = 'tinyblog/post.html'
- def post(request, year, month, slug):
- post = get_object_or_404(Post, created__year=year, created__month=month,
- slug=slug)
- if post.created > datetime.now():
- if not request.user.is_staff:
- raise Http404
+ def get_object(self):
+ post = get_object_or_404(
+ Post,
+ created__year=int(self.kwargs['year']),
+ created__month=int(self.kwargs['month']),
+ slug=self.kwargs['slug']
+ )
- return render_to_response('tinyblog/post.html',
- {'post': post},
- context_instance=RequestContext(request))
+ if post.created > datetime.now():
+ if not self.request.user.is_staff:
+ raise Http404
+ return post
+ post = TinyBlogPostView.as_view()
class TinyBlogIndexView(ArchiveIndexView):
date_field = 'created'
def get_queryset(self):
return Post.published_objects.all()
index_view = TinyBlogIndexView.as_view()
class TinyBlogYearView(YearArchiveView):
date_field = 'created'
make_object_list = True
def get_queryset(self):
return Post.published_objects.all()
year_view = TinyBlogYearView.as_view()
class TinyBlogMonthView(MonthArchiveView):
date_field = 'created'
month_format = '%m'
def get_queryset(self):
return Post.published_objects.all()
month_view = TinyBlogMonthView.as_view()
| Switch the main post detail view to a CBV | ## Code Before:
from datetime import datetime
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.views.generic import (
ArchiveIndexView,
YearArchiveView,
MonthArchiveView,
)
from tinyblog.models import Post
def post(request, year, month, slug):
post = get_object_or_404(Post, created__year=year, created__month=month,
slug=slug)
if post.created > datetime.now():
if not request.user.is_staff:
raise Http404
return render_to_response('tinyblog/post.html',
{'post': post},
context_instance=RequestContext(request))
class TinyBlogIndexView(ArchiveIndexView):
date_field = 'created'
def get_queryset(self):
return Post.published_objects.all()
index_view = TinyBlogIndexView.as_view()
class TinyBlogYearView(YearArchiveView):
date_field = 'created'
make_object_list = True
def get_queryset(self):
return Post.published_objects.all()
year_view = TinyBlogYearView.as_view()
class TinyBlogMonthView(MonthArchiveView):
date_field = 'created'
month_format = '%m'
def get_queryset(self):
return Post.published_objects.all()
month_view = TinyBlogMonthView.as_view()
## Instruction:
Switch the main post detail view to a CBV
## Code After:
from datetime import datetime
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.views.generic import (
ArchiveIndexView,
YearArchiveView,
MonthArchiveView,
DetailView,
)
from tinyblog.models import Post
class TinyBlogPostView(DetailView):
template_name = 'tinyblog/post.html'
def get_object(self):
post = get_object_or_404(
Post,
created__year=int(self.kwargs['year']),
created__month=int(self.kwargs['month']),
slug=self.kwargs['slug']
)
if post.created > datetime.now():
if not self.request.user.is_staff:
raise Http404
return post
post = TinyBlogPostView.as_view()
class TinyBlogIndexView(ArchiveIndexView):
date_field = 'created'
def get_queryset(self):
return Post.published_objects.all()
index_view = TinyBlogIndexView.as_view()
class TinyBlogYearView(YearArchiveView):
date_field = 'created'
make_object_list = True
def get_queryset(self):
return Post.published_objects.all()
year_view = TinyBlogYearView.as_view()
class TinyBlogMonthView(MonthArchiveView):
date_field = 'created'
month_format = '%m'
def get_queryset(self):
return Post.published_objects.all()
month_view = TinyBlogMonthView.as_view()
|
7e11e57ee4f9fc1dc3c967c9b2d26038a7727f72 | wqflask/wqflask/database.py | wqflask/wqflask/database.py | import os
import sys
from string import Template
from typing import Tuple
from urllib.parse import urlparse
import importlib
import MySQLdb
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
def read_from_pyfile(pyfile, setting):
orig_sys_path = sys.path[:]
sys.path.insert(0, os.path.dirname(pyfile))
module = importlib.import_module(os.path.basename(pyfile).strip(".py"))
sys.path = orig_sys_path[:]
return module.__dict__.get(setting)
def sql_uri():
"""Read the SQL_URI from the environment or settings file."""
return os.environ.get(
"SQL_URI", read_from_pyfile(
os.environ.get(
"GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")),
"SQL_URI"))
def parse_db_url(sql_uri: str) -> Tuple:
"""
Parse SQL_URI env variable from an sql URI
e.g. 'mysql://user:pass@host_name/db_name'
"""
parsed_db = urlparse(sql_uri)
return (
parsed_db.hostname, parsed_db.username, parsed_db.password,
parsed_db.path[1:], parsed_db.port)
def database_connection():
"""Returns a database connection"""
host, user, passwd, db_name, port = parse_db_url(sql_uri())
return MySQLdb.connect(
db=db_name, user=user, passwd=passwd, host=host, port=port)
| import os
import sys
from string import Template
from typing import Tuple
from urllib.parse import urlparse
import importlib
import MySQLdb
def sql_uri():
"""Read the SQL_URI from the environment or settings file."""
return os.environ.get(
"SQL_URI", read_from_pyfile(
os.environ.get(
"GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")),
"SQL_URI"))
def parse_db_url(sql_uri: str) -> Tuple:
"""
Parse SQL_URI env variable from an sql URI
e.g. 'mysql://user:pass@host_name/db_name'
"""
parsed_db = urlparse(sql_uri)
return (
parsed_db.hostname, parsed_db.username, parsed_db.password,
parsed_db.path[1:], parsed_db.port)
def database_connection():
"""Returns a database connection"""
host, user, passwd, db_name, port = parse_db_url(sql_uri())
return MySQLdb.connect(
db=db_name, user=user, passwd=passwd, host=host, port=port)
| Delete unused function and imports. | Delete unused function and imports.
* wqflask/wqflask/database.py: Remove unused sqlalchemy imports.
(read_from_pyfile): Delete it.
| Python | agpl-3.0 | genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2,genenetwork/genenetwork2 | import os
import sys
from string import Template
from typing import Tuple
from urllib.parse import urlparse
import importlib
import MySQLdb
- from sqlalchemy import create_engine
- from sqlalchemy.orm import scoped_session, sessionmaker
- from sqlalchemy.ext.declarative import declarative_base
-
- def read_from_pyfile(pyfile, setting):
- orig_sys_path = sys.path[:]
- sys.path.insert(0, os.path.dirname(pyfile))
- module = importlib.import_module(os.path.basename(pyfile).strip(".py"))
- sys.path = orig_sys_path[:]
- return module.__dict__.get(setting)
def sql_uri():
"""Read the SQL_URI from the environment or settings file."""
return os.environ.get(
"SQL_URI", read_from_pyfile(
os.environ.get(
"GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")),
"SQL_URI"))
def parse_db_url(sql_uri: str) -> Tuple:
"""
Parse SQL_URI env variable from an sql URI
e.g. 'mysql://user:pass@host_name/db_name'
"""
parsed_db = urlparse(sql_uri)
return (
parsed_db.hostname, parsed_db.username, parsed_db.password,
parsed_db.path[1:], parsed_db.port)
def database_connection():
"""Returns a database connection"""
host, user, passwd, db_name, port = parse_db_url(sql_uri())
return MySQLdb.connect(
db=db_name, user=user, passwd=passwd, host=host, port=port)
| Delete unused function and imports. | ## Code Before:
import os
import sys
from string import Template
from typing import Tuple
from urllib.parse import urlparse
import importlib
import MySQLdb
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
def read_from_pyfile(pyfile, setting):
orig_sys_path = sys.path[:]
sys.path.insert(0, os.path.dirname(pyfile))
module = importlib.import_module(os.path.basename(pyfile).strip(".py"))
sys.path = orig_sys_path[:]
return module.__dict__.get(setting)
def sql_uri():
"""Read the SQL_URI from the environment or settings file."""
return os.environ.get(
"SQL_URI", read_from_pyfile(
os.environ.get(
"GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")),
"SQL_URI"))
def parse_db_url(sql_uri: str) -> Tuple:
"""
Parse SQL_URI env variable from an sql URI
e.g. 'mysql://user:pass@host_name/db_name'
"""
parsed_db = urlparse(sql_uri)
return (
parsed_db.hostname, parsed_db.username, parsed_db.password,
parsed_db.path[1:], parsed_db.port)
def database_connection():
"""Returns a database connection"""
host, user, passwd, db_name, port = parse_db_url(sql_uri())
return MySQLdb.connect(
db=db_name, user=user, passwd=passwd, host=host, port=port)
## Instruction:
Delete unused function and imports.
## Code After:
import os
import sys
from string import Template
from typing import Tuple
from urllib.parse import urlparse
import importlib
import MySQLdb
def sql_uri():
"""Read the SQL_URI from the environment or settings file."""
return os.environ.get(
"SQL_URI", read_from_pyfile(
os.environ.get(
"GN2_SETTINGS", os.path.abspath("../etc/default_settings.py")),
"SQL_URI"))
def parse_db_url(sql_uri: str) -> Tuple:
"""
Parse SQL_URI env variable from an sql URI
e.g. 'mysql://user:pass@host_name/db_name'
"""
parsed_db = urlparse(sql_uri)
return (
parsed_db.hostname, parsed_db.username, parsed_db.password,
parsed_db.path[1:], parsed_db.port)
def database_connection():
"""Returns a database connection"""
host, user, passwd, db_name, port = parse_db_url(sql_uri())
return MySQLdb.connect(
db=db_name, user=user, passwd=passwd, host=host, port=port)
|
5c787be025ca99da339aae221b714bd1d8f2d0bd | route/station.py | route/station.py | from flask import request
from flask.ext import restful
from route.base import api
from model.base import db
from model.user import User
import logging
class StationAPI(restful.Resource):
def post(self):
data = request.get_json()
station = Station(data['name'], data['address'], data['address2'], data['town'], data['district'], data['lat'], data['lng'], data['bike_stands'], data['banking'])
db.session.add(station)
db.session.commit()
return Station.query.first()
api.add_resource(StationAPI, "/station")
| from flask import request
from flask.ext import restful
from route.base import api
from model.base import db
from model.user import User
import logging
class StationAPI(restful.Resource):
def post(self):
data = request.get_json()
station = Station(data['name'], data['address'], data['address2'], data['town'], data['district'], data['lat'], data['lng'], data['bike_stands'], data['banking'])
db.session.add(station)
db.session.commit()
return Station.query.first()
def get(self, station_id):
data = request.get
api.add_resource(StationAPI, "/station")
| Add start of get funtion | Add start of get funtion
| Python | mit | hexa4313/velov-companion-server,hexa4313/velov-companion-server | from flask import request
from flask.ext import restful
from route.base import api
from model.base import db
from model.user import User
import logging
class StationAPI(restful.Resource):
def post(self):
data = request.get_json()
station = Station(data['name'], data['address'], data['address2'], data['town'], data['district'], data['lat'], data['lng'], data['bike_stands'], data['banking'])
db.session.add(station)
db.session.commit()
return Station.query.first()
+ def get(self, station_id):
+ data = request.get
+
api.add_resource(StationAPI, "/station")
| Add start of get funtion | ## Code Before:
from flask import request
from flask.ext import restful
from route.base import api
from model.base import db
from model.user import User
import logging
class StationAPI(restful.Resource):
def post(self):
data = request.get_json()
station = Station(data['name'], data['address'], data['address2'], data['town'], data['district'], data['lat'], data['lng'], data['bike_stands'], data['banking'])
db.session.add(station)
db.session.commit()
return Station.query.first()
api.add_resource(StationAPI, "/station")
## Instruction:
Add start of get funtion
## Code After:
from flask import request
from flask.ext import restful
from route.base import api
from model.base import db
from model.user import User
import logging
class StationAPI(restful.Resource):
def post(self):
data = request.get_json()
station = Station(data['name'], data['address'], data['address2'], data['town'], data['district'], data['lat'], data['lng'], data['bike_stands'], data['banking'])
db.session.add(station)
db.session.commit()
return Station.query.first()
def get(self, station_id):
data = request.get
api.add_resource(StationAPI, "/station")
|
d64e85f96483e6b212adca38ca5fa89c64508701 | froide_campaign/listeners.py | froide_campaign/listeners.py | from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if reference is None:
return
if 'campaign' not in reference:
return
try:
campaign, slug = reference['campaign'].split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
iobj = InformationObject.objects.get(campaign=campaign, slug=slug)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
| from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, slug = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
iobj = InformationObject.objects.get(campaign=campaign, slug=slug)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
| Adjust to new reference handling | Adjust to new reference handling | Python | mit | okfde/froide-campaign,okfde/froide-campaign,okfde/froide-campaign | from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
- if reference is None:
+ if not reference:
return
- if 'campaign' not in reference:
+ if not reference.startswith('campaign:'):
return
+ namespace, campaign_value = reference.split(':', 1)
try:
- campaign, slug = reference['campaign'].split('@', 1)
+ campaign, slug = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
iobj = InformationObject.objects.get(campaign=campaign, slug=slug)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
| Adjust to new reference handling | ## Code Before:
from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if reference is None:
return
if 'campaign' not in reference:
return
try:
campaign, slug = reference['campaign'].split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
iobj = InformationObject.objects.get(campaign=campaign, slug=slug)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
## Instruction:
Adjust to new reference handling
## Code After:
from .models import Campaign, InformationObject
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, slug = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
try:
iobj = InformationObject.objects.get(campaign=campaign, slug=slug)
except InformationObject.DoesNotExist:
return
if iobj.foirequest is not None:
return
if iobj.publicbody != sender.public_body:
return
if not sender.public:
return
iobj.foirequest = sender
iobj.save()
|
b5fa4f9eb11575ddd8838bc53817854de831337f | dumpling/views.py | dumpling/views.py | from django.conf import settings
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
context_object_name = 'page'
def get_queryset(self):
return Page.objects.published().prefetch_related('pagewidget__widget')
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
paths = list(filter(None, self.kwargs.get('path', '/').split('/')))
if not paths:
paths = ['']
paths.reverse()
query = {}
prefix = 'path'
for step in paths:
query[prefix] = step
prefix = 'parent__' + prefix
query[prefix.replace('path', 'isnull')] = True
return get_object_or_404(queryset, **query)
def get_template_names(self):
return self.object.template[len(settings.USER_TEMPLATES_PATH):]
#
# Management Interface
#
| from django.conf import settings
from django.shortcuts import get_object_or_404, render
from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
context_object_name = 'page'
def get_queryset(self):
return Page.objects.published().prefetch_related('pagewidget_set__widget')
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
paths = list(filter(None, self.kwargs.get('path', '/').split('/')))
if not paths:
paths = ['']
paths.reverse()
query = {}
prefix = 'path'
for step in paths:
query[prefix] = step
prefix = 'parent__' + prefix
query[prefix.replace('path', 'isnull')] = True
return get_object_or_404(queryset, **query)
def get_template_names(self):
return self.object.template[len(settings.USER_TEMPLATES_PATH):]
def styles(request, name):
namespace = Namespace()
for tv in ThemeValue.objects.all():
namespace.set_variable('${}-{}'.format(tv.group, tv.name), String(tv.value))
compiler = Compiler(namespace=namespace)
return compiler.compile_string(src)
| Fix prefetch. Add styles view | Fix prefetch. Add styles view
| Python | mit | funkybob/dumpling,funkybob/dumpling | from django.conf import settings
- from django.shortcuts import get_object_or_404
+ from django.shortcuts import get_object_or_404, render
from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
context_object_name = 'page'
def get_queryset(self):
- return Page.objects.published().prefetch_related('pagewidget__widget')
+ return Page.objects.published().prefetch_related('pagewidget_set__widget')
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
paths = list(filter(None, self.kwargs.get('path', '/').split('/')))
if not paths:
paths = ['']
paths.reverse()
query = {}
prefix = 'path'
for step in paths:
query[prefix] = step
prefix = 'parent__' + prefix
query[prefix.replace('path', 'isnull')] = True
return get_object_or_404(queryset, **query)
def get_template_names(self):
return self.object.template[len(settings.USER_TEMPLATES_PATH):]
- #
- # Management Interface
- #
+ def styles(request, name):
+ namespace = Namespace()
+ for tv in ThemeValue.objects.all():
+ namespace.set_variable('${}-{}'.format(tv.group, tv.name), String(tv.value))
+ compiler = Compiler(namespace=namespace)
+ return compiler.compile_string(src)
| Fix prefetch. Add styles view | ## Code Before:
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
context_object_name = 'page'
def get_queryset(self):
return Page.objects.published().prefetch_related('pagewidget__widget')
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
paths = list(filter(None, self.kwargs.get('path', '/').split('/')))
if not paths:
paths = ['']
paths.reverse()
query = {}
prefix = 'path'
for step in paths:
query[prefix] = step
prefix = 'parent__' + prefix
query[prefix.replace('path', 'isnull')] = True
return get_object_or_404(queryset, **query)
def get_template_names(self):
return self.object.template[len(settings.USER_TEMPLATES_PATH):]
#
# Management Interface
#
## Instruction:
Fix prefetch. Add styles view
## Code After:
from django.conf import settings
from django.shortcuts import get_object_or_404, render
from django.views.generic import DetailView
from .models import Page
class PageView(DetailView):
context_object_name = 'page'
def get_queryset(self):
return Page.objects.published().prefetch_related('pagewidget_set__widget')
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
paths = list(filter(None, self.kwargs.get('path', '/').split('/')))
if not paths:
paths = ['']
paths.reverse()
query = {}
prefix = 'path'
for step in paths:
query[prefix] = step
prefix = 'parent__' + prefix
query[prefix.replace('path', 'isnull')] = True
return get_object_or_404(queryset, **query)
def get_template_names(self):
return self.object.template[len(settings.USER_TEMPLATES_PATH):]
def styles(request, name):
namespace = Namespace()
for tv in ThemeValue.objects.all():
namespace.set_variable('${}-{}'.format(tv.group, tv.name), String(tv.value))
compiler = Compiler(namespace=namespace)
return compiler.compile_string(src)
|
5cf66e26259f5b4c78e61530822fa19dfc117206 | settings_test.py | settings_test.py | INSTALLED_APPS = (
'oauth_tokens',
'taggit',
'vkontakte_groups',
)
OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034
OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz'
OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats']
OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715'
OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich'
OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237' | INSTALLED_APPS = (
'oauth_tokens',
'taggit',
'vkontakte_groups',
)
OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034
OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz'
OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats']
OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715'
OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich'
OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237'
# Set VK API Timeout
VKONTAKTE_API_REQUEST_TIMEOUT = 7
| Fix RuntimeError: maximum recursion depth | Fix RuntimeError: maximum recursion depth
| Python | bsd-3-clause | ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic,ramusus/django-vkontakte-groups-statistic | INSTALLED_APPS = (
'oauth_tokens',
'taggit',
'vkontakte_groups',
)
OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034
OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz'
OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats']
OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715'
OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich'
OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237'
+
+ # Set VK API Timeout
+ VKONTAKTE_API_REQUEST_TIMEOUT = 7
+ | Fix RuntimeError: maximum recursion depth | ## Code Before:
INSTALLED_APPS = (
'oauth_tokens',
'taggit',
'vkontakte_groups',
)
OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034
OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz'
OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats']
OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715'
OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich'
OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237'
## Instruction:
Fix RuntimeError: maximum recursion depth
## Code After:
INSTALLED_APPS = (
'oauth_tokens',
'taggit',
'vkontakte_groups',
)
OAUTH_TOKENS_VKONTAKTE_CLIENT_ID = 3430034
OAUTH_TOKENS_VKONTAKTE_CLIENT_SECRET = 'b0FwzyKtO8QiQmgWQMTz'
OAUTH_TOKENS_VKONTAKTE_SCOPE = ['ads,wall,photos,friends,stats']
OAUTH_TOKENS_VKONTAKTE_USERNAME = '+919665223715'
OAUTH_TOKENS_VKONTAKTE_PASSWORD = 'githubovich'
OAUTH_TOKENS_VKONTAKTE_PHONE_END = '96652237'
# Set VK API Timeout
VKONTAKTE_API_REQUEST_TIMEOUT = 7
|
a81fbdd334dc475554e77bbb71ae00985f2d23c4 | eventlog/stats.py | eventlog/stats.py | from datetime import datetime, timedelta
from django.contrib.auth.models import User
def stats():
return {
"used_site_last_thirty_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=30)).distinct().count(),
"used_site_last_seven_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=7)).distinct().count()
}
| from datetime import datetime, timedelta
from django.contrib.auth.models import User
def used_active(days):
used = User.objects.filter(
log__timestamp__gt=datetime.now() - timedelta(days=days)
).distinct().count()
active = User.objects.filter(
log__timestamp__gt=datetime.now() - timedelta(days=days)
).exclude(
date_joined__gt=datetime.now() - timedelta(days=days)
).distinct().count()
return used, active
def stats():
used_seven, active_seven = used_active(7)
used_thirty, active_thirty = used_active(30)
return {
"used_seven": used_seven,
"used_thirty": used_thirty,
"active_seven": active_seven,
"active_thirty": active_thirty
}
| Add active_seven and active_thirty users | Add active_seven and active_thirty users
| Python | bsd-3-clause | ConsumerAffairs/django-eventlog-ca,rosscdh/pinax-eventlog,KleeTaurus/pinax-eventlog,jawed123/pinax-eventlog,pinax/pinax-eventlog | from datetime import datetime, timedelta
from django.contrib.auth.models import User
+ def used_active(days):
+ used = User.objects.filter(
+ log__timestamp__gt=datetime.now() - timedelta(days=days)
+ ).distinct().count()
+
+ active = User.objects.filter(
+ log__timestamp__gt=datetime.now() - timedelta(days=days)
+ ).exclude(
+ date_joined__gt=datetime.now() - timedelta(days=days)
+ ).distinct().count()
+
+ return used, active
+
+
def stats():
+ used_seven, active_seven = used_active(7)
+ used_thirty, active_thirty = used_active(30)
+
return {
- "used_site_last_thirty_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=30)).distinct().count(),
- "used_site_last_seven_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=7)).distinct().count()
+ "used_seven": used_seven,
+ "used_thirty": used_thirty,
+ "active_seven": active_seven,
+ "active_thirty": active_thirty
}
| Add active_seven and active_thirty users | ## Code Before:
from datetime import datetime, timedelta
from django.contrib.auth.models import User
def stats():
return {
"used_site_last_thirty_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=30)).distinct().count(),
"used_site_last_seven_days": User.objects.filter(log__timestamp__gt=datetime.now() - timedelta(days=7)).distinct().count()
}
## Instruction:
Add active_seven and active_thirty users
## Code After:
from datetime import datetime, timedelta
from django.contrib.auth.models import User
def used_active(days):
used = User.objects.filter(
log__timestamp__gt=datetime.now() - timedelta(days=days)
).distinct().count()
active = User.objects.filter(
log__timestamp__gt=datetime.now() - timedelta(days=days)
).exclude(
date_joined__gt=datetime.now() - timedelta(days=days)
).distinct().count()
return used, active
def stats():
used_seven, active_seven = used_active(7)
used_thirty, active_thirty = used_active(30)
return {
"used_seven": used_seven,
"used_thirty": used_thirty,
"active_seven": active_seven,
"active_thirty": active_thirty
}
|
850803d02868e20bc637f777ee201ac778c63606 | lms/djangoapps/edraak_misc/utils.py | lms/djangoapps/edraak_misc/utils.py | from courseware.access import has_access
from django.conf import settings
def is_certificate_allowed(user, course):
return (course.has_ended()
and settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE')
or has_access(user, 'staff', course.id))
| from courseware.access import has_access
from django.conf import settings
def is_certificate_allowed(user, course):
if not settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE'):
return False
return course.has_ended() or has_access(user, 'staff', course.id)
| Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False | Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False
| Python | agpl-3.0 | Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform | from courseware.access import has_access
from django.conf import settings
def is_certificate_allowed(user, course):
- return (course.has_ended()
- and settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE')
+ if not settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE'):
- or has_access(user, 'staff', course.id))
+ return False
+ return course.has_ended() or has_access(user, 'staff', course.id)
+ | Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False | ## Code Before:
from courseware.access import has_access
from django.conf import settings
def is_certificate_allowed(user, course):
return (course.has_ended()
and settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE')
or has_access(user, 'staff', course.id))
## Instruction:
Disable certificate for all if ENABLE_ISSUE_CERTIFICATE == False
## Code After:
from courseware.access import has_access
from django.conf import settings
def is_certificate_allowed(user, course):
if not settings.FEATURES.get('ENABLE_ISSUE_CERTIFICATE'):
return False
return course.has_ended() or has_access(user, 'staff', course.id)
|
b3a144e9dfba915d186fd1243515172780611689 | models/waifu_model.py | models/waifu_model.py | from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuModel(BaseModel):
class Meta:
db_table = 'waifus'
name = CharField(max_length=128, null=False)
description = TextField(null=False)
pic = CharField(max_length=128, null=False)
created_at = DateTimeField(null=False, default=datetime.now)
updated_at = DateTimeField(null=False, default=datetime.now)
rating = IntegerField(null=False, default=0)
sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE)
owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me')
| from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuModel(BaseModel):
class Meta:
db_table = 'waifus'
name = CharField(max_length=128, null=False)
description = TextField(null=False)
pic = CharField(max_length=128, null=False)
created_at = DateTimeField(null=False, default=datetime.now)
updated_at = DateTimeField(null=False, default=datetime.now)
rating = IntegerField(null=False, default=0)
sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE)
owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me')
def to_json(self):
json = super(WaifuModel, self).to_json()
json['users_count'] = self.users.count()
return json
| Add users count to json representation. | Add users count to json representation.
| Python | cc0-1.0 | sketchturnerr/WaifuSim-backend,sketchturnerr/WaifuSim-backend | from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuModel(BaseModel):
class Meta:
db_table = 'waifus'
name = CharField(max_length=128, null=False)
description = TextField(null=False)
pic = CharField(max_length=128, null=False)
created_at = DateTimeField(null=False, default=datetime.now)
updated_at = DateTimeField(null=False, default=datetime.now)
rating = IntegerField(null=False, default=0)
sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE)
owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me')
+ def to_json(self):
+ json = super(WaifuModel, self).to_json()
+ json['users_count'] = self.users.count()
+ return json
+ | Add users count to json representation. | ## Code Before:
from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuModel(BaseModel):
class Meta:
db_table = 'waifus'
name = CharField(max_length=128, null=False)
description = TextField(null=False)
pic = CharField(max_length=128, null=False)
created_at = DateTimeField(null=False, default=datetime.now)
updated_at = DateTimeField(null=False, default=datetime.now)
rating = IntegerField(null=False, default=0)
sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE)
owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me')
## Instruction:
Add users count to json representation.
## Code After:
from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuModel(BaseModel):
class Meta:
db_table = 'waifus'
name = CharField(max_length=128, null=False)
description = TextField(null=False)
pic = CharField(max_length=128, null=False)
created_at = DateTimeField(null=False, default=datetime.now)
updated_at = DateTimeField(null=False, default=datetime.now)
rating = IntegerField(null=False, default=0)
sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE)
owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me')
def to_json(self):
json = super(WaifuModel, self).to_json()
json['users_count'] = self.users.count()
return json
|
f6841a527bd8b52aa88c4c3b5980a0001387f33e | scoring/models/regressors.py | scoring/models/regressors.py | from sklearn.ensemble import RandomForestRegressor as randomforest
from sklearn.svm import SVR as svm
from sklearn.pls import PLSRegression as pls
from .neuralnetwork import neuralnetwork
__all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork']
| from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.pls import PLSRegression
from .neuralnetwork import neuralnetwork
__all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork']
class randomforest(RandomForestRegressor):
pass
class svm(SVR):
pass
class svm(PLSRegression):
pass
| Make models inherit from sklearn | Make models inherit from sklearn
| Python | bsd-3-clause | mwojcikowski/opendrugdiscovery | - from sklearn.ensemble import RandomForestRegressor as randomforest
+ from sklearn.ensemble import RandomForestRegressor
- from sklearn.svm import SVR as svm
+ from sklearn.svm import SVR
- from sklearn.pls import PLSRegression as pls
+ from sklearn.pls import PLSRegression
from .neuralnetwork import neuralnetwork
__all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork']
+ class randomforest(RandomForestRegressor):
+ pass
+
+ class svm(SVR):
+ pass
+
+ class svm(PLSRegression):
+ pass
+ | Make models inherit from sklearn | ## Code Before:
from sklearn.ensemble import RandomForestRegressor as randomforest
from sklearn.svm import SVR as svm
from sklearn.pls import PLSRegression as pls
from .neuralnetwork import neuralnetwork
__all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork']
## Instruction:
Make models inherit from sklearn
## Code After:
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from sklearn.pls import PLSRegression
from .neuralnetwork import neuralnetwork
__all__ = ['randomforest', 'svm', 'pls', 'neuralnetwork']
class randomforest(RandomForestRegressor):
pass
class svm(SVR):
pass
class svm(PLSRegression):
pass
|
0855f9b5a9d36817139e61937419553f6ad21f78 | symposion/proposals/urls.py | symposion/proposals/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"),
url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"),
url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"),
url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"),
url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"),
url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"),
url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"),
url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"),
url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"),
)
| from django.conf.urls import patterns, url
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"),
url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"),
url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"),
url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"),
url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"),
url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"),
url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"),
url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"),
url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"),
)
| Allow dashes in proposal kind slugs | Allow dashes in proposal kind slugs
We can see from the setting PROPOSAL_FORMS that at least one proposal kind,
Sponsor Tutorial, has a slug with a dash in it: sponsor-tutorial. Yet the
URL pattern for submitting a proposal doesn't accept dashes in the slug.
Fix it.
| Python | bsd-3-clause | njl/pycon,pyconjp/pyconjp-website,njl/pycon,Diwahars/pycon,smellman/sotmjp-website,pyconjp/pyconjp-website,pyconjp/pyconjp-website,PyCon/pycon,osmfj/sotmjp-website,njl/pycon,Diwahars/pycon,PyCon/pycon,pyconjp/pyconjp-website,osmfj/sotmjp-website,osmfj/sotmjp-website,PyCon/pycon,osmfj/sotmjp-website,smellman/sotmjp-website,smellman/sotmjp-website,PyCon/pycon,smellman/sotmjp-website,Diwahars/pycon,Diwahars/pycon,njl/pycon | - from django.conf.urls.defaults import *
+ from django.conf.urls import patterns, url
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
- url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
+ url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"),
url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"),
url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"),
url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"),
url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"),
url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"),
url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"),
url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"),
url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"),
)
| Allow dashes in proposal kind slugs | ## Code Before:
from django.conf.urls.defaults import *
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/(\w+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"),
url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"),
url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"),
url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"),
url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"),
url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"),
url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"),
url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"),
url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"),
)
## Instruction:
Allow dashes in proposal kind slugs
## Code After:
from django.conf.urls import patterns, url
urlpatterns = patterns("symposion.proposals.views",
url(r"^submit/$", "proposal_submit", name="proposal_submit"),
url(r"^submit/([\w-]+)/$", "proposal_submit_kind", name="proposal_submit_kind"),
url(r"^(\d+)/$", "proposal_detail", name="proposal_detail"),
url(r"^(\d+)/edit/$", "proposal_edit", name="proposal_edit"),
url(r"^(\d+)/speakers/$", "proposal_speaker_manage", name="proposal_speaker_manage"),
url(r"^(\d+)/cancel/$", "proposal_cancel", name="proposal_cancel"),
url(r"^(\d+)/leave/$", "proposal_leave", name="proposal_leave"),
url(r"^(\d+)/join/$", "proposal_pending_join", name="proposal_pending_join"),
url(r"^(\d+)/decline/$", "proposal_pending_decline", name="proposal_pending_decline"),
url(r"^(\d+)/document/create/$", "document_create", name="proposal_document_create"),
url(r"^document/(\d+)/delete/$", "document_delete", name="proposal_document_delete"),
url(r"^document/(\d+)/([^/]+)$", "document_download", name="proposal_document_download"),
)
|
da9c0743657ecc890c2a8503ea4bbb681ae00178 | tests/chainer_tests/functions_tests/math_tests/test_arctanh.py | tests/chainer_tests/functions_tests/math_tests/test_arctanh.py | import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
| import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
| Call testing.run_module at the end of the test | Call testing.run_module at the end of the test
| Python | mit | okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,okuta/chainer,chainer/chainer,niboshi/chainer,okuta/chainer,pfnet/chainer,chainer/chainer,tkerola/chainer,chainer/chainer,niboshi/chainer,keisuke-umezawa/chainer,okuta/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,keisuke-umezawa/chainer,chainer/chainer,hvy/chainer,keisuke-umezawa/chainer,hvy/chainer,hvy/chainer | import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
+
+ testing.run_module(__name__, __file__)
+ | Call testing.run_module at the end of the test | ## Code Before:
import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
## Instruction:
Call testing.run_module at the end of the test
## Code After:
import unittest
from chainer import testing
import chainer.functions as F
import numpy
def make_data(shape, dtype):
# Input values close to -1 or 1 would make tests unstable
x = numpy.random.uniform(-0.9, 0.9, shape).astype(dtype, copy=False)
gy = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
ggx = numpy.random.uniform(-1, 1, shape).astype(dtype, copy=False)
return x, gy, ggx
@testing.unary_math_function_unittest(F.arctanh, make_data=make_data)
class TestArctanh(unittest.TestCase):
pass
testing.run_module(__name__, __file__)
|
584891ce58c3e979a5d6871ba7a6ff0a9e01d780 | routes/student_vote.py | routes/student_vote.py | from aiohttp import web
from db_helper import get_project_id, get_most_recent_group, get_user_id
from permissions import view_only, value_set
@view_only("join_projects")
@value_set("student_choosable")
async def on_submit(request):
session = request.app["session"]
cookies = request.cookies
post = await request.post()
option = int(post["order"]) - 1
attrs = ["first_option_id", "second_option_id", "third_option_id"]
project = get_project_id(session, int(post["choice"]))
if project.group is not get_most_recent_group(session):
return web.Response(status=403, text="Cannot join legacy projects")
user = get_user_id(session, cookies)
setattr(user, attrs[option], project.id)
for attr in set(attrs) - {attrs[option]}:
if getattr(user, attr) == project.id:
setattr(user, attr, None)
session.commit()
return web.Response(status=200, text="set")
| from aiohttp import web
from db_helper import get_project_id, get_user_id, can_choose_project
from permissions import view_only, value_set
@view_only("join_projects")
@value_set("student_choosable")
async def on_submit(request):
session = request.app["session"]
cookies = request.cookies
post = await request.post()
option = int(post["order"]) - 1
attrs = ["first_option_id", "second_option_id", "third_option_id"]
project = get_project_id(session, int(post["choice"]))
if not can_choose_project(session, cookies, project):
return web.Response(status=403, text="You cannot choose this project")
user = get_user_id(session, cookies)
setattr(user, attrs[option], project.id)
for attr in set(attrs) - {attrs[option]}:
if getattr(user, attr) == project.id:
setattr(user, attr, None)
session.commit()
return web.Response(status=200, text="set")
| Check if student can choose a project before allowing them to join it | Check if student can choose a project before allowing them to join it
| Python | agpl-3.0 | wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp | from aiohttp import web
- from db_helper import get_project_id, get_most_recent_group, get_user_id
+ from db_helper import get_project_id, get_user_id, can_choose_project
from permissions import view_only, value_set
@view_only("join_projects")
@value_set("student_choosable")
async def on_submit(request):
session = request.app["session"]
cookies = request.cookies
post = await request.post()
option = int(post["order"]) - 1
attrs = ["first_option_id", "second_option_id", "third_option_id"]
project = get_project_id(session, int(post["choice"]))
- if project.group is not get_most_recent_group(session):
+ if not can_choose_project(session, cookies, project):
- return web.Response(status=403, text="Cannot join legacy projects")
+ return web.Response(status=403, text="You cannot choose this project")
user = get_user_id(session, cookies)
setattr(user, attrs[option], project.id)
for attr in set(attrs) - {attrs[option]}:
if getattr(user, attr) == project.id:
setattr(user, attr, None)
session.commit()
return web.Response(status=200, text="set")
| Check if student can choose a project before allowing them to join it | ## Code Before:
from aiohttp import web
from db_helper import get_project_id, get_most_recent_group, get_user_id
from permissions import view_only, value_set
@view_only("join_projects")
@value_set("student_choosable")
async def on_submit(request):
session = request.app["session"]
cookies = request.cookies
post = await request.post()
option = int(post["order"]) - 1
attrs = ["first_option_id", "second_option_id", "third_option_id"]
project = get_project_id(session, int(post["choice"]))
if project.group is not get_most_recent_group(session):
return web.Response(status=403, text="Cannot join legacy projects")
user = get_user_id(session, cookies)
setattr(user, attrs[option], project.id)
for attr in set(attrs) - {attrs[option]}:
if getattr(user, attr) == project.id:
setattr(user, attr, None)
session.commit()
return web.Response(status=200, text="set")
## Instruction:
Check if student can choose a project before allowing them to join it
## Code After:
from aiohttp import web
from db_helper import get_project_id, get_user_id, can_choose_project
from permissions import view_only, value_set
@view_only("join_projects")
@value_set("student_choosable")
async def on_submit(request):
session = request.app["session"]
cookies = request.cookies
post = await request.post()
option = int(post["order"]) - 1
attrs = ["first_option_id", "second_option_id", "third_option_id"]
project = get_project_id(session, int(post["choice"]))
if not can_choose_project(session, cookies, project):
return web.Response(status=403, text="You cannot choose this project")
user = get_user_id(session, cookies)
setattr(user, attrs[option], project.id)
for attr in set(attrs) - {attrs[option]}:
if getattr(user, attr) == project.id:
setattr(user, attr, None)
session.commit()
return web.Response(status=200, text="set")
|
eefff91804317f4fb2c518446ab8e2072af4d87f | app/models.py | app/models.py | from django.db import models
import mongoengine
from mongoengine import Document, EmbeddedDocument
from mongoengine.fields import *
# Create your models here.
class Greeting(models.Model):
when = models.DateTimeField('date created', auto_now_add=True)
MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority'
mongoengine.connect('fikanotedb', host=MONGODB_URI)
class Shownote(EmbeddedDocument):
url = URLField()
title = StringField()
date = DateTimeField()
class FikanoteDB(Document):
title = StringField()
number = IntField()
person = ListField(StringField())
agenda = StringField()
date = DateTimeField()
shownotes = ListField(EmbeddedDocumentField(Shownote))
meta = {'collection': 'fikanotedb'}
class AgendaDB(Document):
url = URLField()
title = StringField()
date = DateTimeField()
meta = {'collection': 'agendadb'}
| from django.db import models
import mongoengine
from mongoengine import Document, EmbeddedDocument
from mongoengine.fields import *
import os
# Create your models here.
class Greeting(models.Model):
when = models.DateTimeField('date created', auto_now_add=True)
USER = os.getenv('DATABASE_USER')
PASWORD = os.getenv('DATABASE_PASSWORD')
MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD)
mongoengine.connect('fikanotedb', host=MONGODB_URI)
class Shownote(EmbeddedDocument):
url = URLField()
title = StringField()
date = DateTimeField()
class FikanoteDB(Document):
title = StringField()
number = IntField()
person = ListField(StringField())
agenda = StringField()
date = DateTimeField()
shownotes = ListField(EmbeddedDocumentField(Shownote))
meta = {'collection': 'fikanotedb'}
class AgendaDB(Document):
url = URLField()
title = StringField()
date = DateTimeField()
meta = {'collection': 'agendadb'}
| Remove username and password from repository | Remove username and password from repository
| Python | mit | gmkou/FikaNote,gmkou/FikaNote,gmkou/FikaNote | from django.db import models
import mongoengine
from mongoengine import Document, EmbeddedDocument
from mongoengine.fields import *
+ import os
# Create your models here.
class Greeting(models.Model):
when = models.DateTimeField('date created', auto_now_add=True)
+ USER = os.getenv('DATABASE_USER')
+ PASWORD = os.getenv('DATABASE_PASSWORD')
- MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority'
+ MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD)
mongoengine.connect('fikanotedb', host=MONGODB_URI)
class Shownote(EmbeddedDocument):
url = URLField()
title = StringField()
date = DateTimeField()
class FikanoteDB(Document):
title = StringField()
number = IntField()
person = ListField(StringField())
agenda = StringField()
date = DateTimeField()
shownotes = ListField(EmbeddedDocumentField(Shownote))
meta = {'collection': 'fikanotedb'}
class AgendaDB(Document):
url = URLField()
title = StringField()
date = DateTimeField()
meta = {'collection': 'agendadb'}
| Remove username and password from repository | ## Code Before:
from django.db import models
import mongoengine
from mongoengine import Document, EmbeddedDocument
from mongoengine.fields import *
# Create your models here.
class Greeting(models.Model):
when = models.DateTimeField('date created', auto_now_add=True)
MONGODB_URI = 'mongodb+srv://fikaadmin:ZJ6TtyTZMXA@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority'
mongoengine.connect('fikanotedb', host=MONGODB_URI)
class Shownote(EmbeddedDocument):
url = URLField()
title = StringField()
date = DateTimeField()
class FikanoteDB(Document):
title = StringField()
number = IntField()
person = ListField(StringField())
agenda = StringField()
date = DateTimeField()
shownotes = ListField(EmbeddedDocumentField(Shownote))
meta = {'collection': 'fikanotedb'}
class AgendaDB(Document):
url = URLField()
title = StringField()
date = DateTimeField()
meta = {'collection': 'agendadb'}
## Instruction:
Remove username and password from repository
## Code After:
from django.db import models
import mongoengine
from mongoengine import Document, EmbeddedDocument
from mongoengine.fields import *
import os
# Create your models here.
class Greeting(models.Model):
when = models.DateTimeField('date created', auto_now_add=True)
USER = os.getenv('DATABASE_USER')
PASWORD = os.getenv('DATABASE_PASSWORD')
MONGODB_URI = "mongodb+srv://{}:{}@fikanotedb.ltkpy.mongodb.net/fikanotedb?retryWrites=true&w=majority".format(USER, PASWORD)
mongoengine.connect('fikanotedb', host=MONGODB_URI)
class Shownote(EmbeddedDocument):
url = URLField()
title = StringField()
date = DateTimeField()
class FikanoteDB(Document):
title = StringField()
number = IntField()
person = ListField(StringField())
agenda = StringField()
date = DateTimeField()
shownotes = ListField(EmbeddedDocumentField(Shownote))
meta = {'collection': 'fikanotedb'}
class AgendaDB(Document):
url = URLField()
title = StringField()
date = DateTimeField()
meta = {'collection': 'agendadb'}
|
556cef75198e3a5a8ac3e8f523c54b0b2df6a2c1 | mousestyles/data/tests/test_data.py | mousestyles/data/tests/test_data.py |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_equal
import mousestyles.data as data
def test_all_features_mousedays_11bins():
all_features = data.all_feature_data()
print(all_features.shape)
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_equal
import mousestyles.data as data
def test_all_features_loader():
all_features = data.load_all_features()
assert_equal(all_features.shape, (21131, 13))
| Test for new data loader | TST: Test for new data loader
Just a start, should probably add a more detailed test later.
| Python | bsd-2-clause | berkeley-stat222/mousestyles,togawa28/mousestyles,changsiyao/mousestyles |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_equal
import mousestyles.data as data
- def test_all_features_mousedays_11bins():
+ def test_all_features_loader():
- all_features = data.all_feature_data()
+ all_features = data.load_all_features()
- print(all_features.shape)
+ assert_equal(all_features.shape, (21131, 13))
| Test for new data loader | ## Code Before:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_equal
import mousestyles.data as data
def test_all_features_mousedays_11bins():
all_features = data.all_feature_data()
print(all_features.shape)
## Instruction:
Test for new data loader
## Code After:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import numpy as np
from numpy.testing import assert_equal
import mousestyles.data as data
def test_all_features_loader():
all_features = data.load_all_features()
assert_equal(all_features.shape, (21131, 13))
|
1e10fa30998f63359ddd26d9804bd32a837c2cab | armstrong/esi/tests/_utils.py | armstrong/esi/tests/_utils.py | from django.conf import settings
from django.test import TestCase as DjangoTestCase
import fudge
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
| from django.conf import settings
from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
def with_fake_request(func):
def inner(self, *args, **kwargs):
request = fudge.Fake(HttpRequest)
fudge.clear_calls()
result = func(self, request, *args, **kwargs)
fudge.verify()
fudge.clear_expectations()
return result
return inner
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
| Add in a decorator for generating fake request objects for test cases | Add in a decorator for generating fake request objects for test cases
| Python | bsd-3-clause | armstrong/armstrong.esi | from django.conf import settings
+ from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
+
+ def with_fake_request(func):
+ def inner(self, *args, **kwargs):
+ request = fudge.Fake(HttpRequest)
+ fudge.clear_calls()
+
+ result = func(self, request, *args, **kwargs)
+
+ fudge.verify()
+ fudge.clear_expectations()
+ return result
+ return inner
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
| Add in a decorator for generating fake request objects for test cases | ## Code Before:
from django.conf import settings
from django.test import TestCase as DjangoTestCase
import fudge
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
## Instruction:
Add in a decorator for generating fake request objects for test cases
## Code After:
from django.conf import settings
from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
def with_fake_request(func):
def inner(self, *args, **kwargs):
request = fudge.Fake(HttpRequest)
fudge.clear_calls()
result = func(self, request, *args, **kwargs)
fudge.verify()
fudge.clear_expectations()
return result
return inner
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
|
675e0a29f780d6053d942dce4f80c6d934f3785a | Python/tigre/utilities/Ax.py | Python/tigre/utilities/Ax.py | from _Ax import _Ax_ext
import numpy as np
import copy
def Ax(img, geo, angles, projection_type="Siddon"):
if img.dtype != np.float32:
raise TypeError("Input data should be float32, not "+ str(img.dtype))
if not np.isreal(img).all():
raise ValueError("Complex types not compatible for projection.")
geox = copy.deepcopy(geo)
geox.check_geo(angles)
"""
Here we cast all values in geo to single point precision float. This way we
know what behaviour to expect from pytigre to Cuda and can change
single parameters accordingly.
"""
geox.cast_to_single()
#geox.checknans()
if abs(img.shape - geox.nVoxel).max()>1e-8:
raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geox.nVoxel) +
" not:" + str(img.shape))
return _Ax_ext(img, geox, geox.angles, projection_type, geox.mode)
| from _Ax import _Ax_ext
import numpy as np
import copy
def Ax(img, geo, angles, projection_type="Siddon"):
if img.dtype != np.float32:
raise TypeError("Input data should be float32, not "+ str(img.dtype))
if not np.isreal(img).all():
raise ValueError("Complex types not compatible for projection.")
if any(img.shape != geo.nVoxel):
raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geo.nVoxel) +
" not:" + str(img.shape))
geox = copy.deepcopy(geo)
geox.check_geo(angles)
"""
Here we cast all values in geo to single point precision float. This way we
know what behaviour to expect from pytigre to Cuda and can change
single parameters accordingly.
"""
geox.cast_to_single()
#geox.checknans()
return _Ax_ext(img, geox, geox.angles, projection_type, geox.mode)
| Check the shape of input data earlier | Check the shape of input data earlier
Using geo.nVoxel to check the input img shape earlier, before geo is casted to float32 (geox). We should use any() instead of all(), since "!=" is used? | Python | bsd-3-clause | CERN/TIGRE,CERN/TIGRE,CERN/TIGRE,CERN/TIGRE | from _Ax import _Ax_ext
import numpy as np
import copy
def Ax(img, geo, angles, projection_type="Siddon"):
if img.dtype != np.float32:
raise TypeError("Input data should be float32, not "+ str(img.dtype))
if not np.isreal(img).all():
raise ValueError("Complex types not compatible for projection.")
+ if any(img.shape != geo.nVoxel):
+ raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geo.nVoxel) +
+ " not:" + str(img.shape))
geox = copy.deepcopy(geo)
geox.check_geo(angles)
"""
Here we cast all values in geo to single point precision float. This way we
know what behaviour to expect from pytigre to Cuda and can change
single parameters accordingly.
"""
geox.cast_to_single()
#geox.checknans()
- if abs(img.shape - geox.nVoxel).max()>1e-8:
- raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geox.nVoxel) +
- " not:" + str(img.shape))
return _Ax_ext(img, geox, geox.angles, projection_type, geox.mode)
| Check the shape of input data earlier | ## Code Before:
from _Ax import _Ax_ext
import numpy as np
import copy
def Ax(img, geo, angles, projection_type="Siddon"):
if img.dtype != np.float32:
raise TypeError("Input data should be float32, not "+ str(img.dtype))
if not np.isreal(img).all():
raise ValueError("Complex types not compatible for projection.")
geox = copy.deepcopy(geo)
geox.check_geo(angles)
"""
Here we cast all values in geo to single point precision float. This way we
know what behaviour to expect from pytigre to Cuda and can change
single parameters accordingly.
"""
geox.cast_to_single()
#geox.checknans()
if abs(img.shape - geox.nVoxel).max()>1e-8:
raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geox.nVoxel) +
" not:" + str(img.shape))
return _Ax_ext(img, geox, geox.angles, projection_type, geox.mode)
## Instruction:
Check the shape of input data earlier
## Code After:
from _Ax import _Ax_ext
import numpy as np
import copy
def Ax(img, geo, angles, projection_type="Siddon"):
if img.dtype != np.float32:
raise TypeError("Input data should be float32, not "+ str(img.dtype))
if not np.isreal(img).all():
raise ValueError("Complex types not compatible for projection.")
if any(img.shape != geo.nVoxel):
raise ValueError("Input data should be of shape geo.nVoxel: "+ str(geo.nVoxel) +
" not:" + str(img.shape))
geox = copy.deepcopy(geo)
geox.check_geo(angles)
"""
Here we cast all values in geo to single point precision float. This way we
know what behaviour to expect from pytigre to Cuda and can change
single parameters accordingly.
"""
geox.cast_to_single()
#geox.checknans()
return _Ax_ext(img, geox, geox.angles, projection_type, geox.mode)
|
08d6c4414d72b5431d5a50013058f325f38d7b1c | txdbus/test/test_message.py | txdbus/test/test_message.py | import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_reserved_path(self):
def c():
message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo')
self.assertRaises(error.MarshallingError, c)
def test_invalid_message_type(self):
class E(message.ErrorMessage):
_messageType=99
try:
message.parseMessage(E('foo.bar', 5).rawMessage)
self.assertTrue(False)
except Exception as e:
self.assertEquals(str(e), 'Unknown Message Type: 99')
| import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_reserved_path(self):
def c():
message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo')
self.assertRaises(error.MarshallingError, c)
def test_invalid_message_type(self):
class E(message.ErrorMessage):
_messageType=99
try:
message.parseMessage(E('foo.bar', 5).rawMessage, oobFDs=[])
self.assertTrue(False)
except Exception as e:
self.assertEquals(str(e), 'Unknown Message Type: 99')
| Fix message tests after in message.parseMessage args three commits ago | Fix message tests after in message.parseMessage args three commits ago
(three commits ago is 08a6c170daa79e74ba538c928e183f441a0fb441)
| Python | mit | cocagne/txdbus | import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_reserved_path(self):
def c():
message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo')
self.assertRaises(error.MarshallingError, c)
def test_invalid_message_type(self):
class E(message.ErrorMessage):
_messageType=99
try:
- message.parseMessage(E('foo.bar', 5).rawMessage)
+ message.parseMessage(E('foo.bar', 5).rawMessage, oobFDs=[])
self.assertTrue(False)
except Exception as e:
self.assertEquals(str(e), 'Unknown Message Type: 99')
| Fix message tests after in message.parseMessage args three commits ago | ## Code Before:
import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_reserved_path(self):
def c():
message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo')
self.assertRaises(error.MarshallingError, c)
def test_invalid_message_type(self):
class E(message.ErrorMessage):
_messageType=99
try:
message.parseMessage(E('foo.bar', 5).rawMessage)
self.assertTrue(False)
except Exception as e:
self.assertEquals(str(e), 'Unknown Message Type: 99')
## Instruction:
Fix message tests after in message.parseMessage args three commits ago
## Code After:
import os
import unittest
from txdbus import error, message
class MessageTester(unittest.TestCase):
def test_too_long(self):
class E(message.ErrorMessage):
_maxMsgLen = 1
def c():
E('foo.bar', 5)
self.assertRaises(error.MarshallingError, c)
def test_reserved_path(self):
def c():
message.MethodCallMessage('/org/freedesktop/DBus/Local', 'foo')
self.assertRaises(error.MarshallingError, c)
def test_invalid_message_type(self):
class E(message.ErrorMessage):
_messageType=99
try:
message.parseMessage(E('foo.bar', 5).rawMessage, oobFDs=[])
self.assertTrue(False)
except Exception as e:
self.assertEquals(str(e), 'Unknown Message Type: 99')
|
84c2c987151451180281f1aecb0483321462340c | influxalchemy/__init__.py | influxalchemy/__init__.py | """ InfluxDB Alchemy. """
from .client import InfluxAlchemy
from .measurement import Measurement
__version__ = "0.1.0"
| """ InfluxDB Alchemy. """
import pkg_resources
from .client import InfluxAlchemy
from .measurement import Measurement
try:
__version__ = pkg_resources.get_distribution(__package__).version
except pkg_resources.DistributionNotFound: # pragma: no cover
__version__ = None # pragma: no cover
| Use package version for __version__ | Use package version for __version__
| Python | mit | amancevice/influxalchemy | """ InfluxDB Alchemy. """
+ import pkg_resources
from .client import InfluxAlchemy
from .measurement import Measurement
- __version__ = "0.1.0"
+ try:
+ __version__ = pkg_resources.get_distribution(__package__).version
+ except pkg_resources.DistributionNotFound: # pragma: no cover
+ __version__ = None # pragma: no cover
+ | Use package version for __version__ | ## Code Before:
""" InfluxDB Alchemy. """
from .client import InfluxAlchemy
from .measurement import Measurement
__version__ = "0.1.0"
## Instruction:
Use package version for __version__
## Code After:
""" InfluxDB Alchemy. """
import pkg_resources
from .client import InfluxAlchemy
from .measurement import Measurement
try:
__version__ = pkg_resources.get_distribution(__package__).version
except pkg_resources.DistributionNotFound: # pragma: no cover
__version__ = None # pragma: no cover
|
fc6e3c276ee638fbb4409fa00d470817205f2028 | lib/awsflow/test/workflow_testing_context.py | lib/awsflow/test/workflow_testing_context.py | from awsflow.core import AsyncEventLoop
from awsflow.context import ContextBase
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
self._context = self.get_context()
self.set_context(self)
self._event_loop.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self._event_loop.execute_all_tasks()
self._event_loop.__exit__(exc_type, exc_val, exc_tb)
| from awsflow.core import AsyncEventLoop
from awsflow.context import ContextBase
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
try:
self._context = self.get_context()
except AttributeError:
self._context = None
self.set_context(self)
self._event_loop.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self._event_loop.execute_all_tasks()
self._event_loop.__exit__(exc_type, exc_val, exc_tb)
| Fix context setting on the test context | Fix context setting on the test context
| Python | apache-2.0 | darjus/botoflow,boto/botoflow | from awsflow.core import AsyncEventLoop
from awsflow.context import ContextBase
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
+ try:
- self._context = self.get_context()
+ self._context = self.get_context()
+ except AttributeError:
+ self._context = None
self.set_context(self)
self._event_loop.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self._event_loop.execute_all_tasks()
self._event_loop.__exit__(exc_type, exc_val, exc_tb)
| Fix context setting on the test context | ## Code Before:
from awsflow.core import AsyncEventLoop
from awsflow.context import ContextBase
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
self._context = self.get_context()
self.set_context(self)
self._event_loop.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self._event_loop.execute_all_tasks()
self._event_loop.__exit__(exc_type, exc_val, exc_tb)
## Instruction:
Fix context setting on the test context
## Code After:
from awsflow.core import AsyncEventLoop
from awsflow.context import ContextBase
class WorkflowTestingContext(ContextBase):
def __init__(self):
self._event_loop = AsyncEventLoop()
def __enter__(self):
try:
self._context = self.get_context()
except AttributeError:
self._context = None
self.set_context(self)
self._event_loop.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self._event_loop.execute_all_tasks()
self._event_loop.__exit__(exc_type, exc_val, exc_tb)
|
b3fb2ba913a836a1e198795019870e318879d5f7 | dictionary/forms.py | dictionary/forms.py | from django import forms
from django.forms.models import BaseModelFormSet
from django.utils.translation import ugettext_lazy as _
class BaseWordFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(BaseWordFormSet, self).add_fields(form, index)
form.fields["isLocal"] = forms.BooleanField(label=_("Local"))
| from django import forms
from django.forms.models import BaseModelFormSet
from django.utils.translation import ugettext_lazy as _
class BaseWordFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(BaseWordFormSet, self).add_fields(form, index)
form.fields["isLocal"] = forms.BooleanField(label=_("Local"), required=False)
| Make sure the isLocal BooleanField is not required | Make sure the isLocal BooleanField is not required
| Python | agpl-3.0 | sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer,sbsdev/daisyproducer | from django import forms
from django.forms.models import BaseModelFormSet
from django.utils.translation import ugettext_lazy as _
class BaseWordFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(BaseWordFormSet, self).add_fields(form, index)
- form.fields["isLocal"] = forms.BooleanField(label=_("Local"))
+ form.fields["isLocal"] = forms.BooleanField(label=_("Local"), required=False)
| Make sure the isLocal BooleanField is not required | ## Code Before:
from django import forms
from django.forms.models import BaseModelFormSet
from django.utils.translation import ugettext_lazy as _
class BaseWordFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(BaseWordFormSet, self).add_fields(form, index)
form.fields["isLocal"] = forms.BooleanField(label=_("Local"))
## Instruction:
Make sure the isLocal BooleanField is not required
## Code After:
from django import forms
from django.forms.models import BaseModelFormSet
from django.utils.translation import ugettext_lazy as _
class BaseWordFormSet(BaseModelFormSet):
def add_fields(self, form, index):
super(BaseWordFormSet, self).add_fields(form, index)
form.fields["isLocal"] = forms.BooleanField(label=_("Local"), required=False)
|
e34b7c8d9e869ac1be10e8ae3d71cea794044e13 | docs/blender-sphinx-build.py | docs/blender-sphinx-build.py | import os
import site # get site-packages into sys.path
import sys
# add local addons folder to sys.path so blender finds it
sys.path = (
[os.path.join(os.path.dirname(__file__), '..', 'scripts', 'addons')]
+ sys.path
)
# run sphinx builder
# this assumes that the builder is called as
# "blender --background --factory-startup --python blender-sphinx-build.py -- ..."
# pass the correct arguments by dropping the arguments prior to --
import sphinx
argv = ['blender-sphinx-build'] + sys.argv[6:]
sphinx.main(argv=argv)
| import os
import site # get site-packages into sys.path
import sys
# add local addons folder to sys.path so blender finds it
sys.path = (
[os.path.join(os.path.dirname(__file__), '..')]
+ sys.path
)
# run sphinx builder
# this assumes that the builder is called as
# "blender --background --factory-startup --python blender-sphinx-build.py -- ..."
# pass the correct arguments by dropping the arguments prior to --
import sphinx
argv = ['blender-sphinx-build'] + sys.argv[6:]
sphinx.main(argv=argv)
| Correct sys.path when generating docs. | Correct sys.path when generating docs.
| Python | bsd-3-clause | nightstrike/blender_nif_plugin,amorilia/blender_nif_plugin,amorilia/blender_nif_plugin,nightstrike/blender_nif_plugin | import os
import site # get site-packages into sys.path
import sys
# add local addons folder to sys.path so blender finds it
sys.path = (
- [os.path.join(os.path.dirname(__file__), '..', 'scripts', 'addons')]
+ [os.path.join(os.path.dirname(__file__), '..')]
+ sys.path
)
# run sphinx builder
# this assumes that the builder is called as
# "blender --background --factory-startup --python blender-sphinx-build.py -- ..."
# pass the correct arguments by dropping the arguments prior to --
import sphinx
argv = ['blender-sphinx-build'] + sys.argv[6:]
sphinx.main(argv=argv)
| Correct sys.path when generating docs. | ## Code Before:
import os
import site # get site-packages into sys.path
import sys
# add local addons folder to sys.path so blender finds it
sys.path = (
[os.path.join(os.path.dirname(__file__), '..', 'scripts', 'addons')]
+ sys.path
)
# run sphinx builder
# this assumes that the builder is called as
# "blender --background --factory-startup --python blender-sphinx-build.py -- ..."
# pass the correct arguments by dropping the arguments prior to --
import sphinx
argv = ['blender-sphinx-build'] + sys.argv[6:]
sphinx.main(argv=argv)
## Instruction:
Correct sys.path when generating docs.
## Code After:
import os
import site # get site-packages into sys.path
import sys
# add local addons folder to sys.path so blender finds it
sys.path = (
[os.path.join(os.path.dirname(__file__), '..')]
+ sys.path
)
# run sphinx builder
# this assumes that the builder is called as
# "blender --background --factory-startup --python blender-sphinx-build.py -- ..."
# pass the correct arguments by dropping the arguments prior to --
import sphinx
argv = ['blender-sphinx-build'] + sys.argv[6:]
sphinx.main(argv=argv)
|
2f60d4665a960578ab97bdaf313893ec366c24f1 | kdb/default_config.py | kdb/default_config.py |
CONFIG = {
"server": {
"host": "irc.freenode.net",
"port": 6667
},
"bot": {
"nick": "kdb",
"ident": "kdb",
"name": "Knowledge Database Bot",
"channels": "#circuits",
},
"plugins": {
"broadcast.*": "enabled",
"channels.*": "enabled",
"core.*": "enabled",
"ctcp.*": "enabled",
"dnstools.*": "enabled",
"eval.*": "enabled",
"google.*": "enabled",
"greeting.*": "enabled",
"help.*": "enabled",
"irc.*": "enabled",
"stats.*": "enabled",
"swatch.*": "enabled",
"timers.*": "enabled",
},
}
|
CONFIG = {
"server": {
"host": "irc.freenode.net",
"port": 6667
},
"bot": {
"nick": "kdb",
"ident": "kdb",
"name": "Knowledge Database Bot",
"channels": "#circuits",
},
"plugins": {
"broadcast.*": "enabled",
"channels.*": "enabled",
"core.*": "enabled",
"ctcp.*": "enabled",
"dnstools.*": "enabled",
"eval.*": "enabled",
"google.*": "enabled",
"greeting.*": "enabled",
"help.*": "enabled",
"irc.*": "enabled",
"remote.*": "enabled",
"rmessage.*": "enabled",
"rnotify.*": "enabled",
"stats.*": "enabled",
"swatch.*": "enabled",
"timers.*": "enabled",
},
}
| Enable remote, rmessage and rnotify plugins by default | Enable remote, rmessage and rnotify plugins by default
| Python | mit | prologic/kdb,prologic/kdb,prologic/kdb |
CONFIG = {
"server": {
"host": "irc.freenode.net",
"port": 6667
},
"bot": {
"nick": "kdb",
"ident": "kdb",
"name": "Knowledge Database Bot",
"channels": "#circuits",
},
"plugins": {
"broadcast.*": "enabled",
"channels.*": "enabled",
"core.*": "enabled",
"ctcp.*": "enabled",
"dnstools.*": "enabled",
"eval.*": "enabled",
"google.*": "enabled",
"greeting.*": "enabled",
"help.*": "enabled",
"irc.*": "enabled",
+ "remote.*": "enabled",
+ "rmessage.*": "enabled",
+ "rnotify.*": "enabled",
"stats.*": "enabled",
"swatch.*": "enabled",
"timers.*": "enabled",
},
}
| Enable remote, rmessage and rnotify plugins by default | ## Code Before:
CONFIG = {
"server": {
"host": "irc.freenode.net",
"port": 6667
},
"bot": {
"nick": "kdb",
"ident": "kdb",
"name": "Knowledge Database Bot",
"channels": "#circuits",
},
"plugins": {
"broadcast.*": "enabled",
"channels.*": "enabled",
"core.*": "enabled",
"ctcp.*": "enabled",
"dnstools.*": "enabled",
"eval.*": "enabled",
"google.*": "enabled",
"greeting.*": "enabled",
"help.*": "enabled",
"irc.*": "enabled",
"stats.*": "enabled",
"swatch.*": "enabled",
"timers.*": "enabled",
},
}
## Instruction:
Enable remote, rmessage and rnotify plugins by default
## Code After:
CONFIG = {
"server": {
"host": "irc.freenode.net",
"port": 6667
},
"bot": {
"nick": "kdb",
"ident": "kdb",
"name": "Knowledge Database Bot",
"channels": "#circuits",
},
"plugins": {
"broadcast.*": "enabled",
"channels.*": "enabled",
"core.*": "enabled",
"ctcp.*": "enabled",
"dnstools.*": "enabled",
"eval.*": "enabled",
"google.*": "enabled",
"greeting.*": "enabled",
"help.*": "enabled",
"irc.*": "enabled",
"remote.*": "enabled",
"rmessage.*": "enabled",
"rnotify.*": "enabled",
"stats.*": "enabled",
"swatch.*": "enabled",
"timers.*": "enabled",
},
}
|
6eca222d0bc36b2573a09c1345d940239f8e9d4d | documents/models.py | documents/models.py | from django.db import models
from django.urls import reverse
class Document(models.Model):
FILE_TYPES = ('md', 'txt')
repo = models.ForeignKey('interface.Repo', related_name='documents')
path = models.TextField()
filename = models.TextField()
body = models.TextField(blank=True)
commit_date = models.DateTimeField()
def __str__(self):
return '{}/{}'.format(self.path, self.filename)
@property
def github_view_link(self):
return 'https://github.com/{0}/blob/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, str(self))
@property
def github_edit_link(self):
return 'https://github.com/{0}/edit/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, str(self))
def get_absolute_url(self):
return reverse('repo_detail', kwargs={'full_name': self.repo.full_name, 'path': str(self)})
class Meta:
unique_together = ('repo', 'path', 'filename')
| from django.db import models
from django.urls import reverse
class Document(models.Model):
FILE_TYPES = ('md', 'txt')
repo = models.ForeignKey('interface.Repo', related_name='documents')
path = models.TextField()
filename = models.TextField()
body = models.TextField(blank=True)
commit_date = models.DateTimeField()
def __str__(self):
return self.full_path
@property
def full_path(self):
return '{}/{}'.format(self.path, self.filename)
@property
def github_view_link(self):
return 'https://github.com/{0}/blob/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, self.full_path)
@property
def github_edit_link(self):
return 'https://github.com/{0}/edit/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, self.full_path)
def get_absolute_url(self):
return reverse('repo_detail', kwargs={'full_name': self.repo.full_name, 'path': self.full_path})
class Meta:
unique_together = ('repo', 'path', 'filename')
| Move Document.__str__ to named method | Move Document.__str__ to named method
| Python | mit | ZeroCater/Eyrie,ZeroCater/Eyrie,ZeroCater/Eyrie | from django.db import models
from django.urls import reverse
class Document(models.Model):
FILE_TYPES = ('md', 'txt')
repo = models.ForeignKey('interface.Repo', related_name='documents')
path = models.TextField()
filename = models.TextField()
body = models.TextField(blank=True)
commit_date = models.DateTimeField()
def __str__(self):
+ return self.full_path
+
+ @property
+ def full_path(self):
return '{}/{}'.format(self.path, self.filename)
@property
def github_view_link(self):
- return 'https://github.com/{0}/blob/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, str(self))
+ return 'https://github.com/{0}/blob/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, self.full_path)
@property
def github_edit_link(self):
- return 'https://github.com/{0}/edit/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, str(self))
+ return 'https://github.com/{0}/edit/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, self.full_path)
def get_absolute_url(self):
- return reverse('repo_detail', kwargs={'full_name': self.repo.full_name, 'path': str(self)})
+ return reverse('repo_detail', kwargs={'full_name': self.repo.full_name, 'path': self.full_path})
class Meta:
unique_together = ('repo', 'path', 'filename')
| Move Document.__str__ to named method | ## Code Before:
from django.db import models
from django.urls import reverse
class Document(models.Model):
FILE_TYPES = ('md', 'txt')
repo = models.ForeignKey('interface.Repo', related_name='documents')
path = models.TextField()
filename = models.TextField()
body = models.TextField(blank=True)
commit_date = models.DateTimeField()
def __str__(self):
return '{}/{}'.format(self.path, self.filename)
@property
def github_view_link(self):
return 'https://github.com/{0}/blob/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, str(self))
@property
def github_edit_link(self):
return 'https://github.com/{0}/edit/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, str(self))
def get_absolute_url(self):
return reverse('repo_detail', kwargs={'full_name': self.repo.full_name, 'path': str(self)})
class Meta:
unique_together = ('repo', 'path', 'filename')
## Instruction:
Move Document.__str__ to named method
## Code After:
from django.db import models
from django.urls import reverse
class Document(models.Model):
FILE_TYPES = ('md', 'txt')
repo = models.ForeignKey('interface.Repo', related_name='documents')
path = models.TextField()
filename = models.TextField()
body = models.TextField(blank=True)
commit_date = models.DateTimeField()
def __str__(self):
return self.full_path
@property
def full_path(self):
return '{}/{}'.format(self.path, self.filename)
@property
def github_view_link(self):
return 'https://github.com/{0}/blob/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, self.full_path)
@property
def github_edit_link(self):
return 'https://github.com/{0}/edit/{1}{2}'.format(self.repo.full_name, self.repo.wiki_branch, self.full_path)
def get_absolute_url(self):
return reverse('repo_detail', kwargs={'full_name': self.repo.full_name, 'path': self.full_path})
class Meta:
unique_together = ('repo', 'path', 'filename')
|
89d9987f742fa74fc3646ccc163610d0c9400d75 | dewbrick/utils.py | dewbrick/utils.py | import tldextract
import pyphen
from random import choice
TITLES = ('Mister', 'Little Miss')
SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD')
def generate_name(domain):
title = choice(TITLES)
_parts = tldextract.extract(domain)
_parts = [_parts.subdomain, _parts.domain]
parts = []
for i, part in enumerate(_parts):
if part and part != 'www':
parts.append('{}{}'.format(part[0].upper(), part[1:]))
name = '-'.join(parts)
dic = pyphen.Pyphen(lang='en_US')
name = '{} {}'.format(title, dic.inserted(name))
if choice((True, False)):
name = '{} {}'.format(name, choice(SUFFIXES))
return name
| import tldextract
import pyphen
from random import choice
TITLES = ('Mister', 'Little Miss', 'Señor', 'Queen')
SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD',
'Ah-gowan-gowan-gowan')
def generate_name(domain):
title = choice(TITLES)
_parts = tldextract.extract(domain)
_parts = [_parts.subdomain, _parts.domain]
parts = []
for i, part in enumerate(_parts):
if part and part != 'www':
parts.append('{}{}'.format(part[0].upper(), part[1:]))
name = '-'.join(parts)
dic = pyphen.Pyphen(lang='en_US')
name = '{} {}'.format(title, dic.inserted(name))
if choice((True, False)):
name = '{} {}'.format(name, choice(SUFFIXES))
return name
| Add more titles and suffixes | Add more titles and suffixes
| Python | apache-2.0 | ohmygourd/dewbrick,ohmygourd/dewbrick,ohmygourd/dewbrick | import tldextract
import pyphen
from random import choice
- TITLES = ('Mister', 'Little Miss')
+ TITLES = ('Mister', 'Little Miss', 'Señor', 'Queen')
- SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD')
+ SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD',
+ 'Ah-gowan-gowan-gowan')
def generate_name(domain):
title = choice(TITLES)
_parts = tldextract.extract(domain)
_parts = [_parts.subdomain, _parts.domain]
parts = []
for i, part in enumerate(_parts):
if part and part != 'www':
parts.append('{}{}'.format(part[0].upper(), part[1:]))
name = '-'.join(parts)
dic = pyphen.Pyphen(lang='en_US')
name = '{} {}'.format(title, dic.inserted(name))
if choice((True, False)):
name = '{} {}'.format(name, choice(SUFFIXES))
return name
| Add more titles and suffixes | ## Code Before:
import tldextract
import pyphen
from random import choice
TITLES = ('Mister', 'Little Miss')
SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD')
def generate_name(domain):
title = choice(TITLES)
_parts = tldextract.extract(domain)
_parts = [_parts.subdomain, _parts.domain]
parts = []
for i, part in enumerate(_parts):
if part and part != 'www':
parts.append('{}{}'.format(part[0].upper(), part[1:]))
name = '-'.join(parts)
dic = pyphen.Pyphen(lang='en_US')
name = '{} {}'.format(title, dic.inserted(name))
if choice((True, False)):
name = '{} {}'.format(name, choice(SUFFIXES))
return name
## Instruction:
Add more titles and suffixes
## Code After:
import tldextract
import pyphen
from random import choice
TITLES = ('Mister', 'Little Miss', 'Señor', 'Queen')
SUFFIXES = ('Destroyer of Worlds', 'the Monkey Botherer', 'PhD',
'Ah-gowan-gowan-gowan')
def generate_name(domain):
title = choice(TITLES)
_parts = tldextract.extract(domain)
_parts = [_parts.subdomain, _parts.domain]
parts = []
for i, part in enumerate(_parts):
if part and part != 'www':
parts.append('{}{}'.format(part[0].upper(), part[1:]))
name = '-'.join(parts)
dic = pyphen.Pyphen(lang='en_US')
name = '{} {}'.format(title, dic.inserted(name))
if choice((True, False)):
name = '{} {}'.format(name, choice(SUFFIXES))
return name
|
e9814c857bdbf3d163352abddade1d12f0e30810 | mbaas/settings_jenkins.py | mbaas/settings_jenkins.py | from mbaas.settings import *
INSTALLED_APPS += ('django_nose',)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--cover-erase',
'--with-xunit',
'--with-coverage',
'--cover-xml',
'--cover-html',
'--cover-package=accounts,push',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test.db'),
}
}
| from mbaas.settings import *
INSTALLED_APPS += ('django_nose',)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-xunit',
'--with-coverage',
'--cover-xml',
'--cover-html',
'--cover-package=accounts,push',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test.db'),
}
}
| Remove clear before test results | Remove clear before test results | Python | apache-2.0 | nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas | from mbaas.settings import *
INSTALLED_APPS += ('django_nose',)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
- '--cover-erase',
'--with-xunit',
'--with-coverage',
'--cover-xml',
'--cover-html',
'--cover-package=accounts,push',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test.db'),
}
}
| Remove clear before test results | ## Code Before:
from mbaas.settings import *
INSTALLED_APPS += ('django_nose',)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--cover-erase',
'--with-xunit',
'--with-coverage',
'--cover-xml',
'--cover-html',
'--cover-package=accounts,push',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test.db'),
}
}
## Instruction:
Remove clear before test results
## Code After:
from mbaas.settings import *
INSTALLED_APPS += ('django_nose',)
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--with-xunit',
'--with-coverage',
'--cover-xml',
'--cover-html',
'--cover-package=accounts,push',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'test.db'),
}
}
|
4b4ed18f01c13c321285463628bb0a3b70a75ac5 | test/conftest.py | test/conftest.py | import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so we need to
# destroy any homely modules that may have imported things based on this.
# Essentially we blast away the entire module and reload it from scratch.
for name in list(sys.modules.keys()):
if name.startswith('homely.'):
sys.modules.pop(name, None)
os.environ['HOME'] = home
return home
@pytest.fixture(scope="function")
def tmpdir(request):
path = tempfile.mkdtemp()
destructor = shutil.rmtree
def destructor(path):
print("rm -rf %s" % path)
shutil.rmtree(path)
request.addfinalizer(functools.partial(destructor, path))
return os.path.realpath(path)
| import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
old_home = os.environ['HOME']
try:
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so we need to
# destroy any homely modules that may have imported things based on this.
# Essentially we blast away the entire module and reload it from scratch.
for name in list(sys.modules.keys()):
if name.startswith('homely.'):
sys.modules.pop(name, None)
os.environ['HOME'] = home
yield home
finally:
os.environ['HOME'] = old_home
@pytest.fixture(scope="function")
def tmpdir(request):
path = tempfile.mkdtemp()
destructor = shutil.rmtree
def destructor(path):
print("rm -rf %s" % path)
shutil.rmtree(path)
request.addfinalizer(functools.partial(destructor, path))
return os.path.realpath(path)
| Rework HOME fixture so it doesn't leave os.environ corrupted | Rework HOME fixture so it doesn't leave os.environ corrupted
| Python | mit | phodge/homely,phodge/homely | import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
+ old_home = os.environ['HOME']
+
+ try:
- home = os.path.join(tmpdir, 'john')
+ home = os.path.join(tmpdir, 'john')
- os.mkdir(home)
+ os.mkdir(home)
- # NOTE: homely._utils makes use of os.environ['HOME'], so we need to
+ # NOTE: homely._utils makes use of os.environ['HOME'], so we need to
- # destroy any homely modules that may have imported things based on this.
+ # destroy any homely modules that may have imported things based on this.
- # Essentially we blast away the entire module and reload it from scratch.
+ # Essentially we blast away the entire module and reload it from scratch.
- for name in list(sys.modules.keys()):
+ for name in list(sys.modules.keys()):
- if name.startswith('homely.'):
+ if name.startswith('homely.'):
- sys.modules.pop(name, None)
+ sys.modules.pop(name, None)
- os.environ['HOME'] = home
+ os.environ['HOME'] = home
- return home
+ yield home
+ finally:
+ os.environ['HOME'] = old_home
@pytest.fixture(scope="function")
def tmpdir(request):
path = tempfile.mkdtemp()
destructor = shutil.rmtree
def destructor(path):
print("rm -rf %s" % path)
shutil.rmtree(path)
request.addfinalizer(functools.partial(destructor, path))
return os.path.realpath(path)
| Rework HOME fixture so it doesn't leave os.environ corrupted | ## Code Before:
import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so we need to
# destroy any homely modules that may have imported things based on this.
# Essentially we blast away the entire module and reload it from scratch.
for name in list(sys.modules.keys()):
if name.startswith('homely.'):
sys.modules.pop(name, None)
os.environ['HOME'] = home
return home
@pytest.fixture(scope="function")
def tmpdir(request):
path = tempfile.mkdtemp()
destructor = shutil.rmtree
def destructor(path):
print("rm -rf %s" % path)
shutil.rmtree(path)
request.addfinalizer(functools.partial(destructor, path))
return os.path.realpath(path)
## Instruction:
Rework HOME fixture so it doesn't leave os.environ corrupted
## Code After:
import functools
import os.path
import shutil
import sys
import tempfile
import pytest
@pytest.fixture(scope="function")
def HOME(tmpdir):
old_home = os.environ['HOME']
try:
home = os.path.join(tmpdir, 'john')
os.mkdir(home)
# NOTE: homely._utils makes use of os.environ['HOME'], so we need to
# destroy any homely modules that may have imported things based on this.
# Essentially we blast away the entire module and reload it from scratch.
for name in list(sys.modules.keys()):
if name.startswith('homely.'):
sys.modules.pop(name, None)
os.environ['HOME'] = home
yield home
finally:
os.environ['HOME'] = old_home
@pytest.fixture(scope="function")
def tmpdir(request):
path = tempfile.mkdtemp()
destructor = shutil.rmtree
def destructor(path):
print("rm -rf %s" % path)
shutil.rmtree(path)
request.addfinalizer(functools.partial(destructor, path))
return os.path.realpath(path)
|
edd5adc9be2a700421bd8e98af825322796b8714 | dns/models.py | dns/models.py | from google.appengine.ext import db
TOP_LEVEL_DOMAINS = 'com net org biz info'.split()
class Lookup(db.Model):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
Updates since 2010-01-01 use negative numbers for 60 bit hashes of
the SOA server name, see tools/update_dns.py.
"""
backwards = db.StringProperty(required=True) # For suffix matching.
timestamp = db.DateTimeProperty(required=True) # Created or updated.
com = db.IntegerProperty(indexed=False)
net = db.IntegerProperty(indexed=False)
org = db.IntegerProperty(indexed=False)
biz = db.IntegerProperty(indexed=False)
info = db.IntegerProperty(indexed=False)
| from google.appengine.ext import db
TOP_LEVEL_DOMAINS = """
com net org biz info
ag am at
be by
ch ck
de
es eu
fm
in io is it
la li ly
me mobi ms
name
ru
se sh sy
tel th to travel tv
us
""".split()
# Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN.
class UpgradeStringProperty(db.IntegerProperty):
def validate(self, value):
return unicode(value) if value else u''
class Lookup(db.Expando):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
Some updates on 2010-01-01 use negative numbers for 60 bit hashes of
the SOA server name.
Since 2010-01-02, this model inherits from Expando to flexibly add
more top level domains. Each property stores the authority name
server as string backwards, e.g. com.1and1.ns1 for better sorting.
"""
backwards = db.StringProperty(required=True) # For suffix matching.
timestamp = db.DateTimeProperty(required=True) # Created or updated.
com = UpgradeStringProperty()
net = UpgradeStringProperty()
org = UpgradeStringProperty()
biz = UpgradeStringProperty()
info = UpgradeStringProperty()
| Upgrade Lookup model to Expando and DNS result properties from integer to string. | Upgrade Lookup model to Expando and DNS result properties from integer to string.
| Python | mit | jcrocholl/nxdom,jcrocholl/nxdom | from google.appengine.ext import db
- TOP_LEVEL_DOMAINS = 'com net org biz info'.split()
+ TOP_LEVEL_DOMAINS = """
+ com net org biz info
+ ag am at
+ be by
+ ch ck
+ de
+ es eu
+ fm
+ in io is it
+ la li ly
+ me mobi ms
+ name
+ ru
+ se sh sy
+ tel th to travel tv
+ us
+ """.split()
+
+ # Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN.
+ class UpgradeStringProperty(db.IntegerProperty):
+
+ def validate(self, value):
+ return unicode(value) if value else u''
+
+
+
- class Lookup(db.Model):
+ class Lookup(db.Expando):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
- Updates since 2010-01-01 use negative numbers for 60 bit hashes of
+ Some updates on 2010-01-01 use negative numbers for 60 bit hashes of
- the SOA server name, see tools/update_dns.py.
+ the SOA server name.
+
+ Since 2010-01-02, this model inherits from Expando to flexibly add
+ more top level domains. Each property stores the authority name
+ server as string backwards, e.g. com.1and1.ns1 for better sorting.
"""
backwards = db.StringProperty(required=True) # For suffix matching.
timestamp = db.DateTimeProperty(required=True) # Created or updated.
- com = db.IntegerProperty(indexed=False)
- net = db.IntegerProperty(indexed=False)
- org = db.IntegerProperty(indexed=False)
- biz = db.IntegerProperty(indexed=False)
- info = db.IntegerProperty(indexed=False)
+ com = UpgradeStringProperty()
+ net = UpgradeStringProperty()
+ org = UpgradeStringProperty()
+ biz = UpgradeStringProperty()
+ info = UpgradeStringProperty()
| Upgrade Lookup model to Expando and DNS result properties from integer to string. | ## Code Before:
from google.appengine.ext import db
TOP_LEVEL_DOMAINS = 'com net org biz info'.split()
class Lookup(db.Model):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
Updates since 2010-01-01 use negative numbers for 60 bit hashes of
the SOA server name, see tools/update_dns.py.
"""
backwards = db.StringProperty(required=True) # For suffix matching.
timestamp = db.DateTimeProperty(required=True) # Created or updated.
com = db.IntegerProperty(indexed=False)
net = db.IntegerProperty(indexed=False)
org = db.IntegerProperty(indexed=False)
biz = db.IntegerProperty(indexed=False)
info = db.IntegerProperty(indexed=False)
## Instruction:
Upgrade Lookup model to Expando and DNS result properties from integer to string.
## Code After:
from google.appengine.ext import db
TOP_LEVEL_DOMAINS = """
com net org biz info
ag am at
be by
ch ck
de
es eu
fm
in io is it
la li ly
me mobi ms
name
ru
se sh sy
tel th to travel tv
us
""".split()
# Omitting nu, ph, st, ws because they don't seem to have NXDOMAIN.
class UpgradeStringProperty(db.IntegerProperty):
def validate(self, value):
return unicode(value) if value else u''
class Lookup(db.Expando):
"""
The datastore key name is the domain name, without top level.
IP address fields use 0 (zero) for NXDOMAIN because None is
returned for missing properties.
Some updates on 2010-01-01 use negative numbers for 60 bit hashes of
the SOA server name.
Since 2010-01-02, this model inherits from Expando to flexibly add
more top level domains. Each property stores the authority name
server as string backwards, e.g. com.1and1.ns1 for better sorting.
"""
backwards = db.StringProperty(required=True) # For suffix matching.
timestamp = db.DateTimeProperty(required=True) # Created or updated.
com = UpgradeStringProperty()
net = UpgradeStringProperty()
org = UpgradeStringProperty()
biz = UpgradeStringProperty()
info = UpgradeStringProperty()
|
00cbac852e83eb1f3ddc03ed70ad32494f16fdbf | caslogging.py | caslogging.py | from config import config
import logging as root_logging
# Set up the logger
logger = root_logging.getLogger()
logger.setLevel(root_logging.INFO)
logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
logging_file_handler = root_logging.FileHandler(config['logging']['filename'])
logging_file_handler.setLevel(root_logging.INFO)
logging_file_handler.setFormatter(logger_format)
logger.addHandler(logging_file_handler)
logging_stream_handler = root_logging.StreamHandler()
logging_stream_handler.setLevel(root_logging.INFO)
logging_stream_handler.setFormatter(logger_format)
logger.addHandler(logging_stream_handler)
logging = root_logging | from config import config
import logging as root_logging
# Set up the logger
logger = root_logging.getLogger()
logger.setLevel(root_logging.INFO)
logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S')
logging_file_handler = root_logging.FileHandler(config['logging_system']['filename'])
logging_file_handler.setLevel(root_logging.INFO)
logging_file_handler.setFormatter(logger_format)
logger.addHandler(logging_file_handler)
logging_stream_handler = root_logging.StreamHandler()
logging_stream_handler.setLevel(root_logging.INFO)
logging_stream_handler.setFormatter(logger_format)
logger.addHandler(logging_stream_handler)
logging = root_logging | Fix of the logging system exception | Fix of the logging system exception
Added a format to the date for the logging system. '%Y-%m-%d %H:%M:%S’.
Fixed an exception opening the logging file because the variable name
was not written correctly.
| Python | mit | bumper-app/bumper-bianca,bumper-app/bumper-bianca | from config import config
import logging as root_logging
# Set up the logger
logger = root_logging.getLogger()
logger.setLevel(root_logging.INFO)
- logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
+ logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S')
- logging_file_handler = root_logging.FileHandler(config['logging']['filename'])
+ logging_file_handler = root_logging.FileHandler(config['logging_system']['filename'])
logging_file_handler.setLevel(root_logging.INFO)
logging_file_handler.setFormatter(logger_format)
logger.addHandler(logging_file_handler)
logging_stream_handler = root_logging.StreamHandler()
logging_stream_handler.setLevel(root_logging.INFO)
logging_stream_handler.setFormatter(logger_format)
logger.addHandler(logging_stream_handler)
logging = root_logging | Fix of the logging system exception | ## Code Before:
from config import config
import logging as root_logging
# Set up the logger
logger = root_logging.getLogger()
logger.setLevel(root_logging.INFO)
logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
logging_file_handler = root_logging.FileHandler(config['logging']['filename'])
logging_file_handler.setLevel(root_logging.INFO)
logging_file_handler.setFormatter(logger_format)
logger.addHandler(logging_file_handler)
logging_stream_handler = root_logging.StreamHandler()
logging_stream_handler.setLevel(root_logging.INFO)
logging_stream_handler.setFormatter(logger_format)
logger.addHandler(logging_stream_handler)
logging = root_logging
## Instruction:
Fix of the logging system exception
## Code After:
from config import config
import logging as root_logging
# Set up the logger
logger = root_logging.getLogger()
logger.setLevel(root_logging.INFO)
logger_format = root_logging.Formatter('%(asctime)s %(levelname)s: %(message)s', '%Y-%m-%d %H:%M:%S')
logging_file_handler = root_logging.FileHandler(config['logging_system']['filename'])
logging_file_handler.setLevel(root_logging.INFO)
logging_file_handler.setFormatter(logger_format)
logger.addHandler(logging_file_handler)
logging_stream_handler = root_logging.StreamHandler()
logging_stream_handler.setLevel(root_logging.INFO)
logging_stream_handler.setFormatter(logger_format)
logger.addHandler(logging_stream_handler)
logging = root_logging |
8bacd0f657a931754d8c03e2de86c5e00ac5f791 | modoboa/lib/cryptutils.py | modoboa/lib/cryptutils.py | from Crypto.Cipher import AES
import base64
import random
import string
from modoboa.lib import parameters
def random_key(l=16):
"""Generate a random key
:param integer l: the key's length
:return: a string
"""
char_set = string.digits + string.letters + string.punctuation
return ''.join(random.sample(char_set * l, l))
def encrypt(clear):
key = parameters.get_admin("SECRET_KEY", app="core")
obj = AES.new(key, AES.MODE_ECB)
if type(clear) is unicode:
clear = clear.encode("utf-8")
if len(clear) % AES.block_size:
clear += " " * (AES.block_size - len(clear) % AES.block_size)
ciph = obj.encrypt(clear)
ciph = base64.b64encode(ciph)
return ciph
def decrypt(ciph):
obj = AES.new(
parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB
)
ciph = base64.b64decode(ciph)
clear = obj.decrypt(ciph)
return clear.rstrip(' ')
def get_password(request):
return decrypt(request.session["password"])
| """Crypto related utilities."""
import base64
import random
import string
from Crypto.Cipher import AES
from modoboa.lib import parameters
def random_key(l=16):
"""Generate a random key.
:param integer l: the key's length
:return: a string
"""
population = string.digits + string.letters + string.punctuation
while True:
key = "".join(random.sample(population * l, l))
if len(key) == l:
return key
def encrypt(clear):
key = parameters.get_admin("SECRET_KEY", app="core")
obj = AES.new(key, AES.MODE_ECB)
if type(clear) is unicode:
clear = clear.encode("utf-8")
if len(clear) % AES.block_size:
clear += " " * (AES.block_size - len(clear) % AES.block_size)
ciph = obj.encrypt(clear)
ciph = base64.b64encode(ciph)
return ciph
def decrypt(ciph):
obj = AES.new(
parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB
)
ciph = base64.b64decode(ciph)
clear = obj.decrypt(ciph)
return clear.rstrip(' ')
def get_password(request):
return decrypt(request.session["password"])
| Make sure key has the required size. | Make sure key has the required size.
see #867
| Python | isc | tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,tonioo/modoboa,modoboa/modoboa,bearstech/modoboa,carragom/modoboa,bearstech/modoboa,bearstech/modoboa,modoboa/modoboa,carragom/modoboa,modoboa/modoboa,tonioo/modoboa | - from Crypto.Cipher import AES
+ """Crypto related utilities."""
+
import base64
import random
import string
+
+ from Crypto.Cipher import AES
+
from modoboa.lib import parameters
def random_key(l=16):
- """Generate a random key
+ """Generate a random key.
:param integer l: the key's length
:return: a string
"""
- char_set = string.digits + string.letters + string.punctuation
+ population = string.digits + string.letters + string.punctuation
- return ''.join(random.sample(char_set * l, l))
+ while True:
+ key = "".join(random.sample(population * l, l))
+ if len(key) == l:
+ return key
def encrypt(clear):
key = parameters.get_admin("SECRET_KEY", app="core")
obj = AES.new(key, AES.MODE_ECB)
if type(clear) is unicode:
clear = clear.encode("utf-8")
if len(clear) % AES.block_size:
clear += " " * (AES.block_size - len(clear) % AES.block_size)
ciph = obj.encrypt(clear)
ciph = base64.b64encode(ciph)
return ciph
def decrypt(ciph):
obj = AES.new(
parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB
)
ciph = base64.b64decode(ciph)
clear = obj.decrypt(ciph)
return clear.rstrip(' ')
def get_password(request):
return decrypt(request.session["password"])
| Make sure key has the required size. | ## Code Before:
from Crypto.Cipher import AES
import base64
import random
import string
from modoboa.lib import parameters
def random_key(l=16):
"""Generate a random key
:param integer l: the key's length
:return: a string
"""
char_set = string.digits + string.letters + string.punctuation
return ''.join(random.sample(char_set * l, l))
def encrypt(clear):
key = parameters.get_admin("SECRET_KEY", app="core")
obj = AES.new(key, AES.MODE_ECB)
if type(clear) is unicode:
clear = clear.encode("utf-8")
if len(clear) % AES.block_size:
clear += " " * (AES.block_size - len(clear) % AES.block_size)
ciph = obj.encrypt(clear)
ciph = base64.b64encode(ciph)
return ciph
def decrypt(ciph):
obj = AES.new(
parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB
)
ciph = base64.b64decode(ciph)
clear = obj.decrypt(ciph)
return clear.rstrip(' ')
def get_password(request):
return decrypt(request.session["password"])
## Instruction:
Make sure key has the required size.
## Code After:
"""Crypto related utilities."""
import base64
import random
import string
from Crypto.Cipher import AES
from modoboa.lib import parameters
def random_key(l=16):
"""Generate a random key.
:param integer l: the key's length
:return: a string
"""
population = string.digits + string.letters + string.punctuation
while True:
key = "".join(random.sample(population * l, l))
if len(key) == l:
return key
def encrypt(clear):
key = parameters.get_admin("SECRET_KEY", app="core")
obj = AES.new(key, AES.MODE_ECB)
if type(clear) is unicode:
clear = clear.encode("utf-8")
if len(clear) % AES.block_size:
clear += " " * (AES.block_size - len(clear) % AES.block_size)
ciph = obj.encrypt(clear)
ciph = base64.b64encode(ciph)
return ciph
def decrypt(ciph):
obj = AES.new(
parameters.get_admin("SECRET_KEY", app="core"), AES.MODE_ECB
)
ciph = base64.b64decode(ciph)
clear = obj.decrypt(ciph)
return clear.rstrip(' ')
def get_password(request):
return decrypt(request.session["password"])
|
61cef22952451df6345355ad596b38cb92697256 | flocker/test/test_flocker.py | flocker/test/test_flocker.py |
from sys import executable
from subprocess import check_output, STDOUT
from twisted.trial.unittest import SynchronousTestCase
class WarningsTests(SynchronousTestCase):
"""
Tests for warning suppression.
"""
def test_warnings_suppressed(self):
"""
Warnings are suppressed for processes that import flocker.
"""
result = check_output(
[executable, b"-c", (b"import flocker; import warnings; " +
b"warnings.warn('ohno')")],
stderr=STDOUT)
self.assertEqual(result, b"")
|
from sys import executable
from subprocess import check_output, STDOUT
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath
import flocker
class WarningsTests(SynchronousTestCase):
"""
Tests for warning suppression.
"""
def test_warnings_suppressed(self):
"""
Warnings are suppressed for processes that import flocker.
"""
root = FilePath(flocker.__file__)
result = check_output(
[executable, b"-c", (b"import flocker; import warnings; " +
b"warnings.warn('ohno')")],
stderr=STDOUT,
# Make sure we can import flocker package:
cwd=root.parent().parent().path)
self.assertEqual(result, b"")
| Make sure flocker package can be imported even if it's not installed. | Make sure flocker package can be imported even if it's not installed.
| Python | apache-2.0 | beni55/flocker,hackday-profilers/flocker,achanda/flocker,adamtheturtle/flocker,mbrukman/flocker,Azulinho/flocker,w4ngyi/flocker,agonzalezro/flocker,agonzalezro/flocker,1d4Nf6/flocker,moypray/flocker,AndyHuu/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,w4ngyi/flocker,Azulinho/flocker,LaynePeng/flocker,lukemarsden/flocker,mbrukman/flocker,moypray/flocker,LaynePeng/flocker,runcom/flocker,AndyHuu/flocker,runcom/flocker,wallnerryan/flocker-profiles,AndyHuu/flocker,agonzalezro/flocker,w4ngyi/flocker,achanda/flocker,hackday-profilers/flocker,adamtheturtle/flocker,lukemarsden/flocker,1d4Nf6/flocker,jml/flocker,runcom/flocker,LaynePeng/flocker,beni55/flocker,adamtheturtle/flocker,moypray/flocker,achanda/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,Azulinho/flocker,beni55/flocker,1d4Nf6/flocker,jml/flocker,jml/flocker |
from sys import executable
from subprocess import check_output, STDOUT
from twisted.trial.unittest import SynchronousTestCase
+ from twisted.python.filepath import FilePath
+
+ import flocker
class WarningsTests(SynchronousTestCase):
"""
Tests for warning suppression.
"""
def test_warnings_suppressed(self):
"""
Warnings are suppressed for processes that import flocker.
"""
+ root = FilePath(flocker.__file__)
result = check_output(
[executable, b"-c", (b"import flocker; import warnings; " +
b"warnings.warn('ohno')")],
- stderr=STDOUT)
+ stderr=STDOUT,
+ # Make sure we can import flocker package:
+ cwd=root.parent().parent().path)
self.assertEqual(result, b"")
| Make sure flocker package can be imported even if it's not installed. | ## Code Before:
from sys import executable
from subprocess import check_output, STDOUT
from twisted.trial.unittest import SynchronousTestCase
class WarningsTests(SynchronousTestCase):
"""
Tests for warning suppression.
"""
def test_warnings_suppressed(self):
"""
Warnings are suppressed for processes that import flocker.
"""
result = check_output(
[executable, b"-c", (b"import flocker; import warnings; " +
b"warnings.warn('ohno')")],
stderr=STDOUT)
self.assertEqual(result, b"")
## Instruction:
Make sure flocker package can be imported even if it's not installed.
## Code After:
from sys import executable
from subprocess import check_output, STDOUT
from twisted.trial.unittest import SynchronousTestCase
from twisted.python.filepath import FilePath
import flocker
class WarningsTests(SynchronousTestCase):
"""
Tests for warning suppression.
"""
def test_warnings_suppressed(self):
"""
Warnings are suppressed for processes that import flocker.
"""
root = FilePath(flocker.__file__)
result = check_output(
[executable, b"-c", (b"import flocker; import warnings; " +
b"warnings.warn('ohno')")],
stderr=STDOUT,
# Make sure we can import flocker package:
cwd=root.parent().parent().path)
self.assertEqual(result, b"")
|
384822f44d0731f425698cc67115d179d8d13e4c | examples/mastery.py | examples/mastery.py | import cassiopeia as cass
from cassiopeia.core import Summoner
def test_cass():
name = "Kalturi"
masteries = cass.get_masteries()
for mastery in masteries:
print(mastery.name)
if __name__ == "__main__":
test_cass()
| import cassiopeia as cass
def print_masteries():
for mastery in cass.get_masteries():
print(mastery.name)
if __name__ == "__main__":
print_masteries()
| Remove redundant import, change function name. | Remove redundant import, change function name.
| Python | mit | 10se1ucgo/cassiopeia,meraki-analytics/cassiopeia,robrua/cassiopeia | import cassiopeia as cass
- from cassiopeia.core import Summoner
- def test_cass():
- name = "Kalturi"
+ def print_masteries():
- masteries = cass.get_masteries()
+ for mastery in cass.get_masteries():
- for mastery in masteries:
print(mastery.name)
if __name__ == "__main__":
- test_cass()
+ print_masteries()
| Remove redundant import, change function name. | ## Code Before:
import cassiopeia as cass
from cassiopeia.core import Summoner
def test_cass():
name = "Kalturi"
masteries = cass.get_masteries()
for mastery in masteries:
print(mastery.name)
if __name__ == "__main__":
test_cass()
## Instruction:
Remove redundant import, change function name.
## Code After:
import cassiopeia as cass
def print_masteries():
for mastery in cass.get_masteries():
print(mastery.name)
if __name__ == "__main__":
print_masteries()
|
e49638c1b2f844e3fa74e00b0d0a96b7c9774c24 | test/test_box.py | test/test_box.py | from nex import box
def test_glue_flex():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=False)
assert h_box.stretch == [50 + 350]
assert h_box.shrink == [20 + 21]
def test_glue_flex_set():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=True)
assert h_box.stretch == [0]
assert h_box.shrink == [0]
| from nex.dampf.dvi_document import DVIDocument
from nex import box, box_writer
def test_glue_flex():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=False)
assert h_box.stretch == [50 + 350]
assert h_box.shrink == [20 + 21]
def test_glue_flex_set():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=True)
assert h_box.stretch == [0]
assert h_box.shrink == [0]
def test_box_writer():
doc = DVIDocument(magnification=1000)
lay_list = [
box.Rule(1, 1, 1),
box.Glue(1, 2, 3),
box.HBox([
box.Glue(3, 2, 1),
box.Rule(3, 3, 3),
]),
]
box_writer.write_box_to_doc(doc, lay_list)
| Add basic test for box writer | Add basic test for box writer
| Python | mit | eddiejessup/nex | + from nex.dampf.dvi_document import DVIDocument
- from nex import box
+ from nex import box, box_writer
def test_glue_flex():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=False)
assert h_box.stretch == [50 + 350]
assert h_box.shrink == [20 + 21]
def test_glue_flex_set():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=True)
assert h_box.stretch == [0]
assert h_box.shrink == [0]
+
+ def test_box_writer():
+ doc = DVIDocument(magnification=1000)
+ lay_list = [
+ box.Rule(1, 1, 1),
+ box.Glue(1, 2, 3),
+ box.HBox([
+ box.Glue(3, 2, 1),
+ box.Rule(3, 3, 3),
+ ]),
+ ]
+ box_writer.write_box_to_doc(doc, lay_list)
+ | Add basic test for box writer | ## Code Before:
from nex import box
def test_glue_flex():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=False)
assert h_box.stretch == [50 + 350]
assert h_box.shrink == [20 + 21]
def test_glue_flex_set():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=True)
assert h_box.stretch == [0]
assert h_box.shrink == [0]
## Instruction:
Add basic test for box writer
## Code After:
from nex.dampf.dvi_document import DVIDocument
from nex import box, box_writer
def test_glue_flex():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=False)
assert h_box.stretch == [50 + 350]
assert h_box.shrink == [20 + 21]
def test_glue_flex_set():
h_box = box.HBox(contents=[box.Glue(dimen=100, stretch=50, shrink=20),
box.Glue(dimen=10, stretch=350, shrink=21)],
set_glue=True)
assert h_box.stretch == [0]
assert h_box.shrink == [0]
def test_box_writer():
doc = DVIDocument(magnification=1000)
lay_list = [
box.Rule(1, 1, 1),
box.Glue(1, 2, 3),
box.HBox([
box.Glue(3, 2, 1),
box.Rule(3, 3, 3),
]),
]
box_writer.write_box_to_doc(doc, lay_list)
|
921421e4d9e2d536596980e14286db5faa83dd5c | egpackager/cli.py | egpackager/cli.py |
import click
import sys
from egpackager.datasources import GspreadDataSource
@click.group()
def cli():
'''
'''
pass
@cli.command()
def register():
click.echo(click.style('Initialized the database', fg='green'))
@cli.command()
def list():
click.echo(click.style('Dropped the database', fg='red'))
if __name__ == '__main__':
sys.exit(cli())
|
import click
import sys
from egpackager.registry import RegistryManager
@click.group()
@click.pass_context
def cli(ctx):
'''
'''
ctx.obj = {}
ctx.obj['MANAGER'] = RegistryManager()
@cli.command()
@click.pass_context
@click.option('--type', type=click.Choice(['gspread']), help='type of data source')
@click.option('--uri', default='', help='URI to the data source')
@click.option('--credentials', default='', help='path to Google Drive API credentials JSON file')
@click.argument('raster', nargs=1)
def create_metadata(ctx, uri, type, credentials, raster):
if type == 'gspread':
try:
if uri == '':
raise click.ClickException('For Google spreadsheets, an URI must be provided')
elif credentials == '':
raise click.ClickException('For Google spreadsheets, a path to Google Drive API credentials JSON file must be provided')
else:
ctx.obj['MANAGER'].add_gpsread_datasource(uri, credentials)
except click.ClickException as e:
e.show()
except FileNotFoundError as e:
click.echo(click.style('File {0} not found'.format(credentials), fg='red'))
@cli.command()
def list():
click.echo(click.style('Dropped the database', fg='red'))
if __name__ == '__main__':
cli()
| Add basic options for the CLI | Add basic options for the CLI
| Python | mit | VUEG/egpackager |
import click
import sys
- from egpackager.datasources import GspreadDataSource
+ from egpackager.registry import RegistryManager
@click.group()
+ @click.pass_context
- def cli():
+ def cli(ctx):
'''
'''
- pass
+ ctx.obj = {}
+ ctx.obj['MANAGER'] = RegistryManager()
@cli.command()
- def register():
- click.echo(click.style('Initialized the database', fg='green'))
-
+ @click.pass_context
+ @click.option('--type', type=click.Choice(['gspread']), help='type of data source')
+ @click.option('--uri', default='', help='URI to the data source')
+ @click.option('--credentials', default='', help='path to Google Drive API credentials JSON file')
+ @click.argument('raster', nargs=1)
+ def create_metadata(ctx, uri, type, credentials, raster):
+ if type == 'gspread':
+ try:
+ if uri == '':
+ raise click.ClickException('For Google spreadsheets, an URI must be provided')
+ elif credentials == '':
+ raise click.ClickException('For Google spreadsheets, a path to Google Drive API credentials JSON file must be provided')
+ else:
+ ctx.obj['MANAGER'].add_gpsread_datasource(uri, credentials)
+ except click.ClickException as e:
+ e.show()
+ except FileNotFoundError as e:
+ click.echo(click.style('File {0} not found'.format(credentials), fg='red'))
@cli.command()
def list():
click.echo(click.style('Dropped the database', fg='red'))
if __name__ == '__main__':
- sys.exit(cli())
+ cli()
| Add basic options for the CLI | ## Code Before:
import click
import sys
from egpackager.datasources import GspreadDataSource
@click.group()
def cli():
'''
'''
pass
@cli.command()
def register():
click.echo(click.style('Initialized the database', fg='green'))
@cli.command()
def list():
click.echo(click.style('Dropped the database', fg='red'))
if __name__ == '__main__':
sys.exit(cli())
## Instruction:
Add basic options for the CLI
## Code After:
import click
import sys
from egpackager.registry import RegistryManager
@click.group()
@click.pass_context
def cli(ctx):
'''
'''
ctx.obj = {}
ctx.obj['MANAGER'] = RegistryManager()
@cli.command()
@click.pass_context
@click.option('--type', type=click.Choice(['gspread']), help='type of data source')
@click.option('--uri', default='', help='URI to the data source')
@click.option('--credentials', default='', help='path to Google Drive API credentials JSON file')
@click.argument('raster', nargs=1)
def create_metadata(ctx, uri, type, credentials, raster):
if type == 'gspread':
try:
if uri == '':
raise click.ClickException('For Google spreadsheets, an URI must be provided')
elif credentials == '':
raise click.ClickException('For Google spreadsheets, a path to Google Drive API credentials JSON file must be provided')
else:
ctx.obj['MANAGER'].add_gpsread_datasource(uri, credentials)
except click.ClickException as e:
e.show()
except FileNotFoundError as e:
click.echo(click.style('File {0} not found'.format(credentials), fg='red'))
@cli.command()
def list():
click.echo(click.style('Dropped the database', fg='red'))
if __name__ == '__main__':
cli()
|
bd2d1869894b30eb83eb11ec6e9814e7ab2d4168 | panda/api/activity_log.py | panda/api/activity_log.py |
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
return bundle
|
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpConflict
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from django.db import IntegrityError
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
try:
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
except IntegrityError:
raise ImmediateHttpResponse(response=HttpConflict('Activity has already been recorded.'))
return bundle
| Return 409 for duplicate activity logging. | Return 409 for duplicate activity logging.
| Python | mit | ibrahimcesar/panda,PalmBeachPost/panda,ibrahimcesar/panda,NUKnightLab/panda,pandaproject/panda,datadesk/panda,newsapps/panda,ibrahimcesar/panda,newsapps/panda,pandaproject/panda,PalmBeachPost/panda,PalmBeachPost/panda,NUKnightLab/panda,pandaproject/panda,pandaproject/panda,ibrahimcesar/panda,ibrahimcesar/panda,PalmBeachPost/panda,datadesk/panda,datadesk/panda,NUKnightLab/panda,PalmBeachPost/panda,datadesk/panda,newsapps/panda,NUKnightLab/panda,newsapps/panda,pandaproject/panda,datadesk/panda |
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
+ from tastypie.exceptions import ImmediateHttpResponse
+ from tastypie.http import HttpConflict
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
+ from django.db import IntegrityError
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
+ try:
- bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
+ bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
+ except IntegrityError:
+ raise ImmediateHttpResponse(response=HttpConflict('Activity has already been recorded.'))
return bundle
| Return 409 for duplicate activity logging. | ## Code Before:
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
return bundle
## Instruction:
Return 409 for duplicate activity logging.
## Code After:
from tastypie import fields
from tastypie.authorization import DjangoAuthorization
from tastypie.exceptions import ImmediateHttpResponse
from tastypie.http import HttpConflict
from panda.api.utils import PandaApiKeyAuthentication, PandaModelResource, PandaSerializer
from django.db import IntegrityError
from panda.models import ActivityLog
class ActivityLogResource(PandaModelResource):
"""
API resource for DataUploads.
"""
from panda.api.users import UserResource
creator = fields.ForeignKey(UserResource, 'user', full=True)
class Meta:
queryset = ActivityLog.objects.all()
resource_name = 'activity_log'
allowed_methods = ['get', 'post']
authentication = PandaApiKeyAuthentication()
authorization = DjangoAuthorization()
serializer = PandaSerializer()
def obj_create(self, bundle, request=None, **kwargs):
"""
Create an activity log for the accessing user.
"""
try:
bundle = super(ActivityLogResource, self).obj_create(bundle, request=request, user=request.user, **kwargs)
except IntegrityError:
raise ImmediateHttpResponse(response=HttpConflict('Activity has already been recorded.'))
return bundle
|
b07964e8b243b151e64af86cb09a37e980f94eb1 | vantage/utils.py | vantage/utils.py | import binascii
import base64
import click
def to_base64(value):
value = base64.urlsafe_b64encode(value.encode("utf-8")).decode("utf-8")
return f"base64:{value}"
def from_base64(value):
if value.startswith("base64:"):
try:
value = base64.urlsafe_b64decode(value[7:]).decode("utf-8")
except binascii.Error:
pass
return value
def loquacious(line):
try:
env = click.get_current_context().obj
if env is not None and env.get("VG_VERBOSE"):
click.echo(f"VG-LOG: {line}")
except RuntimeError:
# This happens when there's no active click context so we can't get the
# env. In this case we default to not printing the verbose logs.
# This situation happens when you're trying to autocomplete
pass
| import binascii
import base64
import click
def to_base64(value):
value = base64.urlsafe_b64encode(value.encode("utf-8")).decode("utf-8")
return f"base64:{value}"
def from_base64(value):
if value.startswith("base64:"):
try:
value = base64.urlsafe_b64decode(value[7:]).decode("utf-8")
except binascii.Error:
pass
return value
def loquacious(line, env=None):
try:
env = env or click.get_current_context().obj
if env is not None and env.get("VG_VERBOSE"):
click.echo(f"VG-LOG: {line}")
except RuntimeError:
# This happens when there's no active click context so we can't get the
# env. In this case we default to not printing the verbose logs.
# This situation happens when you're trying to autocomplete
pass
| Add optional env kwargs to logging method | Add optional env kwargs to logging method
| Python | mit | vantage-org/vantage,vantage-org/vantage | import binascii
import base64
import click
def to_base64(value):
value = base64.urlsafe_b64encode(value.encode("utf-8")).decode("utf-8")
return f"base64:{value}"
def from_base64(value):
if value.startswith("base64:"):
try:
value = base64.urlsafe_b64decode(value[7:]).decode("utf-8")
except binascii.Error:
pass
return value
- def loquacious(line):
+ def loquacious(line, env=None):
try:
- env = click.get_current_context().obj
+ env = env or click.get_current_context().obj
if env is not None and env.get("VG_VERBOSE"):
click.echo(f"VG-LOG: {line}")
except RuntimeError:
# This happens when there's no active click context so we can't get the
# env. In this case we default to not printing the verbose logs.
# This situation happens when you're trying to autocomplete
pass
| Add optional env kwargs to logging method | ## Code Before:
import binascii
import base64
import click
def to_base64(value):
value = base64.urlsafe_b64encode(value.encode("utf-8")).decode("utf-8")
return f"base64:{value}"
def from_base64(value):
if value.startswith("base64:"):
try:
value = base64.urlsafe_b64decode(value[7:]).decode("utf-8")
except binascii.Error:
pass
return value
def loquacious(line):
try:
env = click.get_current_context().obj
if env is not None and env.get("VG_VERBOSE"):
click.echo(f"VG-LOG: {line}")
except RuntimeError:
# This happens when there's no active click context so we can't get the
# env. In this case we default to not printing the verbose logs.
# This situation happens when you're trying to autocomplete
pass
## Instruction:
Add optional env kwargs to logging method
## Code After:
import binascii
import base64
import click
def to_base64(value):
value = base64.urlsafe_b64encode(value.encode("utf-8")).decode("utf-8")
return f"base64:{value}"
def from_base64(value):
if value.startswith("base64:"):
try:
value = base64.urlsafe_b64decode(value[7:]).decode("utf-8")
except binascii.Error:
pass
return value
def loquacious(line, env=None):
try:
env = env or click.get_current_context().obj
if env is not None and env.get("VG_VERBOSE"):
click.echo(f"VG-LOG: {line}")
except RuntimeError:
# This happens when there's no active click context so we can't get the
# env. In this case we default to not printing the verbose logs.
# This situation happens when you're trying to autocomplete
pass
|
50784afbb0c95f435c1a25e0840438e406349bbb | plyer/facades/uniqueid.py | plyer/facades/uniqueid.py | '''UniqueID facade.
Returns the following depending on the platform:
* **Android**: Android ID
* **OS X**: Serial number of the device
* **Linux**: Serial number using lshw
* **Windows**: MachineGUID from regkey
Simple Example
--------------
To get the unique ID::
>>> from plyer import uniqueid
>>> uniqueid.id
'1b1a7a4958e2a845'
.. versionadded:: 1.2.0
.. versionchanged:: 1.2.4
On Android returns Android ID instead of IMEI.
'''
class UniqueID(object):
'''
UniqueID facade.
'''
@property
def id(self):
'''
Property that returns the unique id of the platform.
'''
return self.get_uid()
def get_uid(self):
return self._get_uid()
# private
def _get_uid(self, **kwargs):
raise NotImplementedError()
| '''UniqueID facade.
Returns the following depending on the platform:
* **Android**: Android ID
* **OS X**: Serial number of the device
* **Linux**: Serial number using lshw
* **Windows**: MachineGUID from regkey
* **iOS**: UUID
Simple Example
--------------
To get the unique ID::
>>> from plyer import uniqueid
>>> uniqueid.id
'1b1a7a4958e2a845'
.. versionadded:: 1.2.0
.. versionchanged:: 1.2.4
On Android returns Android ID instead of IMEI.
'''
class UniqueID(object):
'''
UniqueID facade.
'''
@property
def id(self):
'''
Property that returns the unique id of the platform.
'''
return self.get_uid()
def get_uid(self):
return self._get_uid()
# private
def _get_uid(self, **kwargs):
raise NotImplementedError()
| Add description for iOS in facade | Add description for iOS in facade
| Python | mit | kivy/plyer,kived/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer,kived/plyer,kivy/plyer,KeyWeeUsr/plyer | '''UniqueID facade.
Returns the following depending on the platform:
* **Android**: Android ID
* **OS X**: Serial number of the device
* **Linux**: Serial number using lshw
* **Windows**: MachineGUID from regkey
+ * **iOS**: UUID
Simple Example
--------------
To get the unique ID::
>>> from plyer import uniqueid
>>> uniqueid.id
'1b1a7a4958e2a845'
.. versionadded:: 1.2.0
.. versionchanged:: 1.2.4
On Android returns Android ID instead of IMEI.
'''
class UniqueID(object):
'''
UniqueID facade.
'''
@property
def id(self):
'''
Property that returns the unique id of the platform.
'''
return self.get_uid()
def get_uid(self):
return self._get_uid()
# private
def _get_uid(self, **kwargs):
raise NotImplementedError()
| Add description for iOS in facade | ## Code Before:
'''UniqueID facade.
Returns the following depending on the platform:
* **Android**: Android ID
* **OS X**: Serial number of the device
* **Linux**: Serial number using lshw
* **Windows**: MachineGUID from regkey
Simple Example
--------------
To get the unique ID::
>>> from plyer import uniqueid
>>> uniqueid.id
'1b1a7a4958e2a845'
.. versionadded:: 1.2.0
.. versionchanged:: 1.2.4
On Android returns Android ID instead of IMEI.
'''
class UniqueID(object):
'''
UniqueID facade.
'''
@property
def id(self):
'''
Property that returns the unique id of the platform.
'''
return self.get_uid()
def get_uid(self):
return self._get_uid()
# private
def _get_uid(self, **kwargs):
raise NotImplementedError()
## Instruction:
Add description for iOS in facade
## Code After:
'''UniqueID facade.
Returns the following depending on the platform:
* **Android**: Android ID
* **OS X**: Serial number of the device
* **Linux**: Serial number using lshw
* **Windows**: MachineGUID from regkey
* **iOS**: UUID
Simple Example
--------------
To get the unique ID::
>>> from plyer import uniqueid
>>> uniqueid.id
'1b1a7a4958e2a845'
.. versionadded:: 1.2.0
.. versionchanged:: 1.2.4
On Android returns Android ID instead of IMEI.
'''
class UniqueID(object):
'''
UniqueID facade.
'''
@property
def id(self):
'''
Property that returns the unique id of the platform.
'''
return self.get_uid()
def get_uid(self):
return self._get_uid()
# private
def _get_uid(self, **kwargs):
raise NotImplementedError()
|
82cb6d190ce1e805914cc791518c97e063ecdc96 | tests/test_individual.py | tests/test_individual.py | import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from BitVector import BitVector
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_get(self):
ind = Individual(9)
ind.data = bitarray("011010100")
self.assertEqual(ind.get(5), 1)
self.assertEqual(ind.get(1), 0)
self.assertEqual(ind.get(10), None)
def test_set(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.set(2, 1)
self.assertEqual(ind.get(2), 1)
ind.set(7, 0)
self.assertEqual(ind.get(7), 0)
ind.set(6, 1)
self.assertEqual(ind.get(6), 1)
def test_flip(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.flip(1)
self.assertEqual(ind.get(1), 1)
ind.flip(8)
self.assertEqual(ind.get(8), 1)
ind.flip(4)
self.assertEqual(ind.get(4), 1)
| import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_get(self):
ind = Individual(9)
ind.data = bitarray("011010100")
self.assertEqual(ind.get(5), 1)
self.assertEqual(ind.get(1), 0)
self.assertEqual(ind.get(10), None)
def test_set(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.set(2, 1)
self.assertEqual(ind.get(2), 1)
ind.set(7, 0)
self.assertEqual(ind.get(7), 0)
ind.set(6, 1)
self.assertEqual(ind.get(6), 1)
def test_flip(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.flip(1)
self.assertEqual(ind.get(1), 1)
ind.flip(8)
self.assertEqual(ind.get(8), 1)
ind.flip(4)
self.assertEqual(ind.get(4), 1)
| Remove BitVector import - Build fails | Remove BitVector import - Build fails | Python | mit | Imperium-Software/resolver,Imperium-Software/resolver,Imperium-Software/resolver,Imperium-Software/resolver | import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
- from BitVector import BitVector
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_get(self):
ind = Individual(9)
ind.data = bitarray("011010100")
self.assertEqual(ind.get(5), 1)
self.assertEqual(ind.get(1), 0)
self.assertEqual(ind.get(10), None)
def test_set(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.set(2, 1)
self.assertEqual(ind.get(2), 1)
ind.set(7, 0)
self.assertEqual(ind.get(7), 0)
ind.set(6, 1)
self.assertEqual(ind.get(6), 1)
def test_flip(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.flip(1)
self.assertEqual(ind.get(1), 1)
ind.flip(8)
self.assertEqual(ind.get(8), 1)
ind.flip(4)
self.assertEqual(ind.get(4), 1)
| Remove BitVector import - Build fails | ## Code Before:
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from BitVector import BitVector
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_get(self):
ind = Individual(9)
ind.data = bitarray("011010100")
self.assertEqual(ind.get(5), 1)
self.assertEqual(ind.get(1), 0)
self.assertEqual(ind.get(10), None)
def test_set(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.set(2, 1)
self.assertEqual(ind.get(2), 1)
ind.set(7, 0)
self.assertEqual(ind.get(7), 0)
ind.set(6, 1)
self.assertEqual(ind.get(6), 1)
def test_flip(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.flip(1)
self.assertEqual(ind.get(1), 1)
ind.flip(8)
self.assertEqual(ind.get(8), 1)
ind.flip(4)
self.assertEqual(ind.get(4), 1)
## Instruction:
Remove BitVector import - Build fails
## Code After:
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
print(myPath)
sys.path.insert(0, myPath + '/../SATSolver')
from unittest import TestCase
from individual import Individual
from bitarray import bitarray
class TestIndividual(TestCase):
"""
Testing class for Individual.
"""
def test_get(self):
ind = Individual(9)
ind.data = bitarray("011010100")
self.assertEqual(ind.get(5), 1)
self.assertEqual(ind.get(1), 0)
self.assertEqual(ind.get(10), None)
def test_set(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.set(2, 1)
self.assertEqual(ind.get(2), 1)
ind.set(7, 0)
self.assertEqual(ind.get(7), 0)
ind.set(6, 1)
self.assertEqual(ind.get(6), 1)
def test_flip(self):
ind = Individual(9)
ind.data = bitarray("011010100")
ind.flip(1)
self.assertEqual(ind.get(1), 1)
ind.flip(8)
self.assertEqual(ind.get(8), 1)
ind.flip(4)
self.assertEqual(ind.get(4), 1)
|
b2764b9ada2ca3bec548ceb82e71697f7515f14f | citrination_client/__init__.py | citrination_client/__init__.py | import os
import re
from citrination_client.base import *
from citrination_client.search import *
from citrination_client.data import *
from citrination_client.models import *
from citrination_client.views.descriptors import *
from .client import CitrinationClient
from pkg_resources import get_distribution, DistributionNotFound
def __get_version():
"""
Returns the version of this package, whether running from source or install
:return: The version of this package
"""
try:
# Try local first, if missing setup.py, then use pkg info
here = os.path.abspath(os.path.dirname(__file__))
print("here:"+here)
with open(os.path.join(here, "../setup.py")) as fp:
version_file = fp.read()
version_match = re.search(r"version=['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
except IOError:
pass
try:
_dist = get_distribution('citrination_client')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'citrination_client')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
raise RuntimeError("Unable to find version string.")
else:
return _dist.version
__version__ = __get_version()
| import os
import re
from citrination_client.base import *
from citrination_client.search import *
from citrination_client.data import *
from citrination_client.models import *
from citrination_client.views.descriptors import *
from .client import CitrinationClient
from pkg_resources import get_distribution, DistributionNotFound
def __get_version():
"""
Returns the version of this package, whether running from source or install
:return: The version of this package
"""
try:
# Try local first, if missing setup.py, then use pkg info
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "../setup.py")) as fp:
version_file = fp.read()
version_match = re.search(r"version=['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
except IOError:
pass
try:
_dist = get_distribution('citrination_client')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'citrination_client')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
raise RuntimeError("Unable to find version string.")
else:
return _dist.version
__version__ = __get_version()
| Remove debug print on getVersion | Remove debug print on getVersion
| Python | apache-2.0 | CitrineInformatics/python-citrination-client | import os
import re
from citrination_client.base import *
from citrination_client.search import *
from citrination_client.data import *
from citrination_client.models import *
from citrination_client.views.descriptors import *
from .client import CitrinationClient
from pkg_resources import get_distribution, DistributionNotFound
def __get_version():
"""
Returns the version of this package, whether running from source or install
:return: The version of this package
"""
try:
# Try local first, if missing setup.py, then use pkg info
here = os.path.abspath(os.path.dirname(__file__))
- print("here:"+here)
with open(os.path.join(here, "../setup.py")) as fp:
version_file = fp.read()
version_match = re.search(r"version=['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
except IOError:
pass
try:
_dist = get_distribution('citrination_client')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'citrination_client')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
raise RuntimeError("Unable to find version string.")
else:
return _dist.version
__version__ = __get_version()
| Remove debug print on getVersion | ## Code Before:
import os
import re
from citrination_client.base import *
from citrination_client.search import *
from citrination_client.data import *
from citrination_client.models import *
from citrination_client.views.descriptors import *
from .client import CitrinationClient
from pkg_resources import get_distribution, DistributionNotFound
def __get_version():
"""
Returns the version of this package, whether running from source or install
:return: The version of this package
"""
try:
# Try local first, if missing setup.py, then use pkg info
here = os.path.abspath(os.path.dirname(__file__))
print("here:"+here)
with open(os.path.join(here, "../setup.py")) as fp:
version_file = fp.read()
version_match = re.search(r"version=['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
except IOError:
pass
try:
_dist = get_distribution('citrination_client')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'citrination_client')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
raise RuntimeError("Unable to find version string.")
else:
return _dist.version
__version__ = __get_version()
## Instruction:
Remove debug print on getVersion
## Code After:
import os
import re
from citrination_client.base import *
from citrination_client.search import *
from citrination_client.data import *
from citrination_client.models import *
from citrination_client.views.descriptors import *
from .client import CitrinationClient
from pkg_resources import get_distribution, DistributionNotFound
def __get_version():
"""
Returns the version of this package, whether running from source or install
:return: The version of this package
"""
try:
# Try local first, if missing setup.py, then use pkg info
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "../setup.py")) as fp:
version_file = fp.read()
version_match = re.search(r"version=['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
except IOError:
pass
try:
_dist = get_distribution('citrination_client')
# Normalize case for Windows systems
dist_loc = os.path.normcase(_dist.location)
here = os.path.normcase(__file__)
if not here.startswith(os.path.join(dist_loc, 'citrination_client')):
# not installed, but there is another version that *is*
raise DistributionNotFound
except DistributionNotFound:
raise RuntimeError("Unable to find version string.")
else:
return _dist.version
__version__ = __get_version()
|
2f140327c24a8efab5482a975793dddedd0ebfc4 | nucleus/wsgi.py | nucleus/wsgi.py | # newrelic.agent must be imported and initialized first
# https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration
import newrelic.agent
newrelic.agent.initialize('newrelic.ini')
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nucleus.settings') # NOQA
from django.core.handlers.wsgi import WSGIRequest
from django.core.wsgi import get_wsgi_application
from decouple import config
IS_HTTPS = config('HTTPS', default='off', cast=bool)
class WSGIHTTPSRequest(WSGIRequest):
def _get_scheme(self):
if IS_HTTPS:
return 'https'
return super(WSGIHTTPSRequest, self)._get_scheme()
application = get_wsgi_application()
application.request_class = WSGIHTTPSRequest
if config('SENTRY_DSN', None):
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
application = Sentry(application)
newrelic_license_key = config('NEW_RELIC_LICENSE_KEY', default=None)
if newrelic_license_key:
application = newrelic.agent.WSGIApplicationWrapper(application)
| import newrelic.agent
newrelic.agent.initialize('newrelic.ini')
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nucleus.settings') # NOQA
from django.core.handlers.wsgi import WSGIRequest
from django.core.wsgi import get_wsgi_application
from decouple import config
IS_HTTPS = config('HTTPS', default='off', cast=bool)
class WSGIHTTPSRequest(WSGIRequest):
def _get_scheme(self):
if IS_HTTPS:
return 'https'
return super(WSGIHTTPSRequest, self)._get_scheme()
application = get_wsgi_application()
application.request_class = WSGIHTTPSRequest
if config('SENTRY_DSN', None):
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
application = Sentry(application)
newrelic_license_key = config('NEW_RELIC_LICENSE_KEY', default=None)
if newrelic_license_key:
application = newrelic.agent.WSGIApplicationWrapper(application)
| Remove old docstring with link to old django docs | Remove old docstring with link to old django docs
| Python | mpl-2.0 | mozilla/nucleus,mozilla/nucleus,mozilla/nucleus,mozilla/nucleus | - # newrelic.agent must be imported and initialized first
- # https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration
import newrelic.agent
newrelic.agent.initialize('newrelic.ini')
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nucleus.settings') # NOQA
from django.core.handlers.wsgi import WSGIRequest
from django.core.wsgi import get_wsgi_application
from decouple import config
IS_HTTPS = config('HTTPS', default='off', cast=bool)
class WSGIHTTPSRequest(WSGIRequest):
def _get_scheme(self):
if IS_HTTPS:
return 'https'
return super(WSGIHTTPSRequest, self)._get_scheme()
application = get_wsgi_application()
application.request_class = WSGIHTTPSRequest
if config('SENTRY_DSN', None):
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
application = Sentry(application)
newrelic_license_key = config('NEW_RELIC_LICENSE_KEY', default=None)
if newrelic_license_key:
application = newrelic.agent.WSGIApplicationWrapper(application)
| Remove old docstring with link to old django docs | ## Code Before:
# newrelic.agent must be imported and initialized first
# https://docs.newrelic.com/docs/agents/python-agent/installation/python-agent-advanced-integration#manual-integration
import newrelic.agent
newrelic.agent.initialize('newrelic.ini')
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nucleus.settings') # NOQA
from django.core.handlers.wsgi import WSGIRequest
from django.core.wsgi import get_wsgi_application
from decouple import config
IS_HTTPS = config('HTTPS', default='off', cast=bool)
class WSGIHTTPSRequest(WSGIRequest):
def _get_scheme(self):
if IS_HTTPS:
return 'https'
return super(WSGIHTTPSRequest, self)._get_scheme()
application = get_wsgi_application()
application.request_class = WSGIHTTPSRequest
if config('SENTRY_DSN', None):
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
application = Sentry(application)
newrelic_license_key = config('NEW_RELIC_LICENSE_KEY', default=None)
if newrelic_license_key:
application = newrelic.agent.WSGIApplicationWrapper(application)
## Instruction:
Remove old docstring with link to old django docs
## Code After:
import newrelic.agent
newrelic.agent.initialize('newrelic.ini')
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nucleus.settings') # NOQA
from django.core.handlers.wsgi import WSGIRequest
from django.core.wsgi import get_wsgi_application
from decouple import config
IS_HTTPS = config('HTTPS', default='off', cast=bool)
class WSGIHTTPSRequest(WSGIRequest):
def _get_scheme(self):
if IS_HTTPS:
return 'https'
return super(WSGIHTTPSRequest, self)._get_scheme()
application = get_wsgi_application()
application.request_class = WSGIHTTPSRequest
if config('SENTRY_DSN', None):
from raven.contrib.django.raven_compat.middleware.wsgi import Sentry
application = Sentry(application)
newrelic_license_key = config('NEW_RELIC_LICENSE_KEY', default=None)
if newrelic_license_key:
application = newrelic.agent.WSGIApplicationWrapper(application)
|
18bf9dd5e1e054d0c260959a8379f331940e167f | online_status/__init__.py | online_status/__init__.py | VERSION = (0, 1, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = "%s %s" % (version, VERSION[3])
if VERSION[4] != 0:
version = '%s %s' % (version, VERSION[4])
return version
| VERSION = (0, 1, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
return version
| Fix 'index out of bound' issue | Fix 'index out of bound' issue
| Python | unlicense | hovel/django-online-status,hovel/django-online-status | VERSION = (0, 1, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
- if VERSION[3:] == ('alpha', 0):
- version = '%s pre-alpha' % version
- else:
- if VERSION[3] != 'final':
- version = "%s %s" % (version, VERSION[3])
- if VERSION[4] != 0:
- version = '%s %s' % (version, VERSION[4])
return version
| Fix 'index out of bound' issue | ## Code Before:
VERSION = (0, 1, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
if VERSION[3:] == ('alpha', 0):
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
version = "%s %s" % (version, VERSION[3])
if VERSION[4] != 0:
version = '%s %s' % (version, VERSION[4])
return version
## Instruction:
Fix 'index out of bound' issue
## Code After:
VERSION = (0, 1, 0)
def get_version():
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2]:
version = '%s.%s' % (version, VERSION[2])
return version
|
b064d8dbc4be13c12c1c87491ebcb484ab71ac52 | geopy/__init__.py | geopy/__init__.py |
from geopy.point import Point
from geopy.location import Location
from geopy.geocoders import * # pylint: disable=W0401
from geopy.util import __version__
|
from geopy.location import Location
from geopy.point import Point
from geopy.util import __version__
from geopy.geocoders import * # noqa
# geopy.geocoders.options must not be importable as `geopy.options`,
# because that is ambiguous (which options are that).
del options # noqa
| Fix geocoder.options being also exported as `geopy.options` | Fix geocoder.options being also exported as `geopy.options`
| Python | mit | geopy/geopy,jmb/geopy |
+ from geopy.location import Location
from geopy.point import Point
- from geopy.location import Location
- from geopy.geocoders import * # pylint: disable=W0401
from geopy.util import __version__
+ from geopy.geocoders import * # noqa
+ # geopy.geocoders.options must not be importable as `geopy.options`,
+ # because that is ambiguous (which options are that).
+ del options # noqa
+ | Fix geocoder.options being also exported as `geopy.options` | ## Code Before:
from geopy.point import Point
from geopy.location import Location
from geopy.geocoders import * # pylint: disable=W0401
from geopy.util import __version__
## Instruction:
Fix geocoder.options being also exported as `geopy.options`
## Code After:
from geopy.location import Location
from geopy.point import Point
from geopy.util import __version__
from geopy.geocoders import * # noqa
# geopy.geocoders.options must not be importable as `geopy.options`,
# because that is ambiguous (which options are that).
del options # noqa
|
a6e6e6bf18c48638d4c6c7d97f894edd3fc3c1ad | ipython_config.py | ipython_config.py | c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
| c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
c.TerminalInteractiveShell.editor = 'gvim'
| Set default shell editor for ipython to gvim | Set default shell editor for ipython to gvim
| Python | mit | brycepg/dotfiles,brycepg/dotfiles | c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
+ c.TerminalInteractiveShell.editor = 'gvim'
| Set default shell editor for ipython to gvim | ## Code Before:
c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
## Instruction:
Set default shell editor for ipython to gvim
## Code After:
c.InteractiveShellApp.exec_lines = []
# ipython-autoimport - Automatically import modules
c.InteractiveShellApp.exec_lines.append(
"try:\n %load_ext ipython_autoimport\nexcept ImportError: pass")
# Automatically reload modules
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
c.TerminalInteractiveShell.editor = 'gvim'
|
78ca9c6b8393b1b4f4bddf41febc87696796d28a | openpassword/openssl_utils.py | openpassword/openssl_utils.py | from Crypto.Hash import MD5
def derive_openssl_key(key, salt, hash=MD5):
key = key[0:-16]
openssl_key = bytes()
prev = bytes()
while len(openssl_key) < 32:
prev = hash.new(prev + key + salt).digest()
openssl_key += prev
return openssl_key
| from Crypto.Hash import MD5
def derive_openssl_key(key, salt, hashing_function=MD5):
key = key[0:-16]
openssl_key = bytes()
prev = bytes()
while len(openssl_key) < 32:
prev = hashing_function.new(prev + key + salt).digest()
openssl_key += prev
return openssl_key
| Rename hash variable to prevent colision with native method | Rename hash variable to prevent colision with native method
| Python | mit | openpassword/blimey,openpassword/blimey | from Crypto.Hash import MD5
- def derive_openssl_key(key, salt, hash=MD5):
+ def derive_openssl_key(key, salt, hashing_function=MD5):
key = key[0:-16]
openssl_key = bytes()
prev = bytes()
while len(openssl_key) < 32:
- prev = hash.new(prev + key + salt).digest()
+ prev = hashing_function.new(prev + key + salt).digest()
openssl_key += prev
return openssl_key
| Rename hash variable to prevent colision with native method | ## Code Before:
from Crypto.Hash import MD5
def derive_openssl_key(key, salt, hash=MD5):
key = key[0:-16]
openssl_key = bytes()
prev = bytes()
while len(openssl_key) < 32:
prev = hash.new(prev + key + salt).digest()
openssl_key += prev
return openssl_key
## Instruction:
Rename hash variable to prevent colision with native method
## Code After:
from Crypto.Hash import MD5
def derive_openssl_key(key, salt, hashing_function=MD5):
key = key[0:-16]
openssl_key = bytes()
prev = bytes()
while len(openssl_key) < 32:
prev = hashing_function.new(prev + key + salt).digest()
openssl_key += prev
return openssl_key
|
2c6dd79d419699e61970719dbb369aefe359ea6e | tests/test_db.py | tests/test_db.py | from pypinfo import db
CREDS_FILE = '/path/to/creds_file.json'
def test_get_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Assert
assert db.get_credentials() is None
def test_set_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
def test_set_credentials_twice(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
db.set_credentials(CREDS_FILE)
def test_round_trip(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
# Assert
assert db.get_credentials() == CREDS_FILE
def test_get_credentials_table(tmp_path):
db.DB_FILE = str(tmp_path / 'db.json')
with db.get_credentials_table() as table:
assert not table._storage._storage._handle.closed
with db.get_credentials_table(table) as table2:
assert table2 is table
assert not table._storage._storage._handle.closed
assert table._storage._storage._handle.closed
| from pypinfo import db
CREDS_FILE = '/path/to/creds_file.json'
def test_get_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Assert
assert db.get_credentials() is None
def test_set_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
def test_set_credentials_twice(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
db.set_credentials(CREDS_FILE)
def test_round_trip(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
# Assert
assert db.get_credentials() == CREDS_FILE
def test_get_credentials_table(tmp_path):
db.DB_FILE = str(tmp_path / 'db.json')
with db.get_credentials_table() as table:
assert not table._storage._handle.closed
with db.get_credentials_table(table) as table2:
assert table2 is table
assert not table._storage._handle.closed
assert table._storage._handle.closed
| Fix tests for updated TinyDB/Tinyrecord | Fix tests for updated TinyDB/Tinyrecord
| Python | mit | ofek/pypinfo | from pypinfo import db
CREDS_FILE = '/path/to/creds_file.json'
def test_get_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Assert
assert db.get_credentials() is None
def test_set_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
def test_set_credentials_twice(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
db.set_credentials(CREDS_FILE)
def test_round_trip(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
# Assert
assert db.get_credentials() == CREDS_FILE
def test_get_credentials_table(tmp_path):
db.DB_FILE = str(tmp_path / 'db.json')
with db.get_credentials_table() as table:
- assert not table._storage._storage._handle.closed
+ assert not table._storage._handle.closed
with db.get_credentials_table(table) as table2:
assert table2 is table
- assert not table._storage._storage._handle.closed
+ assert not table._storage._handle.closed
- assert table._storage._storage._handle.closed
+ assert table._storage._handle.closed
| Fix tests for updated TinyDB/Tinyrecord | ## Code Before:
from pypinfo import db
CREDS_FILE = '/path/to/creds_file.json'
def test_get_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Assert
assert db.get_credentials() is None
def test_set_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
def test_set_credentials_twice(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
db.set_credentials(CREDS_FILE)
def test_round_trip(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
# Assert
assert db.get_credentials() == CREDS_FILE
def test_get_credentials_table(tmp_path):
db.DB_FILE = str(tmp_path / 'db.json')
with db.get_credentials_table() as table:
assert not table._storage._storage._handle.closed
with db.get_credentials_table(table) as table2:
assert table2 is table
assert not table._storage._storage._handle.closed
assert table._storage._storage._handle.closed
## Instruction:
Fix tests for updated TinyDB/Tinyrecord
## Code After:
from pypinfo import db
CREDS_FILE = '/path/to/creds_file.json'
def test_get_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Assert
assert db.get_credentials() is None
def test_set_credentials(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
def test_set_credentials_twice(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
db.set_credentials(CREDS_FILE)
def test_round_trip(tmp_path):
# Arrange
db.DB_FILE = str(tmp_path / 'db.json') # Mock
# Act
db.set_credentials(CREDS_FILE)
# Assert
assert db.get_credentials() == CREDS_FILE
def test_get_credentials_table(tmp_path):
db.DB_FILE = str(tmp_path / 'db.json')
with db.get_credentials_table() as table:
assert not table._storage._handle.closed
with db.get_credentials_table(table) as table2:
assert table2 is table
assert not table._storage._handle.closed
assert table._storage._handle.closed
|
3f909cdfba61719dfa0a860aeba1e418fe740f33 | indra/__init__.py | indra/__init__.py | from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format='%(levelname)s: [%(asctime)s] indra/%(name)s - %(message)s',
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
| from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format=('%(levelname)s: [%(asctime)s] %(name)s'
' - %(message)s'),
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
| Remove indra prefix from logger | Remove indra prefix from logger
| Python | bsd-2-clause | bgyori/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra | from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
- logging.basicConfig(format='%(levelname)s: [%(asctime)s] indra/%(name)s - %(message)s',
+ logging.basicConfig(format=('%(levelname)s: [%(asctime)s] %(name)s'
+ ' - %(message)s'),
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
| Remove indra prefix from logger | ## Code Before:
from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format='%(levelname)s: [%(asctime)s] indra/%(name)s - %(message)s',
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
## Instruction:
Remove indra prefix from logger
## Code After:
from __future__ import print_function, unicode_literals
import logging
import os
import sys
__version__ = '1.10.0'
__all__ = ['assemblers', 'belief', 'databases', 'explanation', 'literature',
'mechlinker', 'preassembler', 'sources', 'tools', 'util']
logging.basicConfig(format=('%(levelname)s: [%(asctime)s] %(name)s'
' - %(message)s'),
level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')
# Suppress INFO-level logging from some dependencies
logging.getLogger('requests').setLevel(logging.ERROR)
logging.getLogger('urllib3').setLevel(logging.ERROR)
logging.getLogger('rdflib').setLevel(logging.ERROR)
logging.getLogger('boto3').setLevel(logging.CRITICAL)
logging.getLogger('botocore').setLevel(logging.CRITICAL)
# This is specifically to suppress lib2to3 logging from networkx
import lib2to3.pgen2.driver
class Lib2to3LoggingModuleShim(object):
def getLogger(self):
return logging.getLogger('lib2to3')
lib2to3.pgen2.driver.logging = Lib2to3LoggingModuleShim()
logging.getLogger('lib2to3').setLevel(logging.ERROR)
logger = logging.getLogger('indra')
from .config import get_config, has_config
|
70b7090a438f7962f28acc23fa78cdb6f5d084a0 | docs/sphinxext/configtraits.py | docs/sphinxext/configtraits.py | from sphinx.locale import l_
from sphinx.util.docfields import Field
def setup(app):
app.add_object_type('configtrait', 'configtrait', objname='Config option')
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
|
def setup(app):
app.add_object_type('configtrait', 'configtrait', objname='Config option')
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
| Fix compatibility with the latest release of Sphinx | Fix compatibility with the latest release of Sphinx
`l_` from sphinx.locale has been deprecated for a long time.
`_` is the new name for the same function but it seems that the
imports there are useless.
https://github.com/sphinx-doc/sphinx/commit/8d653a406dc0dc6c2632176ab4757ca15474b10f
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | +
- from sphinx.locale import l_
- from sphinx.util.docfields import Field
def setup(app):
app.add_object_type('configtrait', 'configtrait', objname='Config option')
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
| Fix compatibility with the latest release of Sphinx | ## Code Before:
from sphinx.locale import l_
from sphinx.util.docfields import Field
def setup(app):
app.add_object_type('configtrait', 'configtrait', objname='Config option')
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
## Instruction:
Fix compatibility with the latest release of Sphinx
## Code After:
def setup(app):
app.add_object_type('configtrait', 'configtrait', objname='Config option')
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
|
ea39c4ebba3d5ab42dfa202f88f7d76386e505fe | plugins/MeshView/MeshView.py | plugins/MeshView/MeshView.py | from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object, renderer):
if object.getMeshData():
renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())
for child in object.getChildren():
self._renderObject(child, renderer)
| from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object, renderer):
if not object.render():
if object.getMeshData():
renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())
for child in object.getChildren():
self._renderObject(child, renderer)
| Allow SceneObjects to render themselves | Allow SceneObjects to render themselves
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object, renderer):
+ if not object.render():
- if object.getMeshData():
+ if object.getMeshData():
- renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())
+ renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())
for child in object.getChildren():
self._renderObject(child, renderer)
| Allow SceneObjects to render themselves | ## Code Before:
from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object, renderer):
if object.getMeshData():
renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())
for child in object.getChildren():
self._renderObject(child, renderer)
## Instruction:
Allow SceneObjects to render themselves
## Code After:
from Cura.View.View import View
class MeshView(View):
def __init__(self):
super(MeshView, self).__init__()
def render(self):
scene = self.getController().getScene()
renderer = self.getRenderer()
self._renderObject(scene.getRoot(), renderer)
def _renderObject(self, object, renderer):
if not object.render():
if object.getMeshData():
renderer.renderMesh(object.getGlobalTransformation(), object.getMeshData())
for child in object.getChildren():
self._renderObject(child, renderer)
|
e733b0d5192437a95c4eafd1babc02385fb4fcf7 | cms/sitemaps/cms_sitemap.py | cms/sitemaps/cms_sitemap.py | from django.contrib.sitemaps import Sitemap
from django.utils import translation
from cms.models import Title
def from_iterable(iterables):
"""
Backport of itertools.chain.from_iterable
"""
for it in iterables:
for element in it:
yield element
class CMSSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
def items(self):
all_titles = Title.objects.public().filter(page__login_required=False)
return all_titles
def lastmod(self, title):
modification_dates = [title.page.changed_date, title.page.publication_date]
plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
modification_dates.extend(plugin_modification_dates)
return max(modification_dates)
def location(self, title):
translation.activate(title.language)
url = title.page.get_absolute_url(title.language)
translation.deactivate()
return url
|
from django.contrib.sitemaps import Sitemap
from django.db.models import Q
from django.utils import translation
from cms.models import Title
def from_iterable(iterables):
"""
Backport of itertools.chain.from_iterable
"""
for it in iterables:
for element in it:
yield element
class CMSSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
def items(self):
#
# It is counter-productive to provide entries for:
# > Pages which redirect:
# - If the page redirects to another page on this site, the
# destination page will already be in the sitemap, and
# - If the page redirects externally, then it shouldn't be
# part of our sitemap anyway.
# > Pages which cannot be accessed by anonymous users (like
# search engines are).
#
all_titles = Title.objects.public().filter(
Q(redirect='') | Q(redirect__isnull=True),
page__login_required=False
)
return all_titles
def lastmod(self, title):
modification_dates = [title.page.changed_date, title.page.publication_date]
plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
modification_dates.extend(plugin_modification_dates)
return max(modification_dates)
def location(self, title):
translation.activate(title.language)
url = title.page.get_absolute_url(title.language)
translation.deactivate()
return url
| Remove redirected pages from the sitemap | Remove redirected pages from the sitemap
| Python | bsd-3-clause | ScholzVolkmer/django-cms,wyg3958/django-cms,donce/django-cms,robmagee/django-cms,DylannCordel/django-cms,frnhr/django-cms,jrief/django-cms,wuzhihui1123/django-cms,Livefyre/django-cms,dhorelik/django-cms,netzkolchose/django-cms,intip/django-cms,chkir/django-cms,jproffitt/django-cms,selecsosi/django-cms,czpython/django-cms,liuyisiyisi/django-cms,takeshineshiro/django-cms,saintbird/django-cms,czpython/django-cms,memnonila/django-cms,FinalAngel/django-cms,farhaadila/django-cms,webu/django-cms,divio/django-cms,SmithsonianEnterprises/django-cms,sephii/django-cms,jproffitt/django-cms,czpython/django-cms,astagi/django-cms,bittner/django-cms,AlexProfi/django-cms,dhorelik/django-cms,nostalgiaz/django-cms,netzkolchose/django-cms,iddqd1/django-cms,jeffreylu9/django-cms,astagi/django-cms,SachaMPS/django-cms,chmberl/django-cms,qnub/django-cms,chkir/django-cms,nostalgiaz/django-cms,SachaMPS/django-cms,rscnt/django-cms,benzkji/django-cms,360youlun/django-cms,cyberintruder/django-cms,jproffitt/django-cms,nostalgiaz/django-cms,Vegasvikk/django-cms,FinalAngel/django-cms,wuzhihui1123/django-cms,SachaMPS/django-cms,datakortet/django-cms,farhaadila/django-cms,nimbis/django-cms,owers19856/django-cms,nimbis/django-cms,cyberintruder/django-cms,frnhr/django-cms,intip/django-cms,rsalmaso/django-cms,qnub/django-cms,liuyisiyisi/django-cms,SofiaReis/django-cms,jsma/django-cms,Jaccorot/django-cms,sznekol/django-cms,frnhr/django-cms,nimbis/django-cms,jrief/django-cms,FinalAngel/django-cms,leture/django-cms,philippze/django-cms,nimbis/django-cms,FinalAngel/django-cms,jproffitt/django-cms,frnhr/django-cms,netzkolchose/django-cms,360youlun/django-cms,stefanw/django-cms,owers19856/django-cms,intip/django-cms,takeshineshiro/django-cms,robmagee/django-cms,MagicSolutions/django-cms,benzkji/django-cms,bittner/django-cms,nostalgiaz/django-cms,bittner/django-cms,isotoma/django-cms,vxsx/django-cms,SofiaReis/django-cms,Vegasvikk/django-cms,vxsx/django-cms,philippze/django-cms,vxsx/django-cms,saintbird/django-cms,SmithsonianEnterprises/django-cms,chkir/django-cms,Vegasvikk/django-cms,astagi/django-cms,Jaccorot/django-cms,stefanfoulis/django-cms,divio/django-cms,irudayarajisawa/django-cms,petecummings/django-cms,petecummings/django-cms,vad/django-cms,vstoykov/django-cms,mkoistinen/django-cms,jrclaramunt/django-cms,webu/django-cms,vad/django-cms,sznekol/django-cms,evildmp/django-cms,AlexProfi/django-cms,rsalmaso/django-cms,rryan/django-cms,josjevv/django-cms,yakky/django-cms,rsalmaso/django-cms,takeshineshiro/django-cms,DylannCordel/django-cms,jrief/django-cms,jeffreylu9/django-cms,stefanw/django-cms,intip/django-cms,stefanw/django-cms,mkoistinen/django-cms,chmberl/django-cms,isotoma/django-cms,donce/django-cms,chmberl/django-cms,saintbird/django-cms,leture/django-cms,datakortet/django-cms,dhorelik/django-cms,Livefyre/django-cms,keimlink/django-cms,divio/django-cms,jsma/django-cms,keimlink/django-cms,ScholzVolkmer/django-cms,MagicSolutions/django-cms,selecsosi/django-cms,qnub/django-cms,jsma/django-cms,kk9599/django-cms,andyzsf/django-cms,selecsosi/django-cms,vstoykov/django-cms,wyg3958/django-cms,jeffreylu9/django-cms,bittner/django-cms,jrclaramunt/django-cms,mkoistinen/django-cms,rsalmaso/django-cms,timgraham/django-cms,yakky/django-cms,rscnt/django-cms,vad/django-cms,kk9599/django-cms,benzkji/django-cms,stefanfoulis/django-cms,memnonila/django-cms,donce/django-cms,petecummings/django-cms,isotoma/django-cms,datakortet/django-cms,Livefyre/django-cms,josjevv/django-cms,wuzhihui1123/django-cms,evildmp/django-cms,josjevv/django-cms,stefanw/django-cms,jeffreylu9/django-cms,ScholzVolkmer/django-cms,robmagee/django-cms,MagicSolutions/django-cms,yakky/django-cms,irudayarajisawa/django-cms,czpython/django-cms,leture/django-cms,timgraham/django-cms,evildmp/django-cms,youprofit/django-cms,mkoistinen/django-cms,webu/django-cms,datakortet/django-cms,sephii/django-cms,vad/django-cms,jsma/django-cms,keimlink/django-cms,evildmp/django-cms,vxsx/django-cms,kk9599/django-cms,iddqd1/django-cms,Livefyre/django-cms,vstoykov/django-cms,liuyisiyisi/django-cms,AlexProfi/django-cms,wyg3958/django-cms,farhaadila/django-cms,netzkolchose/django-cms,360youlun/django-cms,Jaccorot/django-cms,iddqd1/django-cms,andyzsf/django-cms,sephii/django-cms,yakky/django-cms,sznekol/django-cms,stefanfoulis/django-cms,andyzsf/django-cms,andyzsf/django-cms,SmithsonianEnterprises/django-cms,benzkji/django-cms,irudayarajisawa/django-cms,youprofit/django-cms,selecsosi/django-cms,philippze/django-cms,timgraham/django-cms,cyberintruder/django-cms,stefanfoulis/django-cms,jrclaramunt/django-cms,memnonila/django-cms,SofiaReis/django-cms,rscnt/django-cms,rryan/django-cms,rryan/django-cms,youprofit/django-cms,divio/django-cms,wuzhihui1123/django-cms,isotoma/django-cms,jrief/django-cms,sephii/django-cms,rryan/django-cms,DylannCordel/django-cms,owers19856/django-cms | +
from django.contrib.sitemaps import Sitemap
+ from django.db.models import Q
from django.utils import translation
+
from cms.models import Title
def from_iterable(iterables):
"""
Backport of itertools.chain.from_iterable
"""
for it in iterables:
for element in it:
yield element
class CMSSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
def items(self):
+ #
+ # It is counter-productive to provide entries for:
+ # > Pages which redirect:
+ # - If the page redirects to another page on this site, the
+ # destination page will already be in the sitemap, and
+ # - If the page redirects externally, then it shouldn't be
+ # part of our sitemap anyway.
+ # > Pages which cannot be accessed by anonymous users (like
+ # search engines are).
+ #
- all_titles = Title.objects.public().filter(page__login_required=False)
+ all_titles = Title.objects.public().filter(
+ Q(redirect='') | Q(redirect__isnull=True),
+ page__login_required=False
+ )
return all_titles
def lastmod(self, title):
modification_dates = [title.page.changed_date, title.page.publication_date]
plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
modification_dates.extend(plugin_modification_dates)
return max(modification_dates)
def location(self, title):
translation.activate(title.language)
url = title.page.get_absolute_url(title.language)
translation.deactivate()
return url
| Remove redirected pages from the sitemap | ## Code Before:
from django.contrib.sitemaps import Sitemap
from django.utils import translation
from cms.models import Title
def from_iterable(iterables):
"""
Backport of itertools.chain.from_iterable
"""
for it in iterables:
for element in it:
yield element
class CMSSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
def items(self):
all_titles = Title.objects.public().filter(page__login_required=False)
return all_titles
def lastmod(self, title):
modification_dates = [title.page.changed_date, title.page.publication_date]
plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
modification_dates.extend(plugin_modification_dates)
return max(modification_dates)
def location(self, title):
translation.activate(title.language)
url = title.page.get_absolute_url(title.language)
translation.deactivate()
return url
## Instruction:
Remove redirected pages from the sitemap
## Code After:
from django.contrib.sitemaps import Sitemap
from django.db.models import Q
from django.utils import translation
from cms.models import Title
def from_iterable(iterables):
"""
Backport of itertools.chain.from_iterable
"""
for it in iterables:
for element in it:
yield element
class CMSSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
def items(self):
#
# It is counter-productive to provide entries for:
# > Pages which redirect:
# - If the page redirects to another page on this site, the
# destination page will already be in the sitemap, and
# - If the page redirects externally, then it shouldn't be
# part of our sitemap anyway.
# > Pages which cannot be accessed by anonymous users (like
# search engines are).
#
all_titles = Title.objects.public().filter(
Q(redirect='') | Q(redirect__isnull=True),
page__login_required=False
)
return all_titles
def lastmod(self, title):
modification_dates = [title.page.changed_date, title.page.publication_date]
plugins_for_placeholder = lambda placeholder: placeholder.get_plugins()
plugins = from_iterable(map(plugins_for_placeholder, title.page.placeholders.all()))
plugin_modification_dates = map(lambda plugin: plugin.changed_date, plugins)
modification_dates.extend(plugin_modification_dates)
return max(modification_dates)
def location(self, title):
translation.activate(title.language)
url = title.page.get_absolute_url(title.language)
translation.deactivate()
return url
|
f48eb543c3ae2222a71080592ae8932c227dc605 | roche/scripts/xml-load.py | roche/scripts/xml-load.py |
import sys
sys.path.append('../../')
import roche.settings
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.createCollection(u'docker/浙江大學圖書館', True)
with open('../../../dublin-store/db/test_001.xml') as f:
xmldb.load(f, '/docker/001.xml', True)
|
import sys
sys.path.append('.')
import roche.settings
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.createCollection(u'docker/浙江大學圖書館', True)
with open('../dublin-store/db/test_001.xml') as f:
xmldb.load(f, '/docker/001.xml', True)
| Fix relative path in relation to app root dir | Fix relative path in relation to app root dir
| Python | mit | beijingren/roche-website,beijingren/roche-website,beijingren/roche-website,beijingren/roche-website |
import sys
- sys.path.append('../../')
+ sys.path.append('.')
import roche.settings
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.createCollection(u'docker/浙江大學圖書館', True)
- with open('../../../dublin-store/db/test_001.xml') as f:
+ with open('../dublin-store/db/test_001.xml') as f:
xmldb.load(f, '/docker/001.xml', True)
| Fix relative path in relation to app root dir | ## Code Before:
import sys
sys.path.append('../../')
import roche.settings
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.createCollection(u'docker/浙江大學圖書館', True)
with open('../../../dublin-store/db/test_001.xml') as f:
xmldb.load(f, '/docker/001.xml', True)
## Instruction:
Fix relative path in relation to app root dir
## Code After:
import sys
sys.path.append('.')
import roche.settings
from eulexistdb.db import ExistDB
from roche.settings import EXISTDB_SERVER_URL
#
# Timeout higher?
#
xmldb = ExistDB(timeout=30)
xmldb.createCollection('docker', True)
xmldb.createCollection(u'docker/浙江大學圖書館', True)
with open('../dublin-store/db/test_001.xml') as f:
xmldb.load(f, '/docker/001.xml', True)
|
eccedb9f938bd74574e4dcdd9ea63f71ac269f20 | nydus/db/routers/__init__.py | nydus/db/routers/__init__.py |
from .base import BaseRouter, RoundRobinRouter
|
from .base import BaseRouter, RoundRobinRouter, PartitionRouter
| Add partition router to base | Add partition router to base
| Python | apache-2.0 | disqus/nydus |
- from .base import BaseRouter, RoundRobinRouter
+ from .base import BaseRouter, RoundRobinRouter, PartitionRouter
| Add partition router to base | ## Code Before:
from .base import BaseRouter, RoundRobinRouter
## Instruction:
Add partition router to base
## Code After:
from .base import BaseRouter, RoundRobinRouter, PartitionRouter
|
d4dd408e671d14518b3fabb964027cd006366fca | testfixtures/compat.py | testfixtures/compat.py | import sys
if sys.version_info[:2] > (3, 0):
PY2 = False
PY3 = True
Bytes = bytes
Unicode = str
basestring = str
class_type_name = 'class'
ClassType = type
exception_module = 'builtins'
new_class = type
self_name = '__self__'
from io import StringIO
xrange = range
else:
PY2 = True
PY3 = False
Bytes = str
Unicode = unicode
basestring = basestring
class_type_name = 'type'
from types import ClassType
exception_module = 'exceptions'
from new import classobj as new_class
self_name = 'im_self'
from cStringIO import StringIO
xrange = xrange
try:
from mock import call as mock_call
except ImportError: # pragma: no cover
class MockCall: pass
mock_call = MockCall()
try:
from unittest.mock import call as unittest_mock_call
except ImportError:
class UnittestMockCall: pass
unittest_mock_call = UnittestMockCall()
| import sys
if sys.version_info[:2] > (3, 0):
PY2 = False
PY3 = True
Bytes = bytes
Unicode = str
basestring = str
BytesLiteral = lambda x: x.encode('latin1')
UnicodeLiteral = lambda x: x
class_type_name = 'class'
ClassType = type
exception_module = 'builtins'
new_class = type
self_name = '__self__'
from io import StringIO
xrange = range
else:
PY2 = True
PY3 = False
Bytes = str
Unicode = unicode
basestring = basestring
BytesLiteral = lambda x: x
UnicodeLiteral = lambda x: x.decode('latin1')
class_type_name = 'type'
from types import ClassType
exception_module = 'exceptions'
from new import classobj as new_class
self_name = 'im_self'
from cStringIO import StringIO
xrange = xrange
try:
from mock import call as mock_call
except ImportError: # pragma: no cover
class MockCall: pass
mock_call = MockCall()
try:
from unittest.mock import call as unittest_mock_call
except ImportError:
class UnittestMockCall: pass
unittest_mock_call = UnittestMockCall()
| Add Python version agnostic helpers for creating byte and unicode literals. | Add Python version agnostic helpers for creating byte and unicode literals. | Python | mit | Simplistix/testfixtures,nebulans/testfixtures | import sys
if sys.version_info[:2] > (3, 0):
PY2 = False
PY3 = True
Bytes = bytes
Unicode = str
basestring = str
+ BytesLiteral = lambda x: x.encode('latin1')
+ UnicodeLiteral = lambda x: x
class_type_name = 'class'
ClassType = type
exception_module = 'builtins'
new_class = type
self_name = '__self__'
from io import StringIO
xrange = range
else:
PY2 = True
PY3 = False
Bytes = str
Unicode = unicode
basestring = basestring
+ BytesLiteral = lambda x: x
+ UnicodeLiteral = lambda x: x.decode('latin1')
class_type_name = 'type'
from types import ClassType
exception_module = 'exceptions'
from new import classobj as new_class
self_name = 'im_self'
from cStringIO import StringIO
xrange = xrange
try:
from mock import call as mock_call
except ImportError: # pragma: no cover
class MockCall: pass
mock_call = MockCall()
try:
from unittest.mock import call as unittest_mock_call
except ImportError:
class UnittestMockCall: pass
unittest_mock_call = UnittestMockCall()
| Add Python version agnostic helpers for creating byte and unicode literals. | ## Code Before:
import sys
if sys.version_info[:2] > (3, 0):
PY2 = False
PY3 = True
Bytes = bytes
Unicode = str
basestring = str
class_type_name = 'class'
ClassType = type
exception_module = 'builtins'
new_class = type
self_name = '__self__'
from io import StringIO
xrange = range
else:
PY2 = True
PY3 = False
Bytes = str
Unicode = unicode
basestring = basestring
class_type_name = 'type'
from types import ClassType
exception_module = 'exceptions'
from new import classobj as new_class
self_name = 'im_self'
from cStringIO import StringIO
xrange = xrange
try:
from mock import call as mock_call
except ImportError: # pragma: no cover
class MockCall: pass
mock_call = MockCall()
try:
from unittest.mock import call as unittest_mock_call
except ImportError:
class UnittestMockCall: pass
unittest_mock_call = UnittestMockCall()
## Instruction:
Add Python version agnostic helpers for creating byte and unicode literals.
## Code After:
import sys
if sys.version_info[:2] > (3, 0):
PY2 = False
PY3 = True
Bytes = bytes
Unicode = str
basestring = str
BytesLiteral = lambda x: x.encode('latin1')
UnicodeLiteral = lambda x: x
class_type_name = 'class'
ClassType = type
exception_module = 'builtins'
new_class = type
self_name = '__self__'
from io import StringIO
xrange = range
else:
PY2 = True
PY3 = False
Bytes = str
Unicode = unicode
basestring = basestring
BytesLiteral = lambda x: x
UnicodeLiteral = lambda x: x.decode('latin1')
class_type_name = 'type'
from types import ClassType
exception_module = 'exceptions'
from new import classobj as new_class
self_name = 'im_self'
from cStringIO import StringIO
xrange = xrange
try:
from mock import call as mock_call
except ImportError: # pragma: no cover
class MockCall: pass
mock_call = MockCall()
try:
from unittest.mock import call as unittest_mock_call
except ImportError:
class UnittestMockCall: pass
unittest_mock_call = UnittestMockCall()
|
bb3d9ec2d9932da2abb50f5cb6bceffae5112abb | mrbelvedereci/trigger/admin.py | mrbelvedereci/trigger/admin.py | from django.contrib import admin
from mrbelvedereci.trigger.models import Trigger
class TriggerAdmin(admin.ModelAdmin):
list_display = ('repo', 'type', 'flows', 'org', 'regex', 'active', 'public')
list_filter = ('active', 'public', 'repo', 'org', 'type')
admin.site.register(Trigger, TriggerAdmin)
| from django.contrib import admin
from mrbelvedereci.trigger.models import Trigger
class TriggerAdmin(admin.ModelAdmin):
list_display = ('name', 'repo', 'type', 'flows', 'org', 'regex', 'active', 'public')
list_filter = ('active', 'public', 'type', 'org', 'repo')
admin.site.register(Trigger, TriggerAdmin)
| Add name to trigger list view | Add name to trigger list view
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci | from django.contrib import admin
from mrbelvedereci.trigger.models import Trigger
class TriggerAdmin(admin.ModelAdmin):
- list_display = ('repo', 'type', 'flows', 'org', 'regex', 'active', 'public')
+ list_display = ('name', 'repo', 'type', 'flows', 'org', 'regex', 'active', 'public')
- list_filter = ('active', 'public', 'repo', 'org', 'type')
+ list_filter = ('active', 'public', 'type', 'org', 'repo')
admin.site.register(Trigger, TriggerAdmin)
| Add name to trigger list view | ## Code Before:
from django.contrib import admin
from mrbelvedereci.trigger.models import Trigger
class TriggerAdmin(admin.ModelAdmin):
list_display = ('repo', 'type', 'flows', 'org', 'regex', 'active', 'public')
list_filter = ('active', 'public', 'repo', 'org', 'type')
admin.site.register(Trigger, TriggerAdmin)
## Instruction:
Add name to trigger list view
## Code After:
from django.contrib import admin
from mrbelvedereci.trigger.models import Trigger
class TriggerAdmin(admin.ModelAdmin):
list_display = ('name', 'repo', 'type', 'flows', 'org', 'regex', 'active', 'public')
list_filter = ('active', 'public', 'type', 'org', 'repo')
admin.site.register(Trigger, TriggerAdmin)
|
437eb8432fe91865d3cb24109e1b99818de8ce4e | pysc2/bin/battle_net_maps.py | pysc2/bin/battle_net_maps.py | """Print the list of available maps according to the game."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from pysc2 import run_configs
def main(unused_argv):
with run_configs.get().start(want_rgb=False) as controller:
available_maps = controller.available_maps()
print("\n")
print("Local map paths:")
for m in available_maps.local_map_paths:
print(m)
print()
print("Battle.net maps:")
for m in available_maps.battlenet_map_names:
print(m)
if __name__ == "__main__":
app.run(main)
| """Print the list of available maps according to the game."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from pysc2 import run_configs
def main(unused_argv):
with run_configs.get().start(want_rgb=False) as controller:
available_maps = controller.available_maps()
print("\n")
print("Local map paths:")
for m in sorted(available_maps.local_map_paths):
print(" ", m)
print()
print("Battle.net maps:")
for m in sorted(available_maps.battlenet_map_names):
print(" ", m)
if __name__ == "__main__":
app.run(main)
| Sort and indent the map lists. | Sort and indent the map lists.
PiperOrigin-RevId: 249276696
| Python | apache-2.0 | deepmind/pysc2 | """Print the list of available maps according to the game."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from pysc2 import run_configs
def main(unused_argv):
with run_configs.get().start(want_rgb=False) as controller:
available_maps = controller.available_maps()
print("\n")
print("Local map paths:")
- for m in available_maps.local_map_paths:
+ for m in sorted(available_maps.local_map_paths):
- print(m)
+ print(" ", m)
print()
print("Battle.net maps:")
- for m in available_maps.battlenet_map_names:
+ for m in sorted(available_maps.battlenet_map_names):
- print(m)
+ print(" ", m)
if __name__ == "__main__":
app.run(main)
| Sort and indent the map lists. | ## Code Before:
"""Print the list of available maps according to the game."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from pysc2 import run_configs
def main(unused_argv):
with run_configs.get().start(want_rgb=False) as controller:
available_maps = controller.available_maps()
print("\n")
print("Local map paths:")
for m in available_maps.local_map_paths:
print(m)
print()
print("Battle.net maps:")
for m in available_maps.battlenet_map_names:
print(m)
if __name__ == "__main__":
app.run(main)
## Instruction:
Sort and indent the map lists.
## Code After:
"""Print the list of available maps according to the game."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import app
from pysc2 import run_configs
def main(unused_argv):
with run_configs.get().start(want_rgb=False) as controller:
available_maps = controller.available_maps()
print("\n")
print("Local map paths:")
for m in sorted(available_maps.local_map_paths):
print(" ", m)
print()
print("Battle.net maps:")
for m in sorted(available_maps.battlenet_map_names):
print(" ", m)
if __name__ == "__main__":
app.run(main)
|
73eb3c7c52c2a5c58cad0e1d4dbe09c1e713beeb | conductor/vendor/_stripe.py | conductor/vendor/_stripe.py | from django.conf import settings
import stripe
stripe.api_key = settings.STRIPE_API_KEY
stripe.api_version = "2018-10-31"
class StripeGateway:
"""A gateway to Stripe
This insulates the rest of the system from Stripe errors
and configures the Stripe module with the API key.
"""
def create_customer(self, user: settings.AUTH_USER_MODEL, stripe_token: str) -> str:
"""Add a user to Stripe and join them to the plan."""
# Let this fail on purpose. If it fails, the error monitoring system
# will log it and I'll learn how to harden it for the conductor env.
customer = stripe.Customer.create(email=user.email, source=stripe_token)
stripe.Subscription.create(
customer=customer.id,
items=[{"plan": settings.STRIPE_PLAN}],
trial_from_plan=True,
)
return customer.id
stripe_gateway = StripeGateway()
| from django.conf import settings
import stripe
stripe.api_key = settings.STRIPE_API_KEY
class StripeGateway:
"""A gateway to Stripe
This insulates the rest of the system from Stripe errors
and configures the Stripe module with the API key.
"""
def create_customer(self, user: settings.AUTH_USER_MODEL, stripe_token: str) -> str:
"""Add a user to Stripe and join them to the plan."""
# Let this fail on purpose. If it fails, the error monitoring system
# will log it and I'll learn how to harden it for the conductor env.
customer = stripe.Customer.create(email=user.email, source=stripe_token)
stripe.Subscription.create(
customer=customer.id,
items=[{"plan": settings.STRIPE_PLAN}],
trial_from_plan=True,
)
return customer.id
stripe_gateway = StripeGateway()
| Remove pinned Stripe API version. | Remove pinned Stripe API version.
| Python | bsd-2-clause | mblayman/lcp,mblayman/lcp,mblayman/lcp | from django.conf import settings
import stripe
stripe.api_key = settings.STRIPE_API_KEY
- stripe.api_version = "2018-10-31"
class StripeGateway:
"""A gateway to Stripe
This insulates the rest of the system from Stripe errors
and configures the Stripe module with the API key.
"""
def create_customer(self, user: settings.AUTH_USER_MODEL, stripe_token: str) -> str:
"""Add a user to Stripe and join them to the plan."""
# Let this fail on purpose. If it fails, the error monitoring system
# will log it and I'll learn how to harden it for the conductor env.
customer = stripe.Customer.create(email=user.email, source=stripe_token)
stripe.Subscription.create(
customer=customer.id,
items=[{"plan": settings.STRIPE_PLAN}],
trial_from_plan=True,
)
return customer.id
stripe_gateway = StripeGateway()
| Remove pinned Stripe API version. | ## Code Before:
from django.conf import settings
import stripe
stripe.api_key = settings.STRIPE_API_KEY
stripe.api_version = "2018-10-31"
class StripeGateway:
"""A gateway to Stripe
This insulates the rest of the system from Stripe errors
and configures the Stripe module with the API key.
"""
def create_customer(self, user: settings.AUTH_USER_MODEL, stripe_token: str) -> str:
"""Add a user to Stripe and join them to the plan."""
# Let this fail on purpose. If it fails, the error monitoring system
# will log it and I'll learn how to harden it for the conductor env.
customer = stripe.Customer.create(email=user.email, source=stripe_token)
stripe.Subscription.create(
customer=customer.id,
items=[{"plan": settings.STRIPE_PLAN}],
trial_from_plan=True,
)
return customer.id
stripe_gateway = StripeGateway()
## Instruction:
Remove pinned Stripe API version.
## Code After:
from django.conf import settings
import stripe
stripe.api_key = settings.STRIPE_API_KEY
class StripeGateway:
"""A gateway to Stripe
This insulates the rest of the system from Stripe errors
and configures the Stripe module with the API key.
"""
def create_customer(self, user: settings.AUTH_USER_MODEL, stripe_token: str) -> str:
"""Add a user to Stripe and join them to the plan."""
# Let this fail on purpose. If it fails, the error monitoring system
# will log it and I'll learn how to harden it for the conductor env.
customer = stripe.Customer.create(email=user.email, source=stripe_token)
stripe.Subscription.create(
customer=customer.id,
items=[{"plan": settings.STRIPE_PLAN}],
trial_from_plan=True,
)
return customer.id
stripe_gateway = StripeGateway()
|
9d7f2626294fbf25934e7dda4892b7ac13bd5555 | fireplace/cards/tgt/warlock.py | fireplace/cards/tgt/warlock.py | from ..utils import *
##
# Minions
# Dreadsteed
class AT_019:
deathrattle = Summon(CONTROLLER, "AT_019")
# Tiny Knight of Evil
class AT_021:
events = Discard(FRIENDLY).on(Buff(SELF, "AT_021e"))
# Wrathguard
class AT_026:
events = Damage(SELF).on(Hit(FRIENDLY_HERO, Damage.Args.AMOUNT))
# Wilfred Fizzlebang
class AT_027:
events = Draw(CONTROLLER).on(
lambda self, target, card, source: source is self.controller.hero.power and Buff(card, "AT_027e")
)
class AT_027e:
cost = lambda self, i: 0
##
# Spells
# Fist of Jaraxxus
class AT_022:
play = Hit(RANDOM_ENEMY_CHARACTER, 4)
in_hand = Discard(SELF).on(play)
# Demonfuse
class AT_024:
play = Buff(TARGET, "AT_024e"), GainMana(OPPONENT, 1)
# Dark Bargain
class AT_025:
play = Destroy(RANDOM(ENEMY_MINIONS) * 2), Discard(RANDOM(CONTROLLER_HAND) * 2)
| from ..utils import *
##
# Minions
# Dreadsteed
class AT_019:
deathrattle = Summon(CONTROLLER, "AT_019")
# Tiny Knight of Evil
class AT_021:
events = Discard(FRIENDLY).on(Buff(SELF, "AT_021e"))
# Void Crusher
class AT_023:
inspire = Destroy(RANDOM_ENEMY_MINION | RANDOM_FRIENDLY_MINION)
# Wrathguard
class AT_026:
events = Damage(SELF).on(Hit(FRIENDLY_HERO, Damage.Args.AMOUNT))
# Wilfred Fizzlebang
class AT_027:
events = Draw(CONTROLLER).on(
lambda self, target, card, source: source is self.controller.hero.power and Buff(card, "AT_027e")
)
class AT_027e:
cost = lambda self, i: 0
##
# Spells
# Fist of Jaraxxus
class AT_022:
play = Hit(RANDOM_ENEMY_CHARACTER, 4)
in_hand = Discard(SELF).on(play)
# Demonfuse
class AT_024:
play = Buff(TARGET, "AT_024e"), GainMana(OPPONENT, 1)
# Dark Bargain
class AT_025:
play = Destroy(RANDOM(ENEMY_MINIONS) * 2), Discard(RANDOM(CONTROLLER_HAND) * 2)
| Implement more TGT Warlock cards | Implement more TGT Warlock cards
| Python | agpl-3.0 | liujimj/fireplace,beheh/fireplace,Ragowit/fireplace,Ragowit/fireplace,amw2104/fireplace,amw2104/fireplace,smallnamespace/fireplace,smallnamespace/fireplace,oftc-ftw/fireplace,liujimj/fireplace,oftc-ftw/fireplace,Meerkov/fireplace,jleclanche/fireplace,Meerkov/fireplace,NightKev/fireplace | from ..utils import *
##
# Minions
# Dreadsteed
class AT_019:
deathrattle = Summon(CONTROLLER, "AT_019")
# Tiny Knight of Evil
class AT_021:
events = Discard(FRIENDLY).on(Buff(SELF, "AT_021e"))
+ # Void Crusher
+ class AT_023:
+ inspire = Destroy(RANDOM_ENEMY_MINION | RANDOM_FRIENDLY_MINION)
+
+
# Wrathguard
class AT_026:
events = Damage(SELF).on(Hit(FRIENDLY_HERO, Damage.Args.AMOUNT))
+
# Wilfred Fizzlebang
class AT_027:
events = Draw(CONTROLLER).on(
lambda self, target, card, source: source is self.controller.hero.power and Buff(card, "AT_027e")
)
class AT_027e:
cost = lambda self, i: 0
##
# Spells
# Fist of Jaraxxus
class AT_022:
play = Hit(RANDOM_ENEMY_CHARACTER, 4)
in_hand = Discard(SELF).on(play)
# Demonfuse
class AT_024:
play = Buff(TARGET, "AT_024e"), GainMana(OPPONENT, 1)
# Dark Bargain
class AT_025:
play = Destroy(RANDOM(ENEMY_MINIONS) * 2), Discard(RANDOM(CONTROLLER_HAND) * 2)
| Implement more TGT Warlock cards | ## Code Before:
from ..utils import *
##
# Minions
# Dreadsteed
class AT_019:
deathrattle = Summon(CONTROLLER, "AT_019")
# Tiny Knight of Evil
class AT_021:
events = Discard(FRIENDLY).on(Buff(SELF, "AT_021e"))
# Wrathguard
class AT_026:
events = Damage(SELF).on(Hit(FRIENDLY_HERO, Damage.Args.AMOUNT))
# Wilfred Fizzlebang
class AT_027:
events = Draw(CONTROLLER).on(
lambda self, target, card, source: source is self.controller.hero.power and Buff(card, "AT_027e")
)
class AT_027e:
cost = lambda self, i: 0
##
# Spells
# Fist of Jaraxxus
class AT_022:
play = Hit(RANDOM_ENEMY_CHARACTER, 4)
in_hand = Discard(SELF).on(play)
# Demonfuse
class AT_024:
play = Buff(TARGET, "AT_024e"), GainMana(OPPONENT, 1)
# Dark Bargain
class AT_025:
play = Destroy(RANDOM(ENEMY_MINIONS) * 2), Discard(RANDOM(CONTROLLER_HAND) * 2)
## Instruction:
Implement more TGT Warlock cards
## Code After:
from ..utils import *
##
# Minions
# Dreadsteed
class AT_019:
deathrattle = Summon(CONTROLLER, "AT_019")
# Tiny Knight of Evil
class AT_021:
events = Discard(FRIENDLY).on(Buff(SELF, "AT_021e"))
# Void Crusher
class AT_023:
inspire = Destroy(RANDOM_ENEMY_MINION | RANDOM_FRIENDLY_MINION)
# Wrathguard
class AT_026:
events = Damage(SELF).on(Hit(FRIENDLY_HERO, Damage.Args.AMOUNT))
# Wilfred Fizzlebang
class AT_027:
events = Draw(CONTROLLER).on(
lambda self, target, card, source: source is self.controller.hero.power and Buff(card, "AT_027e")
)
class AT_027e:
cost = lambda self, i: 0
##
# Spells
# Fist of Jaraxxus
class AT_022:
play = Hit(RANDOM_ENEMY_CHARACTER, 4)
in_hand = Discard(SELF).on(play)
# Demonfuse
class AT_024:
play = Buff(TARGET, "AT_024e"), GainMana(OPPONENT, 1)
# Dark Bargain
class AT_025:
play = Destroy(RANDOM(ENEMY_MINIONS) * 2), Discard(RANDOM(CONTROLLER_HAND) * 2)
|
21bf18a03c485304aa00dc2af86aa91930e4b1ac | tests/test_grammar.py | tests/test_grammar.py | import pytest
from parglare import Grammar
from parglare.exceptions import GrammarError
def test_terminal_nonterminal_conflict():
# Production A is a terminal ("a") and non-terminal at the same time.
g = """
A = "a" | B;
B = "b";
"""
try:
Grammar.from_string(g)
assert False
except GrammarError as e:
assert 'Multiple definition' in str(e)
def test_multiple_terminal_definition():
g = """
S = A A;
A = "a";
A = "b";
"""
try:
Grammar.from_string(g)
assert False
except GrammarError as e:
assert 'Multiple definition' in str(e)
| import pytest
from parglare import Grammar
def test_terminal_nonterminal():
# Production A is a terminal ("a") and non-terminal at the same time.
# Thus, it must be recognized as non-terminal.
g = """
S = A B;
A = "a" | B;
B = "b";
"""
Grammar.from_string(g)
# Here A shoud be non-terminal while B will be terminal.
g = """
S = A B;
A = B;
B = "b";
"""
Grammar.from_string(g)
def test_multiple_terminal_definition():
# A is defined multiple times as terminal thus it must be recognized
# as non-terminal with alternative expansions.
g = """
S = A A;
A = "a";
A = "b";
"""
Grammar.from_string(g)
| Fix in tests for terminal definitions. | Fix in tests for terminal definitions.
| Python | mit | igordejanovic/parglare,igordejanovic/parglare | import pytest
from parglare import Grammar
- from parglare.exceptions import GrammarError
- def test_terminal_nonterminal_conflict():
+ def test_terminal_nonterminal():
# Production A is a terminal ("a") and non-terminal at the same time.
+ # Thus, it must be recognized as non-terminal.
g = """
+ S = A B;
A = "a" | B;
B = "b";
"""
- try:
- Grammar.from_string(g)
+ Grammar.from_string(g)
- assert False
- except GrammarError as e:
- assert 'Multiple definition' in str(e)
+
+ # Here A shoud be non-terminal while B will be terminal.
+ g = """
+ S = A B;
+ A = B;
+ B = "b";
+ """
+
+ Grammar.from_string(g)
def test_multiple_terminal_definition():
+ # A is defined multiple times as terminal thus it must be recognized
+ # as non-terminal with alternative expansions.
g = """
S = A A;
A = "a";
A = "b";
"""
- try:
- Grammar.from_string(g)
- assert False
- except GrammarError as e:
- assert 'Multiple definition' in str(e)
+ Grammar.from_string(g)
+ | Fix in tests for terminal definitions. | ## Code Before:
import pytest
from parglare import Grammar
from parglare.exceptions import GrammarError
def test_terminal_nonterminal_conflict():
# Production A is a terminal ("a") and non-terminal at the same time.
g = """
A = "a" | B;
B = "b";
"""
try:
Grammar.from_string(g)
assert False
except GrammarError as e:
assert 'Multiple definition' in str(e)
def test_multiple_terminal_definition():
g = """
S = A A;
A = "a";
A = "b";
"""
try:
Grammar.from_string(g)
assert False
except GrammarError as e:
assert 'Multiple definition' in str(e)
## Instruction:
Fix in tests for terminal definitions.
## Code After:
import pytest
from parglare import Grammar
def test_terminal_nonterminal():
# Production A is a terminal ("a") and non-terminal at the same time.
# Thus, it must be recognized as non-terminal.
g = """
S = A B;
A = "a" | B;
B = "b";
"""
Grammar.from_string(g)
# Here A shoud be non-terminal while B will be terminal.
g = """
S = A B;
A = B;
B = "b";
"""
Grammar.from_string(g)
def test_multiple_terminal_definition():
# A is defined multiple times as terminal thus it must be recognized
# as non-terminal with alternative expansions.
g = """
S = A A;
A = "a";
A = "b";
"""
Grammar.from_string(g)
|
7bf4083ef44585116f0eff86753080612a26b374 | src/__init__.py | src/__init__.py | from bayeslite.api import barplot
from bayeslite.api import cardinality
from bayeslite.api import draw_crosscat
from bayeslite.api import estimate_log_likelihood
from bayeslite.api import heatmap
from bayeslite.api import histogram
from bayeslite.api import mi_hist
from bayeslite.api import nullify
from bayeslite.api import pairplot
from bayeslite.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] | from bdbcontrib.api import barplot
from bdbcontrib.api import cardinality
from bdbcontrib.api import draw_crosscat
from bdbcontrib.api import estimate_log_likelihood
from bdbcontrib.api import heatmap
from bdbcontrib.api import histogram
from bdbcontrib.api import mi_hist
from bdbcontrib.api import nullify
from bdbcontrib.api import pairplot
from bdbcontrib.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] | Fix big from bayeslite to bdbcontrib. | Fix big from bayeslite to bdbcontrib.
| Python | apache-2.0 | probcomp/bdbcontrib,probcomp/bdbcontrib | - from bayeslite.api import barplot
+ from bdbcontrib.api import barplot
- from bayeslite.api import cardinality
+ from bdbcontrib.api import cardinality
- from bayeslite.api import draw_crosscat
+ from bdbcontrib.api import draw_crosscat
- from bayeslite.api import estimate_log_likelihood
+ from bdbcontrib.api import estimate_log_likelihood
- from bayeslite.api import heatmap
+ from bdbcontrib.api import heatmap
- from bayeslite.api import histogram
+ from bdbcontrib.api import histogram
- from bayeslite.api import mi_hist
+ from bdbcontrib.api import mi_hist
- from bayeslite.api import nullify
+ from bdbcontrib.api import nullify
- from bayeslite.api import pairplot
+ from bdbcontrib.api import pairplot
- from bayeslite.api import plot_crosscat_chain_diagnostics
+ from bdbcontrib.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] | Fix big from bayeslite to bdbcontrib. | ## Code Before:
from bayeslite.api import barplot
from bayeslite.api import cardinality
from bayeslite.api import draw_crosscat
from bayeslite.api import estimate_log_likelihood
from bayeslite.api import heatmap
from bayeslite.api import histogram
from bayeslite.api import mi_hist
from bayeslite.api import nullify
from bayeslite.api import pairplot
from bayeslite.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
]
## Instruction:
Fix big from bayeslite to bdbcontrib.
## Code After:
from bdbcontrib.api import barplot
from bdbcontrib.api import cardinality
from bdbcontrib.api import draw_crosscat
from bdbcontrib.api import estimate_log_likelihood
from bdbcontrib.api import heatmap
from bdbcontrib.api import histogram
from bdbcontrib.api import mi_hist
from bdbcontrib.api import nullify
from bdbcontrib.api import pairplot
from bdbcontrib.api import plot_crosscat_chain_diagnostics
"""Main bdbcontrib API.
The bdbcontrib module servers a sandbox for experimental and semi-stable
features that are not yet ready for integreation to the bayeslite repository.
"""
__all__ = [
'barplot',
'cardinality',
'draw_crosscat',
'estimate_log_likelihood',
'heatmap',
'histogram',
'mi_hist',
'nullify',
'pairplot',
'plot_crosscat_chain_diagnostics'
] |
af0ec29ce0c830f096ab809fd2d69affd887ce16 | feincms/module/page/admin.py | feincms/module/page/admin.py |
from __future__ import absolute_import
from django.contrib import admin
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
|
from __future__ import absolute_import
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
'The page module requires a \'Page.register_templates()\' call somewhere'
' (\'Page.register_regions()\' is not sufficient).')
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
| Abort when the page model does not have a template_key field | Abort when the page model does not have a template_key field
| Python | bsd-3-clause | joshuajonah/feincms,mjl/feincms,matthiask/django-content-editor,matthiask/feincms2-content,feincms/feincms,feincms/feincms,pjdelport/feincms,pjdelport/feincms,mjl/feincms,michaelkuty/feincms,matthiask/django-content-editor,joshuajonah/feincms,nickburlett/feincms,matthiask/feincms2-content,matthiask/django-content-editor,michaelkuty/feincms,michaelkuty/feincms,joshuajonah/feincms,nickburlett/feincms,matthiask/feincms2-content,nickburlett/feincms,michaelkuty/feincms,pjdelport/feincms,matthiask/django-content-editor,joshuajonah/feincms,mjl/feincms,feincms/feincms,nickburlett/feincms |
from __future__ import absolute_import
from django.contrib import admin
+ from django.core.exceptions import ImproperlyConfigured
+ from django.db.models import FieldDoesNotExist
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
+ try:
+ Page._meta.get_field('template_key')
+ except FieldDoesNotExist:
+ raise ImproperlyConfigured(
+ 'The page module requires a \'Page.register_templates()\' call somewhere'
+ ' (\'Page.register_regions()\' is not sufficient).')
+
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
| Abort when the page model does not have a template_key field | ## Code Before:
from __future__ import absolute_import
from django.contrib import admin
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
## Instruction:
Abort when the page model does not have a template_key field
## Code After:
from __future__ import absolute_import
from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db.models import FieldDoesNotExist
from .models import Page
from .modeladmins import PageAdmin
# ------------------------------------------------------------------------
try:
Page._meta.get_field('template_key')
except FieldDoesNotExist:
raise ImproperlyConfigured(
'The page module requires a \'Page.register_templates()\' call somewhere'
' (\'Page.register_regions()\' is not sufficient).')
admin.site.register(Page, PageAdmin)
# ------------------------------------------------------------------------
# ------------------------------------------------------------------------
|
2fb27cf8f4399ec6aba36b86d2993e6c3b81d0ee | coalib/bearlib/languages/__init__.py | coalib/bearlib/languages/__init__.py |
# Start ignoring PyUnusedCodeBear
from .Language import Language
from .Language import Languages
from .definitions.Unknown import Unknown
from .definitions.C import C
from .definitions.CPP import CPP
from .definitions.CSharp import CSharp
from .definitions.CSS import CSS
from .definitions.Java import Java
from .definitions.JavaScript import JavaScript
from .definitions.Python import Python
from .definitions.Vala import Vala
from .definitions.html import HTML
# Stop ignoring PyUnusedCodeBear
|
# Start ignoring PyUnusedCodeBear
from .Language import Language
from .Language import Languages
from .definitions.Unknown import Unknown
from .definitions.C import C
from .definitions.CPP import CPP
from .definitions.CSharp import CSharp
from .definitions.CSS import CSS
from .definitions.Fortran import Fortran
from .definitions.Golang import Golang
from .definitions.html import HTML
from .definitions.Java import Java
from .definitions.JavaScript import JavaScript
from .definitions.JSP import JSP
from .definitions.Matlab import Matlab
from .definitions.ObjectiveC import ObjectiveC
from .definitions.PHP import PHP
from .definitions.PLSQL import PLSQL
from .definitions.Python import Python
from .definitions.Ruby import Ruby
from .definitions.Scala import Scala
from .definitions.Swift import Swift
from .definitions.Vala import Vala
# Stop ignoring PyUnusedCodeBear
| Add definition into default import | Language: Add definition into default import
Fixes https://github.com/coala/coala/issues/4688 | Python | agpl-3.0 | coala/coala,SanketDG/coala,shreyans800755/coala,karansingh1559/coala,kartikeys98/coala,kartikeys98/coala,jayvdb/coala,CruiseDevice/coala,Nosferatul/coala,shreyans800755/coala,aptrishu/coala,nemaniarjun/coala,aptrishu/coala,karansingh1559/coala,jayvdb/coala,rimacone/testing2,Asalle/coala,CruiseDevice/coala,shreyans800755/coala,coala-analyzer/coala,coala-analyzer/coala,nemaniarjun/coala,karansingh1559/coala,Asalle/coala,coala/coala,SanketDG/coala,coala-analyzer/coala,SanketDG/coala,rimacone/testing2,CruiseDevice/coala,coala/coala,aptrishu/coala,Nosferatul/coala,kartikeys98/coala,jayvdb/coala,Nosferatul/coala,rimacone/testing2,Asalle/coala,nemaniarjun/coala |
# Start ignoring PyUnusedCodeBear
from .Language import Language
from .Language import Languages
from .definitions.Unknown import Unknown
from .definitions.C import C
from .definitions.CPP import CPP
from .definitions.CSharp import CSharp
from .definitions.CSS import CSS
+ from .definitions.Fortran import Fortran
+ from .definitions.Golang import Golang
+ from .definitions.html import HTML
from .definitions.Java import Java
from .definitions.JavaScript import JavaScript
+ from .definitions.JSP import JSP
+ from .definitions.Matlab import Matlab
+ from .definitions.ObjectiveC import ObjectiveC
+ from .definitions.PHP import PHP
+ from .definitions.PLSQL import PLSQL
from .definitions.Python import Python
+ from .definitions.Ruby import Ruby
+ from .definitions.Scala import Scala
+ from .definitions.Swift import Swift
from .definitions.Vala import Vala
- from .definitions.html import HTML
# Stop ignoring PyUnusedCodeBear
| Add definition into default import | ## Code Before:
# Start ignoring PyUnusedCodeBear
from .Language import Language
from .Language import Languages
from .definitions.Unknown import Unknown
from .definitions.C import C
from .definitions.CPP import CPP
from .definitions.CSharp import CSharp
from .definitions.CSS import CSS
from .definitions.Java import Java
from .definitions.JavaScript import JavaScript
from .definitions.Python import Python
from .definitions.Vala import Vala
from .definitions.html import HTML
# Stop ignoring PyUnusedCodeBear
## Instruction:
Add definition into default import
## Code After:
# Start ignoring PyUnusedCodeBear
from .Language import Language
from .Language import Languages
from .definitions.Unknown import Unknown
from .definitions.C import C
from .definitions.CPP import CPP
from .definitions.CSharp import CSharp
from .definitions.CSS import CSS
from .definitions.Fortran import Fortran
from .definitions.Golang import Golang
from .definitions.html import HTML
from .definitions.Java import Java
from .definitions.JavaScript import JavaScript
from .definitions.JSP import JSP
from .definitions.Matlab import Matlab
from .definitions.ObjectiveC import ObjectiveC
from .definitions.PHP import PHP
from .definitions.PLSQL import PLSQL
from .definitions.Python import Python
from .definitions.Ruby import Ruby
from .definitions.Scala import Scala
from .definitions.Swift import Swift
from .definitions.Vala import Vala
# Stop ignoring PyUnusedCodeBear
|
ac25dd0b2bf3188e1f4325ccdab78e79e7f0a937 | spiceminer/kernel/__init__.py | spiceminer/kernel/__init__.py |
from .highlevel import Kernel
# Legacy support (DEPRECATED)
from .legacy_support import *
from ..bodies import get
def load(path='.', recursive=True, followlinks=False):
return Kernel.load(**locals())
def unload(path='.', recursive=True, followlinks=False):
return Kernel.unload(**locals())
|
from .highlevel import Kernel
def load(path='.', recursive=True, followlinks=False, force_reload=False):
return Kernel.load(**locals())
def load_single(cls, path, extension=None, force_reload=False):
return Kernel.load_single(**locals())
def unload(path='.', recursive=True, followlinks=False):
return Kernel.unload(**locals())
| Change the interface of the kernel submodule to prepare for the API change. * Remove legacy support * Add load_single() * Fix missing keyword argument in load() | Change the interface of the kernel submodule to prepare for the API change.
* Remove legacy support
* Add load_single()
* Fix missing keyword argument in load()
| Python | mit | DaRasch/spiceminer,DaRasch/spiceminer |
from .highlevel import Kernel
- # Legacy support (DEPRECATED)
- from .legacy_support import *
- from ..bodies import get
+ def load(path='.', recursive=True, followlinks=False, force_reload=False):
+ return Kernel.load(**locals())
- def load(path='.', recursive=True, followlinks=False):
+ def load_single(cls, path, extension=None, force_reload=False):
- return Kernel.load(**locals())
+ return Kernel.load_single(**locals())
def unload(path='.', recursive=True, followlinks=False):
return Kernel.unload(**locals())
| Change the interface of the kernel submodule to prepare for the API change. * Remove legacy support * Add load_single() * Fix missing keyword argument in load() | ## Code Before:
from .highlevel import Kernel
# Legacy support (DEPRECATED)
from .legacy_support import *
from ..bodies import get
def load(path='.', recursive=True, followlinks=False):
return Kernel.load(**locals())
def unload(path='.', recursive=True, followlinks=False):
return Kernel.unload(**locals())
## Instruction:
Change the interface of the kernel submodule to prepare for the API change. * Remove legacy support * Add load_single() * Fix missing keyword argument in load()
## Code After:
from .highlevel import Kernel
def load(path='.', recursive=True, followlinks=False, force_reload=False):
return Kernel.load(**locals())
def load_single(cls, path, extension=None, force_reload=False):
return Kernel.load_single(**locals())
def unload(path='.', recursive=True, followlinks=False):
return Kernel.unload(**locals())
|
7ea0e2d8387b622f671638613a476dcbff6438e1 | rest_framework_swagger/urls.py | rest_framework_swagger/urls.py | from django.conf.urls import patterns
from django.conf.urls import url
from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView
urlpatterns = patterns(
'',
url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"),
url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"),
url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'),
)
| from django.conf.urls import url
from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView
urlpatterns = [
url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"),
url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"),
url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'),
]
| Use the new style urlpatterns syntax to fix Django deprecation warnings | Use the new style urlpatterns syntax to fix Django deprecation warnings
The `patterns()` syntax is now deprecated:
https://docs.djangoproject.com/en/1.8/releases/1.8/#django-conf-urls-patterns
And so under Django 1.8 results in warnings:
rest_framework_swagger/urls.py:10: RemovedInDjango110Warning:
django.conf.urls.patterns() is deprecated and will be removed in
Django 1.10. Update your urlpatterns to be a list of
django.conf.urls.url() instances instead.
Fixes #380.
| Python | bsd-2-clause | pombredanne/django-rest-swagger,aioTV/django-rest-swagger,cancan101/django-rest-swagger,visasq/django-rest-swagger,aioTV/django-rest-swagger,marcgibbons/django-rest-swagger,marcgibbons/django-rest-swagger,aioTV/django-rest-swagger,cancan101/django-rest-swagger,pombredanne/django-rest-swagger,arc6373/django-rest-swagger,cancan101/django-rest-swagger,visasq/django-rest-swagger,arc6373/django-rest-swagger,marcgibbons/django-rest-swagger,pombredanne/django-rest-swagger,marcgibbons/django-rest-swagger,visasq/django-rest-swagger,arc6373/django-rest-swagger,pombredanne/django-rest-swagger | - from django.conf.urls import patterns
from django.conf.urls import url
from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView
+ urlpatterns = [
- urlpatterns = patterns(
- '',
url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"),
url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"),
url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'),
- )
+ ]
| Use the new style urlpatterns syntax to fix Django deprecation warnings | ## Code Before:
from django.conf.urls import patterns
from django.conf.urls import url
from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView
urlpatterns = patterns(
'',
url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"),
url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"),
url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'),
)
## Instruction:
Use the new style urlpatterns syntax to fix Django deprecation warnings
## Code After:
from django.conf.urls import url
from rest_framework_swagger.views import SwaggerResourcesView, SwaggerApiView, SwaggerUIView
urlpatterns = [
url(r'^$', SwaggerUIView.as_view(), name="django.swagger.base.view"),
url(r'^api-docs/$', SwaggerResourcesView.as_view(), name="django.swagger.resources.view"),
url(r'^api-docs/(?P<path>.*)/?$', SwaggerApiView.as_view(), name='django.swagger.api.view'),
]
|
b19746badd83190b4e908144d6bc830178445dc2 | cc/license/tests/test_cc_license.py | cc/license/tests/test_cc_license.py |
import cc.license
def test_locales():
locales = cc.license.locales()
for l in locales:
assert type(l) == unicode
for c in ('en', 'de', 'he', 'ja', 'fr'):
assert c in locales
|
import cc.license
def test_locales():
locales = cc.license.locales()
for l in locales:
assert type(l) == unicode
for c in ('en', 'de', 'he', 'ja', 'fr'):
assert c in locales
def test_cc_license_classes():
cc_dir = dir(cc.license)
assert 'Jurisdiction' in cc_dir
assert 'License' in cc_dir
assert 'Question' in cc_dir
assert 'LicenseSelector' in cc_dir
| Add test to make sure certain classes are always found in cc.license, no matter where they are internally. | Add test to make sure certain classes are always found in cc.license,
no matter where they are internally.
| Python | mit | creativecommons/cc.license,creativecommons/cc.license |
import cc.license
def test_locales():
locales = cc.license.locales()
for l in locales:
assert type(l) == unicode
for c in ('en', 'de', 'he', 'ja', 'fr'):
assert c in locales
+ def test_cc_license_classes():
+ cc_dir = dir(cc.license)
+ assert 'Jurisdiction' in cc_dir
+ assert 'License' in cc_dir
+ assert 'Question' in cc_dir
+ assert 'LicenseSelector' in cc_dir
+ | Add test to make sure certain classes are always found in cc.license, no matter where they are internally. | ## Code Before:
import cc.license
def test_locales():
locales = cc.license.locales()
for l in locales:
assert type(l) == unicode
for c in ('en', 'de', 'he', 'ja', 'fr'):
assert c in locales
## Instruction:
Add test to make sure certain classes are always found in cc.license, no matter where they are internally.
## Code After:
import cc.license
def test_locales():
locales = cc.license.locales()
for l in locales:
assert type(l) == unicode
for c in ('en', 'de', 'he', 'ja', 'fr'):
assert c in locales
def test_cc_license_classes():
cc_dir = dir(cc.license)
assert 'Jurisdiction' in cc_dir
assert 'License' in cc_dir
assert 'Question' in cc_dir
assert 'LicenseSelector' in cc_dir
|
0ed7e87a6eeaab56d5c59a7e6874b5a5b0bab314 | tests/test_pointcloud.py | tests/test_pointcloud.py | from simulocloud import PointCloud
import json
import numpy as np
_TEST_XYZ = """[[10.0, 12.2, 14.4, 16.6, 18.8],
[11.1, 13.3, 15.5, 17.7, 19.9],
[0.1, 2.1, 4.5, 6.7, 8.9]]"""
_EXPECTED_POINTS = np.array([( 10. , 11.1, 0.1),
( 12.2, 13.3, 2.1),
( 14.4, 15.5, 4.5),
( 16.6, 17.7, 6.7),
( 18.8, 19.9, 8.9)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
def test_PointCloud_from_lists():
""" Can PointCloud initialisable directly from `[[xs], [ys], [zs]]` ?"""
assert np.all(PointCloud(json.loads(_TEST_XYZ)).points == _EXPECTED_POINTS)
| from simulocloud import PointCloud
import json
import numpy as np
_TEST_XYZ = [[10.0, 12.2, 14.4, 16.6, 18.8],
[11.1, 13.3, 15.5, 17.7, 19.9],
[0.1, 2.1, 4.5, 6.7, 8.9]]
_EXPECTED_POINTS = np.array([( 10. , 11.1, 0.1),
( 12.2, 13.3, 2.1),
( 14.4, 15.5, 4.5),
( 16.6, 17.7, 6.7),
( 18.8, 19.9, 8.9)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
def test_PointCloud_from_lists():
""" Can PointCloud initialisable directly from `[[xs], [ys], [zs]]` ?"""
assert np.all(PointCloud(_TEST_XYZ).points == _EXPECTED_POINTS)
| Write test data as list unless otherwise needed | Write test data as list unless otherwise needed
| Python | mit | stainbank/simulocloud | from simulocloud import PointCloud
import json
import numpy as np
- _TEST_XYZ = """[[10.0, 12.2, 14.4, 16.6, 18.8],
+ _TEST_XYZ = [[10.0, 12.2, 14.4, 16.6, 18.8],
- [11.1, 13.3, 15.5, 17.7, 19.9],
+ [11.1, 13.3, 15.5, 17.7, 19.9],
- [0.1, 2.1, 4.5, 6.7, 8.9]]"""
+ [0.1, 2.1, 4.5, 6.7, 8.9]]
_EXPECTED_POINTS = np.array([( 10. , 11.1, 0.1),
( 12.2, 13.3, 2.1),
( 14.4, 15.5, 4.5),
( 16.6, 17.7, 6.7),
( 18.8, 19.9, 8.9)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
def test_PointCloud_from_lists():
""" Can PointCloud initialisable directly from `[[xs], [ys], [zs]]` ?"""
- assert np.all(PointCloud(json.loads(_TEST_XYZ)).points == _EXPECTED_POINTS)
+ assert np.all(PointCloud(_TEST_XYZ).points == _EXPECTED_POINTS)
| Write test data as list unless otherwise needed | ## Code Before:
from simulocloud import PointCloud
import json
import numpy as np
_TEST_XYZ = """[[10.0, 12.2, 14.4, 16.6, 18.8],
[11.1, 13.3, 15.5, 17.7, 19.9],
[0.1, 2.1, 4.5, 6.7, 8.9]]"""
_EXPECTED_POINTS = np.array([( 10. , 11.1, 0.1),
( 12.2, 13.3, 2.1),
( 14.4, 15.5, 4.5),
( 16.6, 17.7, 6.7),
( 18.8, 19.9, 8.9)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
def test_PointCloud_from_lists():
""" Can PointCloud initialisable directly from `[[xs], [ys], [zs]]` ?"""
assert np.all(PointCloud(json.loads(_TEST_XYZ)).points == _EXPECTED_POINTS)
## Instruction:
Write test data as list unless otherwise needed
## Code After:
from simulocloud import PointCloud
import json
import numpy as np
_TEST_XYZ = [[10.0, 12.2, 14.4, 16.6, 18.8],
[11.1, 13.3, 15.5, 17.7, 19.9],
[0.1, 2.1, 4.5, 6.7, 8.9]]
_EXPECTED_POINTS = np.array([( 10. , 11.1, 0.1),
( 12.2, 13.3, 2.1),
( 14.4, 15.5, 4.5),
( 16.6, 17.7, 6.7),
( 18.8, 19.9, 8.9)],
dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')])
def test_PointCloud_from_lists():
""" Can PointCloud initialisable directly from `[[xs], [ys], [zs]]` ?"""
assert np.all(PointCloud(_TEST_XYZ).points == _EXPECTED_POINTS)
|
8ce14cfb0044d90f2503a7bd940a7f6401c15db2 | wagtail/admin/rich_text/editors/draftail.py | wagtail/admin/rich_text/editors/draftail.py | from django.forms import widgets
from wagtail.admin.edit_handlers import RichTextFieldPanel
from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter
from wagtail.core.rich_text import features
class DraftailRichTextArea(widgets.Textarea):
# this class's constructor accepts a 'features' kwarg
accepts_features = True
def get_panel(self):
return RichTextFieldPanel
def __init__(self, *args, **kwargs):
self.options = kwargs.pop('options', None)
self.features = kwargs.pop('features', None)
if self.features is None:
self.features = features.get_default_features()
self.converter = ContentstateConverter(self.features)
super().__init__(*args, **kwargs)
def render(self, name, value, attrs=None):
if value is None:
translated_value = None
else:
translated_value = self.converter.from_database_format(value)
return super().render(name, translated_value, attrs)
def value_from_datadict(self, data, files, name):
original_value = super().value_from_datadict(data, files, name)
if original_value is None:
return None
return self.converter.to_database_format(original_value)
| import json
from django.forms import Media, widgets
from wagtail.admin.edit_handlers import RichTextFieldPanel
from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter
from wagtail.core.rich_text import features
class DraftailRichTextArea(widgets.Textarea):
# this class's constructor accepts a 'features' kwarg
accepts_features = True
def get_panel(self):
return RichTextFieldPanel
def __init__(self, *args, **kwargs):
self.options = kwargs.pop('options', None)
self.features = kwargs.pop('features', None)
if self.features is None:
self.features = features.get_default_features()
self.converter = ContentstateConverter(self.features)
super().__init__(*args, **kwargs)
def render(self, name, value, attrs=None):
if value is None:
translated_value = None
else:
translated_value = self.converter.from_database_format(value)
return super().render(name, translated_value, attrs)
def render_js_init(self, id_, name, value):
return "window.draftail.initEditor('{name}', {opts})".format(
name=name, opts=json.dumps(self.options))
def value_from_datadict(self, data, files, name):
original_value = super().value_from_datadict(data, files, name)
if original_value is None:
return None
return self.converter.to_database_format(original_value)
@property
def media(self):
return Media(js=[
'wagtailadmin/js/draftail.js',
], css={
'all': ['wagtailadmin/css/panels/dratail.css']
})
| Integrate Draftail-related assets with Django widget | Integrate Draftail-related assets with Django widget
| Python | bsd-3-clause | mikedingjan/wagtail,kaedroho/wagtail,timorieber/wagtail,mixxorz/wagtail,torchbox/wagtail,gasman/wagtail,gasman/wagtail,wagtail/wagtail,timorieber/wagtail,mixxorz/wagtail,nealtodd/wagtail,nimasmi/wagtail,kaedroho/wagtail,mikedingjan/wagtail,takeflight/wagtail,thenewguy/wagtail,zerolab/wagtail,timorieber/wagtail,thenewguy/wagtail,mixxorz/wagtail,FlipperPA/wagtail,zerolab/wagtail,takeflight/wagtail,nealtodd/wagtail,nimasmi/wagtail,zerolab/wagtail,takeflight/wagtail,zerolab/wagtail,mikedingjan/wagtail,mixxorz/wagtail,kaedroho/wagtail,torchbox/wagtail,thenewguy/wagtail,wagtail/wagtail,torchbox/wagtail,rsalmaso/wagtail,gasman/wagtail,rsalmaso/wagtail,zerolab/wagtail,nimasmi/wagtail,thenewguy/wagtail,wagtail/wagtail,rsalmaso/wagtail,nealtodd/wagtail,thenewguy/wagtail,timorieber/wagtail,rsalmaso/wagtail,torchbox/wagtail,nimasmi/wagtail,rsalmaso/wagtail,jnns/wagtail,kaedroho/wagtail,FlipperPA/wagtail,kaedroho/wagtail,takeflight/wagtail,gasman/wagtail,nealtodd/wagtail,wagtail/wagtail,FlipperPA/wagtail,wagtail/wagtail,jnns/wagtail,jnns/wagtail,FlipperPA/wagtail,mikedingjan/wagtail,jnns/wagtail,mixxorz/wagtail,gasman/wagtail | + import json
+
- from django.forms import widgets
+ from django.forms import Media, widgets
from wagtail.admin.edit_handlers import RichTextFieldPanel
from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter
from wagtail.core.rich_text import features
class DraftailRichTextArea(widgets.Textarea):
# this class's constructor accepts a 'features' kwarg
accepts_features = True
def get_panel(self):
return RichTextFieldPanel
def __init__(self, *args, **kwargs):
self.options = kwargs.pop('options', None)
self.features = kwargs.pop('features', None)
if self.features is None:
self.features = features.get_default_features()
self.converter = ContentstateConverter(self.features)
super().__init__(*args, **kwargs)
def render(self, name, value, attrs=None):
if value is None:
translated_value = None
else:
translated_value = self.converter.from_database_format(value)
return super().render(name, translated_value, attrs)
+ def render_js_init(self, id_, name, value):
+ return "window.draftail.initEditor('{name}', {opts})".format(
+ name=name, opts=json.dumps(self.options))
+
def value_from_datadict(self, data, files, name):
original_value = super().value_from_datadict(data, files, name)
if original_value is None:
return None
return self.converter.to_database_format(original_value)
+ @property
+ def media(self):
+ return Media(js=[
+ 'wagtailadmin/js/draftail.js',
+ ], css={
+ 'all': ['wagtailadmin/css/panels/dratail.css']
+ })
+ | Integrate Draftail-related assets with Django widget | ## Code Before:
from django.forms import widgets
from wagtail.admin.edit_handlers import RichTextFieldPanel
from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter
from wagtail.core.rich_text import features
class DraftailRichTextArea(widgets.Textarea):
# this class's constructor accepts a 'features' kwarg
accepts_features = True
def get_panel(self):
return RichTextFieldPanel
def __init__(self, *args, **kwargs):
self.options = kwargs.pop('options', None)
self.features = kwargs.pop('features', None)
if self.features is None:
self.features = features.get_default_features()
self.converter = ContentstateConverter(self.features)
super().__init__(*args, **kwargs)
def render(self, name, value, attrs=None):
if value is None:
translated_value = None
else:
translated_value = self.converter.from_database_format(value)
return super().render(name, translated_value, attrs)
def value_from_datadict(self, data, files, name):
original_value = super().value_from_datadict(data, files, name)
if original_value is None:
return None
return self.converter.to_database_format(original_value)
## Instruction:
Integrate Draftail-related assets with Django widget
## Code After:
import json
from django.forms import Media, widgets
from wagtail.admin.edit_handlers import RichTextFieldPanel
from wagtail.admin.rich_text.converters.contentstate import ContentstateConverter
from wagtail.core.rich_text import features
class DraftailRichTextArea(widgets.Textarea):
# this class's constructor accepts a 'features' kwarg
accepts_features = True
def get_panel(self):
return RichTextFieldPanel
def __init__(self, *args, **kwargs):
self.options = kwargs.pop('options', None)
self.features = kwargs.pop('features', None)
if self.features is None:
self.features = features.get_default_features()
self.converter = ContentstateConverter(self.features)
super().__init__(*args, **kwargs)
def render(self, name, value, attrs=None):
if value is None:
translated_value = None
else:
translated_value = self.converter.from_database_format(value)
return super().render(name, translated_value, attrs)
def render_js_init(self, id_, name, value):
return "window.draftail.initEditor('{name}', {opts})".format(
name=name, opts=json.dumps(self.options))
def value_from_datadict(self, data, files, name):
original_value = super().value_from_datadict(data, files, name)
if original_value is None:
return None
return self.converter.to_database_format(original_value)
@property
def media(self):
return Media(js=[
'wagtailadmin/js/draftail.js',
], css={
'all': ['wagtailadmin/css/panels/dratail.css']
})
|
3db4d306c779ef3a84133dbbfc5614d514d72411 | pi_gpio/handlers.py | pi_gpio/handlers.py | from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app
HTTP_MANAGER = PinHttpManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
"value": fields.Integer
}
def pin_not_found(self):
return {'message': 'Pin not found'}, 404
class PinList(Pin):
def get(self):
result = HTTP_MANAGER.read_all()
return self.response(result, 200)
class PinDetail(Pin):
def get(self, pin_num):
result = HTTP_MANAGER.read_one(pin_num)
if not result:
return self.pin_not_found()
return self.response(result, 200)
def patch(self, pin_num):
self.parser.add_argument('value', type=int)
args = self.parser.parse_args()
result = HTTP_MANAGER.update_value(pin_num, args['value'])
if not result:
return self.pin_not_found()
return self.response(HTTP_MANAGER.read_one(pin_num), 200)
| from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app
HTTP_MANAGER = PinHttpManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
"value": fields.Integer,
"resistor": fields.String,
"initial": fields.String,
"event": fields.String,
"bounce": fields.Integer
}
def pin_not_found(self):
return {'message': 'Pin not found'}, 404
class PinList(Pin):
def get(self):
result = HTTP_MANAGER.read_all()
return self.response(result, 200)
class PinDetail(Pin):
def get(self, pin_num):
result = HTTP_MANAGER.read_one(pin_num)
if not result:
return self.pin_not_found()
return self.response(result, 200)
def patch(self, pin_num):
self.parser.add_argument('value', type=int)
args = self.parser.parse_args()
result = HTTP_MANAGER.update_value(pin_num, args['value'])
if not result:
return self.pin_not_found()
return self.response(HTTP_MANAGER.read_one(pin_num), 200)
| Add new fields to response | Add new fields to response
| Python | mit | projectweekend/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server,projectweekend/Pi-GPIO-Server,thijstriemstra/Pi-GPIO-Server | from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app
HTTP_MANAGER = PinHttpManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
- "value": fields.Integer
+ "value": fields.Integer,
+ "resistor": fields.String,
+ "initial": fields.String,
+ "event": fields.String,
+ "bounce": fields.Integer
}
def pin_not_found(self):
return {'message': 'Pin not found'}, 404
class PinList(Pin):
def get(self):
result = HTTP_MANAGER.read_all()
return self.response(result, 200)
class PinDetail(Pin):
def get(self, pin_num):
result = HTTP_MANAGER.read_one(pin_num)
if not result:
return self.pin_not_found()
return self.response(result, 200)
def patch(self, pin_num):
self.parser.add_argument('value', type=int)
args = self.parser.parse_args()
result = HTTP_MANAGER.update_value(pin_num, args['value'])
if not result:
return self.pin_not_found()
return self.response(HTTP_MANAGER.read_one(pin_num), 200)
| Add new fields to response | ## Code Before:
from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app
HTTP_MANAGER = PinHttpManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
"value": fields.Integer
}
def pin_not_found(self):
return {'message': 'Pin not found'}, 404
class PinList(Pin):
def get(self):
result = HTTP_MANAGER.read_all()
return self.response(result, 200)
class PinDetail(Pin):
def get(self, pin_num):
result = HTTP_MANAGER.read_one(pin_num)
if not result:
return self.pin_not_found()
return self.response(result, 200)
def patch(self, pin_num):
self.parser.add_argument('value', type=int)
args = self.parser.parse_args()
result = HTTP_MANAGER.update_value(pin_num, args['value'])
if not result:
return self.pin_not_found()
return self.response(HTTP_MANAGER.read_one(pin_num), 200)
## Instruction:
Add new fields to response
## Code After:
from flask.ext.restful import fields
from meta import BasicResource
from config.pins import PinHttpManager
from pi_gpio import app
HTTP_MANAGER = PinHttpManager()
class Pin(BasicResource):
def __init__(self):
super(Pin, self).__init__()
self.fields = {
"num": fields.Integer,
"mode": fields.String,
"value": fields.Integer,
"resistor": fields.String,
"initial": fields.String,
"event": fields.String,
"bounce": fields.Integer
}
def pin_not_found(self):
return {'message': 'Pin not found'}, 404
class PinList(Pin):
def get(self):
result = HTTP_MANAGER.read_all()
return self.response(result, 200)
class PinDetail(Pin):
def get(self, pin_num):
result = HTTP_MANAGER.read_one(pin_num)
if not result:
return self.pin_not_found()
return self.response(result, 200)
def patch(self, pin_num):
self.parser.add_argument('value', type=int)
args = self.parser.parse_args()
result = HTTP_MANAGER.update_value(pin_num, args['value'])
if not result:
return self.pin_not_found()
return self.response(HTTP_MANAGER.read_one(pin_num), 200)
|
23bbb5737602408ba553b77810103d7b32140c89 | test.py | test.py |
import neukrill_net.utils as utils
import neukrill_net.image_processing as image_processing
import csv
import pickle
from sklearn.externals import joblib
import numpy as np
import glob
import os
def main():
settings = utils.Settings('settings.json')
image_fname_dict = settings.image_fnames
processing = lambda image: image_processing.resize_image(image, (48,48))
X, names = utils.load_data(image_fname_dict, processing=processing,
verbose=True)
clf = joblib.load('model.pkl')
p = clf.predict_proba(X)
with open('submission.csv', 'w') as csv_out:
out_writer = csv.writer(csv_out, delimiter=',')
out_writer.writerow(['image'] + list(settings.classes))
for index in range(len(names)):
out_writer.writerow([names[index]] + list(p[index,]))
if __name__ == '__main__':
main()
|
import neukrill_net.utils as utils
import neukrill_net.image_processing as image_processing
import csv
import pickle
from sklearn.externals import joblib
import numpy as np
import glob
import os
def main():
settings = utils.Settings('settings.json')
image_fname_dict = settings.image_fnames
processing = lambda image: image_processing.resize_image(image, (48,48))
X, names = utils.load_data(image_fname_dict, processing=processing,
verbose=True)
clf = joblib.load('model.pkl')
p = clf.predict_proba(X)
utils.write_predictions('submission.csv', p, names, settings)
if __name__ == '__main__':
main()
| Swap to using submission prediction writer function | Swap to using submission prediction writer function
| Python | mit | Neuroglycerin/neukrill-net-work,Neuroglycerin/neukrill-net-work,Neuroglycerin/neukrill-net-work |
import neukrill_net.utils as utils
import neukrill_net.image_processing as image_processing
import csv
import pickle
from sklearn.externals import joblib
import numpy as np
import glob
import os
def main():
settings = utils.Settings('settings.json')
image_fname_dict = settings.image_fnames
processing = lambda image: image_processing.resize_image(image, (48,48))
X, names = utils.load_data(image_fname_dict, processing=processing,
verbose=True)
-
+
clf = joblib.load('model.pkl')
p = clf.predict_proba(X)
+
+ utils.write_predictions('submission.csv', p, names, settings)
+
-
- with open('submission.csv', 'w') as csv_out:
- out_writer = csv.writer(csv_out, delimiter=',')
- out_writer.writerow(['image'] + list(settings.classes))
- for index in range(len(names)):
- out_writer.writerow([names[index]] + list(p[index,]))
if __name__ == '__main__':
main()
| Swap to using submission prediction writer function | ## Code Before:
import neukrill_net.utils as utils
import neukrill_net.image_processing as image_processing
import csv
import pickle
from sklearn.externals import joblib
import numpy as np
import glob
import os
def main():
settings = utils.Settings('settings.json')
image_fname_dict = settings.image_fnames
processing = lambda image: image_processing.resize_image(image, (48,48))
X, names = utils.load_data(image_fname_dict, processing=processing,
verbose=True)
clf = joblib.load('model.pkl')
p = clf.predict_proba(X)
with open('submission.csv', 'w') as csv_out:
out_writer = csv.writer(csv_out, delimiter=',')
out_writer.writerow(['image'] + list(settings.classes))
for index in range(len(names)):
out_writer.writerow([names[index]] + list(p[index,]))
if __name__ == '__main__':
main()
## Instruction:
Swap to using submission prediction writer function
## Code After:
import neukrill_net.utils as utils
import neukrill_net.image_processing as image_processing
import csv
import pickle
from sklearn.externals import joblib
import numpy as np
import glob
import os
def main():
settings = utils.Settings('settings.json')
image_fname_dict = settings.image_fnames
processing = lambda image: image_processing.resize_image(image, (48,48))
X, names = utils.load_data(image_fname_dict, processing=processing,
verbose=True)
clf = joblib.load('model.pkl')
p = clf.predict_proba(X)
utils.write_predictions('submission.csv', p, names, settings)
if __name__ == '__main__':
main()
|
9a19da30a933bc2872b9fc5b5966823c43e1982f | website/pages/tests.py | website/pages/tests.py |
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.template.loader import render_to_string
from website.pages.views import home_page, send_email
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('pages/home.html')
self.assertEqual(response.content.decode(), expected_html)
class SendEmailTest(TestCase):
def test_send_email_url_resolves_to_send_email_view(self):
found = resolve('/send-email/')
self.assertEqual(found.func, send_email)
def test_send_email_returns_correct_html(self):
request = HttpRequest()
response = send_email(request)
expected_html = render_to_string('pages/send_email.html')
self.assertEqual(response.content.decode(), expected_html)
|
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.template.loader import render_to_string
from website.pages.views import home_page, contact
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('pages/home.html')
self.assertEqual(response.content.decode(), expected_html)
class ContactTest(TestCase):
def test_contact_url_resolves_to_contact_view(self):
found = resolve('/contact/')
self.assertEqual(found.func, contact)
def test_contact_returns_correct_html(self):
request = HttpRequest()
response = contact(request)
expected_html = render_to_string('pages/contact.html')
self.assertEqual(response.content.decode(), expected_html)
| Change send email to contact namespace | Change send email to contact namespace | Python | mit | MazeFX/cookiecutter_website_project,MazeFX/cookiecutter_website_project,MazeFX/cookiecutter_website_project,MazeFX/cookiecutter_website_project |
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.template.loader import render_to_string
- from website.pages.views import home_page, send_email
+ from website.pages.views import home_page, contact
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('pages/home.html')
self.assertEqual(response.content.decode(), expected_html)
- class SendEmailTest(TestCase):
+ class ContactTest(TestCase):
- def test_send_email_url_resolves_to_send_email_view(self):
+ def test_contact_url_resolves_to_contact_view(self):
- found = resolve('/send-email/')
+ found = resolve('/contact/')
- self.assertEqual(found.func, send_email)
+ self.assertEqual(found.func, contact)
- def test_send_email_returns_correct_html(self):
+ def test_contact_returns_correct_html(self):
request = HttpRequest()
- response = send_email(request)
+ response = contact(request)
- expected_html = render_to_string('pages/send_email.html')
+ expected_html = render_to_string('pages/contact.html')
self.assertEqual(response.content.decode(), expected_html)
| Change send email to contact namespace | ## Code Before:
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.template.loader import render_to_string
from website.pages.views import home_page, send_email
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('pages/home.html')
self.assertEqual(response.content.decode(), expected_html)
class SendEmailTest(TestCase):
def test_send_email_url_resolves_to_send_email_view(self):
found = resolve('/send-email/')
self.assertEqual(found.func, send_email)
def test_send_email_returns_correct_html(self):
request = HttpRequest()
response = send_email(request)
expected_html = render_to_string('pages/send_email.html')
self.assertEqual(response.content.decode(), expected_html)
## Instruction:
Change send email to contact namespace
## Code After:
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.http import HttpRequest
from django.template.loader import render_to_string
from website.pages.views import home_page, contact
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('pages/home.html')
self.assertEqual(response.content.decode(), expected_html)
class ContactTest(TestCase):
def test_contact_url_resolves_to_contact_view(self):
found = resolve('/contact/')
self.assertEqual(found.func, contact)
def test_contact_returns_correct_html(self):
request = HttpRequest()
response = contact(request)
expected_html = render_to_string('pages/contact.html')
self.assertEqual(response.content.decode(), expected_html)
|
f185f04f6efdabe161ae29ba72f7208b8adccc41 | bulletin/tools/plugins/models.py | bulletin/tools/plugins/models.py | from django.db import models
from bulletin.models import Post
class Event(Post):
start_date = models.DateTimeField()
end_date = models.DateTimeField(null=True, blank=True)
time = models.CharField(max_length=255,
null=True, blank=True)
organization = models.CharField(max_length=255,
null=True, blank=True)
location = models.CharField(max_length=255)
class Job(Post):
organization = models.CharField(max_length=255)
class NewResource(Post):
blurb = models.TextField()
class Opportunity(Post):
blurb = models.TextField()
class Meta:
verbose_name_plural = 'opportunities'
class Story(Post):
blurb = models.TextField()
date = models.DateTimeField()
class Meta:
verbose_name_plural = 'stories'
| from django.db import models
from bulletin.models import Post
class Event(Post):
start_date = models.DateTimeField()
end_date = models.DateTimeField(null=True, blank=True)
time = models.CharField(max_length=255,
null=True, blank=True)
organization = models.CharField(max_length=255,
null=True, blank=True)
location = models.CharField(max_length=255)
class Job(Post):
organization = models.CharField(max_length=255)
class NewResource(Post):
blurb = models.TextField()
verbose_name = 'newresource'
class Opportunity(Post):
blurb = models.TextField()
class Meta:
verbose_name_plural = 'opportunities'
class Story(Post):
blurb = models.TextField()
date = models.DateTimeField()
class Meta:
verbose_name_plural = 'stories'
| Set verbose name of NewResource. | Set verbose name of NewResource.
| Python | mit | AASHE/django-bulletin,AASHE/django-bulletin,AASHE/django-bulletin | from django.db import models
from bulletin.models import Post
class Event(Post):
start_date = models.DateTimeField()
end_date = models.DateTimeField(null=True, blank=True)
time = models.CharField(max_length=255,
null=True, blank=True)
organization = models.CharField(max_length=255,
null=True, blank=True)
location = models.CharField(max_length=255)
class Job(Post):
organization = models.CharField(max_length=255)
class NewResource(Post):
blurb = models.TextField()
+ verbose_name = 'newresource'
class Opportunity(Post):
blurb = models.TextField()
class Meta:
verbose_name_plural = 'opportunities'
class Story(Post):
blurb = models.TextField()
date = models.DateTimeField()
class Meta:
verbose_name_plural = 'stories'
| Set verbose name of NewResource. | ## Code Before:
from django.db import models
from bulletin.models import Post
class Event(Post):
start_date = models.DateTimeField()
end_date = models.DateTimeField(null=True, blank=True)
time = models.CharField(max_length=255,
null=True, blank=True)
organization = models.CharField(max_length=255,
null=True, blank=True)
location = models.CharField(max_length=255)
class Job(Post):
organization = models.CharField(max_length=255)
class NewResource(Post):
blurb = models.TextField()
class Opportunity(Post):
blurb = models.TextField()
class Meta:
verbose_name_plural = 'opportunities'
class Story(Post):
blurb = models.TextField()
date = models.DateTimeField()
class Meta:
verbose_name_plural = 'stories'
## Instruction:
Set verbose name of NewResource.
## Code After:
from django.db import models
from bulletin.models import Post
class Event(Post):
start_date = models.DateTimeField()
end_date = models.DateTimeField(null=True, blank=True)
time = models.CharField(max_length=255,
null=True, blank=True)
organization = models.CharField(max_length=255,
null=True, blank=True)
location = models.CharField(max_length=255)
class Job(Post):
organization = models.CharField(max_length=255)
class NewResource(Post):
blurb = models.TextField()
verbose_name = 'newresource'
class Opportunity(Post):
blurb = models.TextField()
class Meta:
verbose_name_plural = 'opportunities'
class Story(Post):
blurb = models.TextField()
date = models.DateTimeField()
class Meta:
verbose_name_plural = 'stories'
|
4641b9a1b9a79fdeb0aaa3264de7bd1703b1d1fa | alexandria/web.py | alexandria/web.py | from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return render_template('index.html')
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
| from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
| Fix return on active user accessing the portal | Fix return on active user accessing the portal
| Python | mit | citruspi/Alexandria,citruspi/Alexandria | from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
- return render_template('index.html')
+ return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
| Fix return on active user accessing the portal | ## Code Before:
from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return render_template('index.html')
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
## Instruction:
Fix return on active user accessing the portal
## Code After:
from alexandria import app, mongo
from decorators import *
from flask import render_template, request, jsonify, g, send_from_directory, redirect, url_for, session, flash
import os
import shutil
import requests
from pymongo import MongoClient
from functools import wraps
import bcrypt
from bson.objectid import ObjectId
@app.route('/', methods=['GET'])
@authenticated
def index():
return render_template('app.html')
@app.route('/portal')
def portal():
if not session.get('username'):
return render_template('portal.html')
else:
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('username', None)
session.pop('role', None)
session.pop('realname', None)
return redirect(url_for('index'))
@app.route('/download/<id>/<format>')
@authenticated
def download(id, format):
book = mongo.Books.find({'id':id})[0]
response = send_from_directory(app.config['LIB_DIR'], id+'.'+format)
response.headers.add('Content-Disposition', 'attachment; filename="' + book['title'] + '.' + format + '"')
return response
@app.route('/upload')
@authenticated
@administrator
def upload():
return render_template('upload.html')
if __name__ == "__main__":
app.run()
|
e3928f489f481c9e44c634d7ee98afc5425b4432 | tests/test_yaml_utils.py | tests/test_yaml_utils.py | import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_operations_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_operations_from_docstring(docstring) == {}
| import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_operations_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_operations_from_docstring(docstring) == {}
def test_dict_to_yaml_unicode():
assert yaml_utils.dict_to_yaml({"가": "나"}) == '"\\uAC00": "\\uB098"\n'
assert yaml_utils.dict_to_yaml({"가": "나"}, {"allow_unicode": True}) == "가: 나\n"
| Add regression test for generating yaml with unicode | Add regression test for generating yaml with unicode
| Python | mit | marshmallow-code/smore,marshmallow-code/apispec | import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_operations_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_operations_from_docstring(docstring) == {}
+
+ def test_dict_to_yaml_unicode():
+ assert yaml_utils.dict_to_yaml({"가": "나"}) == '"\\uAC00": "\\uB098"\n'
+ assert yaml_utils.dict_to_yaml({"가": "나"}, {"allow_unicode": True}) == "가: 나\n"
+ | Add regression test for generating yaml with unicode | ## Code Before:
import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_operations_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_operations_from_docstring(docstring) == {}
## Instruction:
Add regression test for generating yaml with unicode
## Code After:
import pytest
from apispec import yaml_utils
def test_load_yaml_from_docstring():
def f():
"""
Foo
bar
baz quux
---
herp: 1
derp: 2
"""
result = yaml_utils.load_yaml_from_docstring(f.__doc__)
assert result == {"herp": 1, "derp": 2}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_yaml_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_yaml_from_docstring(docstring) == {}
@pytest.mark.parametrize("docstring", (None, "", "---"))
def test_load_operations_from_docstring_empty_docstring(docstring):
assert yaml_utils.load_operations_from_docstring(docstring) == {}
def test_dict_to_yaml_unicode():
assert yaml_utils.dict_to_yaml({"가": "나"}) == '"\\uAC00": "\\uB098"\n'
assert yaml_utils.dict_to_yaml({"가": "나"}, {"allow_unicode": True}) == "가: 나\n"
|
baf09f8b308626abb81431ddca4498409fc9d5ce | campaigns/tests/test_views.py | campaigns/tests/test_views.py | from django.test import TestCase
from django.http import HttpRequest
from campaigns.views import create_campaign
from campaigns.models import Campaign
from campaigns.forms import CampaignForm
class HomePageTest(TestCase):
def test_does_root_url_resolves_the_home_page(self):
called = self.client.get('/')
self.assertTemplateUsed(called, 'home.html')
class CampaignsViewsTest(TestCase):
def test_does_create_campaign_resolves_the_right_url(self):
called = self.client.get('/campaigns/new')
self.assertTemplateUsed(called, 'new_campaign.html')
# Trying to do self.client.post was using GET request for some
# reason so i made it that ugly
def test_does_create_camapign_saves_objects_with_POST_requests(self):
self.assertEqual(Campaign.objects.count(), 0)
request = HttpRequest()
request.method = 'POST'
request.POST['title'] = 'C1'
request.POST['description'] = 'C1Descr'
create_campaign(request)
campaign = Campaign.objects.first()
self.assertEqual(Campaign.objects.count(), 1)
self.assertEqual(campaign.title, 'C1')
self.assertEqual(campaign.description, 'C1Descr')
| from django.test import TestCase
from django.http import HttpRequest
from campaigns.views import create_campaign
from campaigns.models import Campaign
from campaigns.forms import CampaignForm
def make_POST_request(titleValue, descriptionValue):
request = HttpRequest()
request.method = 'POST'
request.POST['title'] = titleValue
request.POST['description'] = descriptionValue
return request
class HomePageTest(TestCase):
def test_does_root_url_resolves_the_home_page(self):
called = self.client.get('/')
self.assertTemplateUsed(called, 'home.html')
class CampaignsViewsTest(TestCase):
def test_does_create_campaign_resolves_the_right_url(self):
called = self.client.get('/campaigns/new')
self.assertTemplateUsed(called, 'new_campaign.html')
# Trying to do self.client.post was using GET request for some
# reason so i made it that ugly
def test_does_create_campaign_saves_objects_with_POST_requests(self):
self.assertEqual(Campaign.objects.count(), 0)
create_campaign(make_POST_request('C1', 'C1Descr'))
campaign = Campaign.objects.first()
self.assertEqual(Campaign.objects.count(), 1)
self.assertEqual(campaign.title, 'C1')
self.assertEqual(campaign.description, 'C1Descr')
def test_create_campaign_dont_saves_empty_objects(self):
self.assertEqual(Campaign.objects.count(), 0)
create_campaign(make_POST_request('', ''))
self.assertEqual(Campaign.objects.count(), 0)
| Refactor some redundancy in the views tests | Refactor some redundancy in the views tests
| Python | apache-2.0 | Springsteen/tues_admission,Springsteen/tues_admission,Springsteen/tues_admission,Springsteen/tues_admission | from django.test import TestCase
from django.http import HttpRequest
from campaigns.views import create_campaign
from campaigns.models import Campaign
from campaigns.forms import CampaignForm
+ def make_POST_request(titleValue, descriptionValue):
+ request = HttpRequest()
+ request.method = 'POST'
+ request.POST['title'] = titleValue
+ request.POST['description'] = descriptionValue
+ return request
+
class HomePageTest(TestCase):
def test_does_root_url_resolves_the_home_page(self):
called = self.client.get('/')
self.assertTemplateUsed(called, 'home.html')
+
class CampaignsViewsTest(TestCase):
def test_does_create_campaign_resolves_the_right_url(self):
called = self.client.get('/campaigns/new')
self.assertTemplateUsed(called, 'new_campaign.html')
# Trying to do self.client.post was using GET request for some
# reason so i made it that ugly
- def test_does_create_camapign_saves_objects_with_POST_requests(self):
+ def test_does_create_campaign_saves_objects_with_POST_requests(self):
self.assertEqual(Campaign.objects.count(), 0)
+ create_campaign(make_POST_request('C1', 'C1Descr'))
- request = HttpRequest()
- request.method = 'POST'
- request.POST['title'] = 'C1'
- request.POST['description'] = 'C1Descr'
- create_campaign(request)
campaign = Campaign.objects.first()
self.assertEqual(Campaign.objects.count(), 1)
self.assertEqual(campaign.title, 'C1')
self.assertEqual(campaign.description, 'C1Descr')
+ def test_create_campaign_dont_saves_empty_objects(self):
+ self.assertEqual(Campaign.objects.count(), 0)
+ create_campaign(make_POST_request('', ''))
+ self.assertEqual(Campaign.objects.count(), 0)
+ | Refactor some redundancy in the views tests | ## Code Before:
from django.test import TestCase
from django.http import HttpRequest
from campaigns.views import create_campaign
from campaigns.models import Campaign
from campaigns.forms import CampaignForm
class HomePageTest(TestCase):
def test_does_root_url_resolves_the_home_page(self):
called = self.client.get('/')
self.assertTemplateUsed(called, 'home.html')
class CampaignsViewsTest(TestCase):
def test_does_create_campaign_resolves_the_right_url(self):
called = self.client.get('/campaigns/new')
self.assertTemplateUsed(called, 'new_campaign.html')
# Trying to do self.client.post was using GET request for some
# reason so i made it that ugly
def test_does_create_camapign_saves_objects_with_POST_requests(self):
self.assertEqual(Campaign.objects.count(), 0)
request = HttpRequest()
request.method = 'POST'
request.POST['title'] = 'C1'
request.POST['description'] = 'C1Descr'
create_campaign(request)
campaign = Campaign.objects.first()
self.assertEqual(Campaign.objects.count(), 1)
self.assertEqual(campaign.title, 'C1')
self.assertEqual(campaign.description, 'C1Descr')
## Instruction:
Refactor some redundancy in the views tests
## Code After:
from django.test import TestCase
from django.http import HttpRequest
from campaigns.views import create_campaign
from campaigns.models import Campaign
from campaigns.forms import CampaignForm
def make_POST_request(titleValue, descriptionValue):
request = HttpRequest()
request.method = 'POST'
request.POST['title'] = titleValue
request.POST['description'] = descriptionValue
return request
class HomePageTest(TestCase):
def test_does_root_url_resolves_the_home_page(self):
called = self.client.get('/')
self.assertTemplateUsed(called, 'home.html')
class CampaignsViewsTest(TestCase):
def test_does_create_campaign_resolves_the_right_url(self):
called = self.client.get('/campaigns/new')
self.assertTemplateUsed(called, 'new_campaign.html')
# Trying to do self.client.post was using GET request for some
# reason so i made it that ugly
def test_does_create_campaign_saves_objects_with_POST_requests(self):
self.assertEqual(Campaign.objects.count(), 0)
create_campaign(make_POST_request('C1', 'C1Descr'))
campaign = Campaign.objects.first()
self.assertEqual(Campaign.objects.count(), 1)
self.assertEqual(campaign.title, 'C1')
self.assertEqual(campaign.description, 'C1Descr')
def test_create_campaign_dont_saves_empty_objects(self):
self.assertEqual(Campaign.objects.count(), 0)
create_campaign(make_POST_request('', ''))
self.assertEqual(Campaign.objects.count(), 0)
|
2ca6f765a3bd1eca6bd255f9c679c9fbea78484a | run_maya_tests.py | run_maya_tests.py |
import sys
import nose
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
|
import sys
import nose
import logging
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
log = logging.getLogger()
# Discard default Maya logging handler
log.handlers[:] = []
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
| Enhance readability of test output | Enhance readability of test output
| Python | mit | MoonShineVFX/core,mindbender-studio/core,MoonShineVFX/core,mindbender-studio/core,getavalon/core,getavalon/core |
import sys
import nose
+ import logging
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
+
+ log = logging.getLogger()
+
+ # Discard default Maya logging handler
+ log.handlers[:] = []
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
| Enhance readability of test output | ## Code Before:
import sys
import nose
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
## Instruction:
Enhance readability of test output
## Code After:
import sys
import nose
import logging
import warnings
from nose_exclude import NoseExclude
warnings.filterwarnings("ignore", category=DeprecationWarning)
if __name__ == "__main__":
from maya import standalone
standalone.initialize()
log = logging.getLogger()
# Discard default Maya logging handler
log.handlers[:] = []
argv = sys.argv[:]
argv.extend([
# Sometimes, files from Windows accessed
# from Linux cause the executable flag to be
# set, and Nose has an aversion to these
# per default.
"--exe",
"--verbose",
"--with-doctest",
"--with-coverage",
"--cover-html",
"--cover-tests",
"--cover-erase",
"--exclude-dir=mindbender/nuke",
"--exclude-dir=mindbender/houdini",
"--exclude-dir=mindbender/schema",
"--exclude-dir=mindbender/plugins",
# We can expect any vendors to
# be well tested beforehand.
"--exclude-dir=mindbender/vendor",
])
nose.main(argv=argv,
addplugins=[NoseExclude()])
|
6578b6d2dfca38940be278d82e4f8d8248ae3c79 | convert_codecs.py | convert_codecs.py |
import codecs
from docopt import docopt
__version__ = '0.1'
__author__ = 'Honghe'
BLOCKSIZE = 1024**2 # size in bytes
def convert(sourceFile, targetFile, sourceEncoding, targetEncoding):
with codecs.open(sourceFile, 'rb', sourceEncoding) as sfile:
with codecs.open(targetFile, 'wb', targetEncoding) as tfile:
while True:
contents = sfile.read(BLOCKSIZE)
if not contents:
break
tfile.write(contents)
if __name__ == '__main__':
arguments = docopt(__doc__)
sourceFile = arguments['<sourceFile>']
targetFile = arguments['<targetFile>']
sourceEncoding = arguments['<sourceEncoding>']
targetEncoding = arguments['<targetEncoding>']
convert(sourceFile, targetFile, sourceEncoding, targetEncoding)
|
import codecs
from docopt import docopt
__version__ = '0.1'
__author__ = 'Honghe'
BLOCKSIZE = 1024 # number of characters in corresponding encoding, not bytes
def convert(sourceFile, targetFile, sourceEncoding, targetEncoding):
with codecs.open(sourceFile, 'rb', sourceEncoding) as sfile:
with codecs.open(targetFile, 'wb', targetEncoding) as tfile:
while True:
contents = sfile.read(BLOCKSIZE)
if not contents:
break
tfile.write(contents)
if __name__ == '__main__':
arguments = docopt(__doc__)
sourceFile = arguments['<sourceFile>']
targetFile = arguments['<targetFile>']
sourceEncoding = arguments['<sourceEncoding>']
targetEncoding = arguments['<targetEncoding>']
convert(sourceFile, targetFile, sourceEncoding, targetEncoding)
| Correct the comment of BLOCKSIZE | Correct the comment of BLOCKSIZE
| Python | apache-2.0 | Honghe/convert_codecs |
import codecs
from docopt import docopt
__version__ = '0.1'
__author__ = 'Honghe'
- BLOCKSIZE = 1024**2 # size in bytes
+ BLOCKSIZE = 1024 # number of characters in corresponding encoding, not bytes
def convert(sourceFile, targetFile, sourceEncoding, targetEncoding):
with codecs.open(sourceFile, 'rb', sourceEncoding) as sfile:
with codecs.open(targetFile, 'wb', targetEncoding) as tfile:
while True:
contents = sfile.read(BLOCKSIZE)
if not contents:
break
tfile.write(contents)
if __name__ == '__main__':
arguments = docopt(__doc__)
sourceFile = arguments['<sourceFile>']
targetFile = arguments['<targetFile>']
sourceEncoding = arguments['<sourceEncoding>']
targetEncoding = arguments['<targetEncoding>']
convert(sourceFile, targetFile, sourceEncoding, targetEncoding)
| Correct the comment of BLOCKSIZE | ## Code Before:
import codecs
from docopt import docopt
__version__ = '0.1'
__author__ = 'Honghe'
BLOCKSIZE = 1024**2 # size in bytes
def convert(sourceFile, targetFile, sourceEncoding, targetEncoding):
with codecs.open(sourceFile, 'rb', sourceEncoding) as sfile:
with codecs.open(targetFile, 'wb', targetEncoding) as tfile:
while True:
contents = sfile.read(BLOCKSIZE)
if not contents:
break
tfile.write(contents)
if __name__ == '__main__':
arguments = docopt(__doc__)
sourceFile = arguments['<sourceFile>']
targetFile = arguments['<targetFile>']
sourceEncoding = arguments['<sourceEncoding>']
targetEncoding = arguments['<targetEncoding>']
convert(sourceFile, targetFile, sourceEncoding, targetEncoding)
## Instruction:
Correct the comment of BLOCKSIZE
## Code After:
import codecs
from docopt import docopt
__version__ = '0.1'
__author__ = 'Honghe'
BLOCKSIZE = 1024 # number of characters in corresponding encoding, not bytes
def convert(sourceFile, targetFile, sourceEncoding, targetEncoding):
with codecs.open(sourceFile, 'rb', sourceEncoding) as sfile:
with codecs.open(targetFile, 'wb', targetEncoding) as tfile:
while True:
contents = sfile.read(BLOCKSIZE)
if not contents:
break
tfile.write(contents)
if __name__ == '__main__':
arguments = docopt(__doc__)
sourceFile = arguments['<sourceFile>']
targetFile = arguments['<targetFile>']
sourceEncoding = arguments['<sourceEncoding>']
targetEncoding = arguments['<targetEncoding>']
convert(sourceFile, targetFile, sourceEncoding, targetEncoding)
|
649bea9ce3ebaf4ba44919097b731ba915703852 | alembic/versions/30d0a626888_add_username.py | alembic/versions/30d0a626888_add_username.py |
# revision identifiers, used by Alembic.
revision = '30d0a626888'
down_revision = '51375067b45'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('_user', sa.Column('username', sa.Unicode(255), unique=True))
op.create_unique_constraint(
'_user_email_key', '_user', ['email'])
def downgrade():
op.drop_column('_user', 'username')
op.drop_constraint(
'_user_email_key', table_name='_user', type_='unique')
|
# revision identifiers, used by Alembic.
revision = '30d0a626888'
down_revision = '51375067b45'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
"""
SQL That equal to the following
ALTER TABLE app_name._user ADD COLUMN username varchar(255);
ALTER TABLE app_name._user ADD CONSTRAINT '_user_email_key' UNIQUE('email');
UPDATE app_name._version set version_num = '30d0a626888;
"""
op.add_column('_user', sa.Column('username', sa.Unicode(255), unique=True))
op.create_unique_constraint(
'_user_email_key', '_user', ['email'])
def downgrade():
op.drop_column('_user', 'username')
op.drop_constraint(
'_user_email_key', table_name='_user', type_='unique')
| Add generate sql example as comment | Add generate sql example as comment
| Python | apache-2.0 | SkygearIO/skygear-server,rickmak/skygear-server,rickmak/skygear-server,SkygearIO/skygear-server,rickmak/skygear-server,SkygearIO/skygear-server,SkygearIO/skygear-server |
# revision identifiers, used by Alembic.
revision = '30d0a626888'
down_revision = '51375067b45'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
+ """
+ SQL That equal to the following
+ ALTER TABLE app_name._user ADD COLUMN username varchar(255);
+ ALTER TABLE app_name._user ADD CONSTRAINT '_user_email_key' UNIQUE('email');
+ UPDATE app_name._version set version_num = '30d0a626888;
+ """
op.add_column('_user', sa.Column('username', sa.Unicode(255), unique=True))
op.create_unique_constraint(
'_user_email_key', '_user', ['email'])
def downgrade():
op.drop_column('_user', 'username')
op.drop_constraint(
'_user_email_key', table_name='_user', type_='unique')
| Add generate sql example as comment | ## Code Before:
# revision identifiers, used by Alembic.
revision = '30d0a626888'
down_revision = '51375067b45'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('_user', sa.Column('username', sa.Unicode(255), unique=True))
op.create_unique_constraint(
'_user_email_key', '_user', ['email'])
def downgrade():
op.drop_column('_user', 'username')
op.drop_constraint(
'_user_email_key', table_name='_user', type_='unique')
## Instruction:
Add generate sql example as comment
## Code After:
# revision identifiers, used by Alembic.
revision = '30d0a626888'
down_revision = '51375067b45'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
"""
SQL That equal to the following
ALTER TABLE app_name._user ADD COLUMN username varchar(255);
ALTER TABLE app_name._user ADD CONSTRAINT '_user_email_key' UNIQUE('email');
UPDATE app_name._version set version_num = '30d0a626888;
"""
op.add_column('_user', sa.Column('username', sa.Unicode(255), unique=True))
op.create_unique_constraint(
'_user_email_key', '_user', ['email'])
def downgrade():
op.drop_column('_user', 'username')
op.drop_constraint(
'_user_email_key', table_name='_user', type_='unique')
|
281a096cea735845bdb74d60abf14f1422f2c624 | test_runner/executable.py | test_runner/executable.py | import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
if __name__ == '__main__':
argh.dispatch_command(main)
| import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
argh.dispatch_command(main)
| Move command dispatch into full module | Move command dispatch into full module
| Python | mit | rcbops-qa/test_runner | import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
+ argh.dispatch_command(main)
- if __name__ == '__main__':
- argh.dispatch_command(main)
- | Move command dispatch into full module | ## Code Before:
import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
if __name__ == '__main__':
argh.dispatch_command(main)
## Instruction:
Move command dispatch into full module
## Code After:
import argh
from .environments import Environment
from .frameworks import Tempest
from .utils import cleanup, Reporter
LOG = Reporter(__name__).setup()
def main(endpoint, username='admin', password='secrete', test_path='api'):
environment = Environment(username, password, endpoint)
with cleanup(environment):
environment.build()
framework = Tempest(environment, repo_dir='/opt/tempest',
test_path=test_path)
results = framework.run_tests()
LOG.info('Results: {0}'.format(results))
argh.dispatch_command(main)
|
0dd935a383d4b8d066dc091226b61119d245a7f9 | threeOhOne.py | threeOhOne.py |
import csv
class ThreeOhOne:
def __ini__(self):
pass
def main():
threeOhOne = ThreeOhOne()
if __name__ == "__main__":
main()
|
import sys
import csv
class ThreeOhOne:
outputDir = 'outputs'
def __init__(self, filename):
self._process(sys.argv[1])
def _process(self, filename):
try:
fd = open(filename, 'rt')
except FileNotFoundError:
print('Error: File not found ;/')
def main():
if len(sys.argv) < 2:
print("usage: " + sys.argv[0] + " <the_file.csv>")
exit(1)
else:
threeOhOne = ThreeOhOne(sys.argv[1])
if __name__ == "__main__":
main()
| Add command line argument capability | [py] Add command line argument capability
| Python | mit | claudemuller/301csv2htaccess |
+ import sys
import csv
class ThreeOhOne:
+ outputDir = 'outputs'
+
- def __ini__(self):
+ def __init__(self, filename):
- pass
+ self._process(sys.argv[1])
+
+ def _process(self, filename):
+ try:
+ fd = open(filename, 'rt')
+
+
+ except FileNotFoundError:
+ print('Error: File not found ;/')
def main():
+ if len(sys.argv) < 2:
+ print("usage: " + sys.argv[0] + " <the_file.csv>")
+ exit(1)
+ else:
- threeOhOne = ThreeOhOne()
+ threeOhOne = ThreeOhOne(sys.argv[1])
if __name__ == "__main__":
main()
| Add command line argument capability | ## Code Before:
import csv
class ThreeOhOne:
def __ini__(self):
pass
def main():
threeOhOne = ThreeOhOne()
if __name__ == "__main__":
main()
## Instruction:
Add command line argument capability
## Code After:
import sys
import csv
class ThreeOhOne:
outputDir = 'outputs'
def __init__(self, filename):
self._process(sys.argv[1])
def _process(self, filename):
try:
fd = open(filename, 'rt')
except FileNotFoundError:
print('Error: File not found ;/')
def main():
if len(sys.argv) < 2:
print("usage: " + sys.argv[0] + " <the_file.csv>")
exit(1)
else:
threeOhOne = ThreeOhOne(sys.argv[1])
if __name__ == "__main__":
main()
|
52c7321c78c8a81b6b557d67fe5af44b8b32df4c | src/octoprint/__main__.py | src/octoprint/__main__.py | from __future__ import absolute_import, division, print_function
if __name__ == "__main__":
import octoprint
octoprint.main()
| from __future__ import absolute_import, division, print_function
import sys
if sys.version_info[0] >= 3:
raise Exception("Octoprint does not support Python 3")
if __name__ == "__main__":
import octoprint
octoprint.main()
| Handle unsupported version at runtime. | Handle unsupported version at runtime.
If you have an ancient setuptools, 4a36ddb3aa77b8d1b1a64c197607fa652705856c
won't successfully prevent installing. These changes will at least give a sane error,
rather then just barfing on random syntax errors due to the `unicode` type not
being present in py3k.
Cherry picked from 2f20f2d
| Python | agpl-3.0 | Jaesin/OctoPrint,foosel/OctoPrint,Jaesin/OctoPrint,Jaesin/OctoPrint,foosel/OctoPrint,Jaesin/OctoPrint,foosel/OctoPrint,foosel/OctoPrint | from __future__ import absolute_import, division, print_function
+
+ import sys
+ if sys.version_info[0] >= 3:
+ raise Exception("Octoprint does not support Python 3")
if __name__ == "__main__":
import octoprint
octoprint.main()
| Handle unsupported version at runtime. | ## Code Before:
from __future__ import absolute_import, division, print_function
if __name__ == "__main__":
import octoprint
octoprint.main()
## Instruction:
Handle unsupported version at runtime.
## Code After:
from __future__ import absolute_import, division, print_function
import sys
if sys.version_info[0] >= 3:
raise Exception("Octoprint does not support Python 3")
if __name__ == "__main__":
import octoprint
octoprint.main()
|
d54e5f25601fe2f57a2c6be5524430f0068e05c4 | image_translate/frames_rendering.py | image_translate/frames_rendering.py | import sys
import pygame
from pygame.locals import *
import opencv
#this is important for capturing/displaying images
from opencv import highgui
def get_image(camera):
img = highgui.cvQueryFrame(camera)
# Add the line below if you need it (Ubuntu 8.04+)
# im = opencv.cvGetMat(im)
# convert Ipl image to PIL image
return opencv.adaptors.Ipl2PIL(img)
def render_flipped_camera():
camera = highgui.cvCreateCameraCapture(0)
fps = 30.0
pygame.init()
pygame.display.set_mode((640, 480))
pygame.display.set_caption("WebCam Demo")
screen = pygame.display.get_surface()
while True:
events = pygame.event.get()
for event in events:
if event.type == QUIT or event.type == KEYDOWN:
sys.exit(0)
im = get_image(camera)
pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)
screen.blit(pg_img, (0, 0))
pygame.display.flip()
pygame.time.delay(int(1000 * 1.0/fps))
if __name__ == "__main__":
render_flipped_camera()
| import sys
import pygame
from pygame.locals import QUIT, KEYDOWN
import opencv
#this is important for capturing/displaying images
from opencv import highgui
def get_image(camera):
img = highgui.cvQueryFrame(camera)
# Add the line below if you need it (Ubuntu 8.04+)
# im = opencv.cvGetMat(im)
# convert Ipl image to PIL image
return opencv.adaptors.Ipl2PIL(img)
def render_flipped_camera():
camera = highgui.cvCreateCameraCapture(0)
fps = 30.0
pygame.init()
pygame.display.set_mode((640, 480))
pygame.display.set_caption("WebCam Demo")
screen = pygame.display.get_surface()
while True:
events = pygame.event.get()
for event in events:
if event.type == QUIT or event.type == KEYDOWN:
sys.exit(0)
im = get_image(camera)
pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)
screen.blit(pg_img, (0, 0))
pygame.display.flip()
pygame.time.delay(int(1000 * 1.0/fps))
if __name__ == "__main__":
render_flipped_camera()
| Remove brute and inconvinient star import | Remove brute and inconvinient star import | Python | mit | duboviy/study_languages | import sys
import pygame
- from pygame.locals import *
+ from pygame.locals import QUIT, KEYDOWN
import opencv
#this is important for capturing/displaying images
from opencv import highgui
def get_image(camera):
img = highgui.cvQueryFrame(camera)
# Add the line below if you need it (Ubuntu 8.04+)
# im = opencv.cvGetMat(im)
# convert Ipl image to PIL image
return opencv.adaptors.Ipl2PIL(img)
def render_flipped_camera():
camera = highgui.cvCreateCameraCapture(0)
fps = 30.0
pygame.init()
pygame.display.set_mode((640, 480))
pygame.display.set_caption("WebCam Demo")
screen = pygame.display.get_surface()
while True:
events = pygame.event.get()
for event in events:
if event.type == QUIT or event.type == KEYDOWN:
sys.exit(0)
im = get_image(camera)
pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)
screen.blit(pg_img, (0, 0))
pygame.display.flip()
pygame.time.delay(int(1000 * 1.0/fps))
if __name__ == "__main__":
render_flipped_camera()
| Remove brute and inconvinient star import | ## Code Before:
import sys
import pygame
from pygame.locals import *
import opencv
#this is important for capturing/displaying images
from opencv import highgui
def get_image(camera):
img = highgui.cvQueryFrame(camera)
# Add the line below if you need it (Ubuntu 8.04+)
# im = opencv.cvGetMat(im)
# convert Ipl image to PIL image
return opencv.adaptors.Ipl2PIL(img)
def render_flipped_camera():
camera = highgui.cvCreateCameraCapture(0)
fps = 30.0
pygame.init()
pygame.display.set_mode((640, 480))
pygame.display.set_caption("WebCam Demo")
screen = pygame.display.get_surface()
while True:
events = pygame.event.get()
for event in events:
if event.type == QUIT or event.type == KEYDOWN:
sys.exit(0)
im = get_image(camera)
pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)
screen.blit(pg_img, (0, 0))
pygame.display.flip()
pygame.time.delay(int(1000 * 1.0/fps))
if __name__ == "__main__":
render_flipped_camera()
## Instruction:
Remove brute and inconvinient star import
## Code After:
import sys
import pygame
from pygame.locals import QUIT, KEYDOWN
import opencv
#this is important for capturing/displaying images
from opencv import highgui
def get_image(camera):
img = highgui.cvQueryFrame(camera)
# Add the line below if you need it (Ubuntu 8.04+)
# im = opencv.cvGetMat(im)
# convert Ipl image to PIL image
return opencv.adaptors.Ipl2PIL(img)
def render_flipped_camera():
camera = highgui.cvCreateCameraCapture(0)
fps = 30.0
pygame.init()
pygame.display.set_mode((640, 480))
pygame.display.set_caption("WebCam Demo")
screen = pygame.display.get_surface()
while True:
events = pygame.event.get()
for event in events:
if event.type == QUIT or event.type == KEYDOWN:
sys.exit(0)
im = get_image(camera)
pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode)
screen.blit(pg_img, (0, 0))
pygame.display.flip()
pygame.time.delay(int(1000 * 1.0/fps))
if __name__ == "__main__":
render_flipped_camera()
|
1d53f6dc8346a655a86e670d0d4de56f7dc93d04 | gala/sparselol.py | gala/sparselol.py | import numpy as np
from scipy import sparse
from .sparselol_cy import extents_count
def extents(labels):
"""Compute the extents of every integer value in ``arr``.
Parameters
----------
labels : array of ints
The array of values to be mapped.
Returns
-------
locs : sparse.csr_matrix
A sparse matrix in which the nonzero elements of row i are the
indices of value i in ``arr``.
"""
labels = labels.ravel()
counts = np.bincount(labels)
indptr = np.concatenate([[0], np.cumsum(counts)])
indices = np.empty(labels.size, int)
extents_count(labels.ravel(), indptr.copy(), out=indices)
locs = sparse.csr_matrix((indices, indices, indptr), dtype=int)
return locs | import numpy as np
from scipy import sparse
from .sparselol_cy import extents_count
def extents(labels):
"""Compute the extents of every integer value in ``arr``.
Parameters
----------
labels : array of ints
The array of values to be mapped.
Returns
-------
locs : sparse.csr_matrix
A sparse matrix in which the nonzero elements of row i are the
indices of value i in ``arr``.
"""
labels = labels.ravel()
counts = np.bincount(labels)
indptr = np.concatenate([[0], np.cumsum(counts)])
indices = np.empty(labels.size, int)
extents_count(labels.ravel(), indptr.copy(), out=indices)
one = np.ones((1,), dtype=int)
data = np.lib.as_strided(one, shape=indices.shape, strides=(0,))
locs = sparse.csr_matrix((data, indices, indptr), dtype=int)
return locs | Use stride tricks to save data memory | Use stride tricks to save data memory
| Python | bsd-3-clause | janelia-flyem/gala,jni/gala | import numpy as np
from scipy import sparse
from .sparselol_cy import extents_count
def extents(labels):
"""Compute the extents of every integer value in ``arr``.
Parameters
----------
labels : array of ints
The array of values to be mapped.
Returns
-------
locs : sparse.csr_matrix
A sparse matrix in which the nonzero elements of row i are the
indices of value i in ``arr``.
"""
labels = labels.ravel()
counts = np.bincount(labels)
indptr = np.concatenate([[0], np.cumsum(counts)])
indices = np.empty(labels.size, int)
extents_count(labels.ravel(), indptr.copy(), out=indices)
+ one = np.ones((1,), dtype=int)
+ data = np.lib.as_strided(one, shape=indices.shape, strides=(0,))
- locs = sparse.csr_matrix((indices, indices, indptr), dtype=int)
+ locs = sparse.csr_matrix((data, indices, indptr), dtype=int)
return locs | Use stride tricks to save data memory | ## Code Before:
import numpy as np
from scipy import sparse
from .sparselol_cy import extents_count
def extents(labels):
"""Compute the extents of every integer value in ``arr``.
Parameters
----------
labels : array of ints
The array of values to be mapped.
Returns
-------
locs : sparse.csr_matrix
A sparse matrix in which the nonzero elements of row i are the
indices of value i in ``arr``.
"""
labels = labels.ravel()
counts = np.bincount(labels)
indptr = np.concatenate([[0], np.cumsum(counts)])
indices = np.empty(labels.size, int)
extents_count(labels.ravel(), indptr.copy(), out=indices)
locs = sparse.csr_matrix((indices, indices, indptr), dtype=int)
return locs
## Instruction:
Use stride tricks to save data memory
## Code After:
import numpy as np
from scipy import sparse
from .sparselol_cy import extents_count
def extents(labels):
"""Compute the extents of every integer value in ``arr``.
Parameters
----------
labels : array of ints
The array of values to be mapped.
Returns
-------
locs : sparse.csr_matrix
A sparse matrix in which the nonzero elements of row i are the
indices of value i in ``arr``.
"""
labels = labels.ravel()
counts = np.bincount(labels)
indptr = np.concatenate([[0], np.cumsum(counts)])
indices = np.empty(labels.size, int)
extents_count(labels.ravel(), indptr.copy(), out=indices)
one = np.ones((1,), dtype=int)
data = np.lib.as_strided(one, shape=indices.shape, strides=(0,))
locs = sparse.csr_matrix((data, indices, indptr), dtype=int)
return locs |
7ebc9a4511d52707ce88a1b8bc2d3fa638e1fb91 | c2rst.py | c2rst.py | import sphinx.parsers
import docutils.parsers.rst as rst
class CStrip(sphinx.parsers.Parser):
def __init__(self):
self.rst_parser = rst.Parser()
def parse(self, inputstring, document):
stripped = []
for line in inputstring.split("\n"):
line = line.strip()
if line == "//|":
stripped.append("")
elif line.startswith("//| "):
stripped.append(line[len("//| "):])
stripped = "\r\n".join(stripped)
self.rst_parser.parse(stripped, document)
| import docutils.parsers
import docutils.parsers.rst as rst
class CStrip(docutils.parsers.Parser):
def __init__(self):
self.rst_parser = rst.Parser()
def parse(self, inputstring, document):
stripped = []
for line in inputstring.split("\n"):
line = line.strip()
if line == "//|":
stripped.append("")
elif line.startswith("//| "):
stripped.append(line[len("//| "):])
stripped = "\r\n".join(stripped)
self.rst_parser.parse(stripped, document)
| Switch away from sphinx.parsers which isn't available in sphinx 1.3.5 on Read The Docs. | Switch away from sphinx.parsers which isn't available in sphinx 1.3.5 on Read The Docs.
| Python | mit | adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/micropython,adafruit/micropython,adafruit/circuitpython,adafruit/micropython,adafruit/circuitpython,adafruit/micropython,adafruit/micropython,adafruit/circuitpython | - import sphinx.parsers
+ import docutils.parsers
import docutils.parsers.rst as rst
- class CStrip(sphinx.parsers.Parser):
+ class CStrip(docutils.parsers.Parser):
def __init__(self):
self.rst_parser = rst.Parser()
def parse(self, inputstring, document):
stripped = []
for line in inputstring.split("\n"):
line = line.strip()
if line == "//|":
stripped.append("")
elif line.startswith("//| "):
stripped.append(line[len("//| "):])
stripped = "\r\n".join(stripped)
self.rst_parser.parse(stripped, document)
| Switch away from sphinx.parsers which isn't available in sphinx 1.3.5 on Read The Docs. | ## Code Before:
import sphinx.parsers
import docutils.parsers.rst as rst
class CStrip(sphinx.parsers.Parser):
def __init__(self):
self.rst_parser = rst.Parser()
def parse(self, inputstring, document):
stripped = []
for line in inputstring.split("\n"):
line = line.strip()
if line == "//|":
stripped.append("")
elif line.startswith("//| "):
stripped.append(line[len("//| "):])
stripped = "\r\n".join(stripped)
self.rst_parser.parse(stripped, document)
## Instruction:
Switch away from sphinx.parsers which isn't available in sphinx 1.3.5 on Read The Docs.
## Code After:
import docutils.parsers
import docutils.parsers.rst as rst
class CStrip(docutils.parsers.Parser):
def __init__(self):
self.rst_parser = rst.Parser()
def parse(self, inputstring, document):
stripped = []
for line in inputstring.split("\n"):
line = line.strip()
if line == "//|":
stripped.append("")
elif line.startswith("//| "):
stripped.append(line[len("//| "):])
stripped = "\r\n".join(stripped)
self.rst_parser.parse(stripped, document)
|
e37c7cace441e837120b820936c6f4ae8de78996 | sts/controller_manager.py | sts/controller_manager.py | from sts.util.console import msg
class ControllerManager(object):
''' Encapsulate a list of controllers objects '''
def __init__(self, controllers):
self.uuid2controller = {
controller.uuid : controller
for controller in controllers
}
@property
def controllers(self):
return self.uuid2controller.values()
@property
def live_controllers(self):
alive = [controller for controller in self.controllers if controller.alive]
return set(alive)
@property
def down_controllers(self):
down = [controller for controller in self.controllers if not controller.alive]
return set(down)
def get_controller(self, uuid):
if uuid not in self.uuid2controller:
raise ValueError("unknown uuid %s" % str(uuid))
return self.uuid2controller[uuid]
def kill_all(self):
for c in self.live_controllers:
c.kill()
self.uuid2controller = {}
@staticmethod
def kill_controller(controller):
msg.event("Killing controller %s" % str(controller))
controller.kill()
@staticmethod
def reboot_controller(controller):
msg.event("Restarting controller %s" % str(controller))
controller.start()
def check_controller_processes_alive(self):
controllers_with_problems = []
for c in self.live_controllers:
(rc, msg) = c.check_process_status()
if not rc:
c.alive = False
controllers_with_problems.append ( (c, msg) )
return controllers_with_problems
| from sts.util.console import msg
class ControllerManager(object):
''' Encapsulate a list of controllers objects '''
def __init__(self, controllers):
self.uuid2controller = {
controller.uuid : controller
for controller in controllers
}
@property
def controllers(self):
cs = self.uuid2controller.values()
cs.sort(key=lambda c: c.uuid)
return cs
@property
def live_controllers(self):
alive = [controller for controller in self.controllers if controller.alive]
return set(alive)
@property
def down_controllers(self):
down = [controller for controller in self.controllers if not controller.alive]
return set(down)
def get_controller(self, uuid):
if uuid not in self.uuid2controller:
raise ValueError("unknown uuid %s" % str(uuid))
return self.uuid2controller[uuid]
def kill_all(self):
for c in self.live_controllers:
c.kill()
self.uuid2controller = {}
@staticmethod
def kill_controller(controller):
msg.event("Killing controller %s" % str(controller))
controller.kill()
@staticmethod
def reboot_controller(controller):
msg.event("Restarting controller %s" % str(controller))
controller.start()
def check_controller_processes_alive(self):
controllers_with_problems = []
live = list(self.live_controllers)
live.sort(key=lambda c: c.uuid)
for c in live:
(rc, msg) = c.check_process_status()
if not rc:
c.alive = False
controllers_with_problems.append ( (c, msg) )
return controllers_with_problems
| Make .contollers() deterministic (was using hash.values()) | Make .contollers() deterministic (was using hash.values())
| Python | apache-2.0 | ucb-sts/sts,jmiserez/sts,ucb-sts/sts,jmiserez/sts | from sts.util.console import msg
class ControllerManager(object):
''' Encapsulate a list of controllers objects '''
def __init__(self, controllers):
self.uuid2controller = {
controller.uuid : controller
for controller in controllers
}
@property
def controllers(self):
- return self.uuid2controller.values()
+ cs = self.uuid2controller.values()
+ cs.sort(key=lambda c: c.uuid)
+ return cs
@property
def live_controllers(self):
alive = [controller for controller in self.controllers if controller.alive]
return set(alive)
@property
def down_controllers(self):
down = [controller for controller in self.controllers if not controller.alive]
return set(down)
def get_controller(self, uuid):
if uuid not in self.uuid2controller:
raise ValueError("unknown uuid %s" % str(uuid))
return self.uuid2controller[uuid]
def kill_all(self):
for c in self.live_controllers:
c.kill()
self.uuid2controller = {}
@staticmethod
def kill_controller(controller):
msg.event("Killing controller %s" % str(controller))
controller.kill()
@staticmethod
def reboot_controller(controller):
msg.event("Restarting controller %s" % str(controller))
controller.start()
def check_controller_processes_alive(self):
controllers_with_problems = []
- for c in self.live_controllers:
+ live = list(self.live_controllers)
+ live.sort(key=lambda c: c.uuid)
+ for c in live:
(rc, msg) = c.check_process_status()
if not rc:
c.alive = False
controllers_with_problems.append ( (c, msg) )
return controllers_with_problems
| Make .contollers() deterministic (was using hash.values()) | ## Code Before:
from sts.util.console import msg
class ControllerManager(object):
''' Encapsulate a list of controllers objects '''
def __init__(self, controllers):
self.uuid2controller = {
controller.uuid : controller
for controller in controllers
}
@property
def controllers(self):
return self.uuid2controller.values()
@property
def live_controllers(self):
alive = [controller for controller in self.controllers if controller.alive]
return set(alive)
@property
def down_controllers(self):
down = [controller for controller in self.controllers if not controller.alive]
return set(down)
def get_controller(self, uuid):
if uuid not in self.uuid2controller:
raise ValueError("unknown uuid %s" % str(uuid))
return self.uuid2controller[uuid]
def kill_all(self):
for c in self.live_controllers:
c.kill()
self.uuid2controller = {}
@staticmethod
def kill_controller(controller):
msg.event("Killing controller %s" % str(controller))
controller.kill()
@staticmethod
def reboot_controller(controller):
msg.event("Restarting controller %s" % str(controller))
controller.start()
def check_controller_processes_alive(self):
controllers_with_problems = []
for c in self.live_controllers:
(rc, msg) = c.check_process_status()
if not rc:
c.alive = False
controllers_with_problems.append ( (c, msg) )
return controllers_with_problems
## Instruction:
Make .contollers() deterministic (was using hash.values())
## Code After:
from sts.util.console import msg
class ControllerManager(object):
''' Encapsulate a list of controllers objects '''
def __init__(self, controllers):
self.uuid2controller = {
controller.uuid : controller
for controller in controllers
}
@property
def controllers(self):
cs = self.uuid2controller.values()
cs.sort(key=lambda c: c.uuid)
return cs
@property
def live_controllers(self):
alive = [controller for controller in self.controllers if controller.alive]
return set(alive)
@property
def down_controllers(self):
down = [controller for controller in self.controllers if not controller.alive]
return set(down)
def get_controller(self, uuid):
if uuid not in self.uuid2controller:
raise ValueError("unknown uuid %s" % str(uuid))
return self.uuid2controller[uuid]
def kill_all(self):
for c in self.live_controllers:
c.kill()
self.uuid2controller = {}
@staticmethod
def kill_controller(controller):
msg.event("Killing controller %s" % str(controller))
controller.kill()
@staticmethod
def reboot_controller(controller):
msg.event("Restarting controller %s" % str(controller))
controller.start()
def check_controller_processes_alive(self):
controllers_with_problems = []
live = list(self.live_controllers)
live.sort(key=lambda c: c.uuid)
for c in live:
(rc, msg) = c.check_process_status()
if not rc:
c.alive = False
controllers_with_problems.append ( (c, msg) )
return controllers_with_problems
|
34b57742801f888af7597378bd00f9d06c2d3b66 | packages/Python/lldbsuite/test/repl/quicklookobject/TestREPLQuickLookObject.py | packages/Python/lldbsuite/test/repl/quicklookobject/TestREPLQuickLookObject.py | """Test that QuickLookObject works correctly in the REPL"""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.lldbtest as lldbtest
class REPLQuickLookTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
self.command('true.customPlaygroundQuickLook()', patterns=['Logical = true'])
self.command('1.25.customPlaygroundQuickLook()', patterns=['Double = 1.25'])
self.command('Float(1.25).customPlaygroundQuickLook()', patterns=['Float = 1.25'])
self.command('"Hello".customPlaygroundQuickLook()', patterns=['Text = \"Hello\"'])
| """Test that QuickLookObject works correctly in the REPL"""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.lldbtest as lldbtest
class REPLQuickLookTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
self.command('PlaygroundQuickLook(reflecting: true)', patterns=['Logical = true'])
self.command('PlaygroundQuickLook(reflecting: 1.25)', patterns=['Double = 1.25'])
self.command('PlaygroundQuickLook(reflecting: Float(1.25))', patterns=['Float = 1.25'])
self.command('PlaygroundQuickLook(reflecting: "Hello")', patterns=['Text = \"Hello\"'])
| Use the PlaygroundQuickLook(reflecting:) constructor in this test case | Use the PlaygroundQuickLook(reflecting:) constructor in this test case
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb | """Test that QuickLookObject works correctly in the REPL"""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.lldbtest as lldbtest
class REPLQuickLookTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
- self.command('true.customPlaygroundQuickLook()', patterns=['Logical = true'])
+ self.command('PlaygroundQuickLook(reflecting: true)', patterns=['Logical = true'])
- self.command('1.25.customPlaygroundQuickLook()', patterns=['Double = 1.25'])
+ self.command('PlaygroundQuickLook(reflecting: 1.25)', patterns=['Double = 1.25'])
- self.command('Float(1.25).customPlaygroundQuickLook()', patterns=['Float = 1.25'])
+ self.command('PlaygroundQuickLook(reflecting: Float(1.25))', patterns=['Float = 1.25'])
- self.command('"Hello".customPlaygroundQuickLook()', patterns=['Text = \"Hello\"'])
+ self.command('PlaygroundQuickLook(reflecting: "Hello")', patterns=['Text = \"Hello\"'])
-
- | Use the PlaygroundQuickLook(reflecting:) constructor in this test case | ## Code Before:
"""Test that QuickLookObject works correctly in the REPL"""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.lldbtest as lldbtest
class REPLQuickLookTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
self.command('true.customPlaygroundQuickLook()', patterns=['Logical = true'])
self.command('1.25.customPlaygroundQuickLook()', patterns=['Double = 1.25'])
self.command('Float(1.25).customPlaygroundQuickLook()', patterns=['Float = 1.25'])
self.command('"Hello".customPlaygroundQuickLook()', patterns=['Text = \"Hello\"'])
## Instruction:
Use the PlaygroundQuickLook(reflecting:) constructor in this test case
## Code After:
"""Test that QuickLookObject works correctly in the REPL"""
import os, time
import unittest2
import lldb
from lldbsuite.test.lldbrepl import REPLTest, load_tests
import lldbsuite.test.lldbtest as lldbtest
class REPLQuickLookTestCase (REPLTest):
mydir = REPLTest.compute_mydir(__file__)
def doTest(self):
self.command('PlaygroundQuickLook(reflecting: true)', patterns=['Logical = true'])
self.command('PlaygroundQuickLook(reflecting: 1.25)', patterns=['Double = 1.25'])
self.command('PlaygroundQuickLook(reflecting: Float(1.25))', patterns=['Float = 1.25'])
self.command('PlaygroundQuickLook(reflecting: "Hello")', patterns=['Text = \"Hello\"'])
|
723f59d43cce9d7a09386447389e8df33b5d323e | tests/base/base.py | tests/base/base.py | import steel
import unittest
class NameAwareOrderedDictTests(unittest.TestCase):
def setUp(self):
self.d = steel.NameAwareOrderedDict()
def test_ignore_object(self):
# Objects without a set_name() method should be ignored
self.d['example'] = object()
self.assertFalse(hasattr(self.d['example'], 'name'))
def test_auto_name(self):
# Objects with a set_name() method should be told their name
class NamedObject(object):
def set_name(self, name):
self.name = name
self.d['example'] = NamedObject()
self.assertEqual(self.d['example'].name, 'example')
def test_errors(self):
# Make sure set_name() errors are raised, not swallowed
class ErrorObject(object):
"Just a simple object that errors out while setting its name"
def set_name(self, name):
raise TypeError('Something went wrong')
with self.assertRaises(TypeError):
self.d['example'] = ErrorObject()
| import steel
import unittest
class NameAwareOrderedDictTests(unittest.TestCase):
def setUp(self):
self.d = steel.NameAwareOrderedDict()
def test_ignore_object(self):
# Objects without a set_name() method should be ignored
self.d['example'] = object()
self.assertFalse(hasattr(self.d['example'], 'name'))
def test_auto_name(self):
# Objects with a set_name() method should be told their name
class NamedObject(object):
def set_name(self, name):
self.name = name
self.d['example'] = NamedObject()
self.assertEqual(self.d['example'].name, 'example')
def test_errors(self):
# Make sure set_name() errors are raised, not swallowed
class ErrorObject(object):
"Just a simple object that errors out while setting its name"
def set_name(self, name):
raise TypeError('Something went wrong')
with self.assertRaises(TypeError):
self.d['example'] = ErrorObject()
class SizeTests(unittest.TestCase):
def test_explicit_sizes(self):
class Test(steel.Structure):
field1 = steel.Bytes(size=2)
field2 = steel.Bytes(size=4)
self.assertEqual(Test.size, 6)
| Add a simple test for calculating the size of a structure | Add a simple test for calculating the size of a structure
| Python | bsd-3-clause | gulopine/steel-experiment | import steel
import unittest
class NameAwareOrderedDictTests(unittest.TestCase):
def setUp(self):
self.d = steel.NameAwareOrderedDict()
def test_ignore_object(self):
# Objects without a set_name() method should be ignored
self.d['example'] = object()
self.assertFalse(hasattr(self.d['example'], 'name'))
def test_auto_name(self):
# Objects with a set_name() method should be told their name
class NamedObject(object):
def set_name(self, name):
self.name = name
self.d['example'] = NamedObject()
self.assertEqual(self.d['example'].name, 'example')
def test_errors(self):
# Make sure set_name() errors are raised, not swallowed
class ErrorObject(object):
"Just a simple object that errors out while setting its name"
def set_name(self, name):
raise TypeError('Something went wrong')
with self.assertRaises(TypeError):
self.d['example'] = ErrorObject()
+
+ class SizeTests(unittest.TestCase):
+ def test_explicit_sizes(self):
+ class Test(steel.Structure):
+ field1 = steel.Bytes(size=2)
+ field2 = steel.Bytes(size=4)
+
+ self.assertEqual(Test.size, 6)
+ | Add a simple test for calculating the size of a structure | ## Code Before:
import steel
import unittest
class NameAwareOrderedDictTests(unittest.TestCase):
def setUp(self):
self.d = steel.NameAwareOrderedDict()
def test_ignore_object(self):
# Objects without a set_name() method should be ignored
self.d['example'] = object()
self.assertFalse(hasattr(self.d['example'], 'name'))
def test_auto_name(self):
# Objects with a set_name() method should be told their name
class NamedObject(object):
def set_name(self, name):
self.name = name
self.d['example'] = NamedObject()
self.assertEqual(self.d['example'].name, 'example')
def test_errors(self):
# Make sure set_name() errors are raised, not swallowed
class ErrorObject(object):
"Just a simple object that errors out while setting its name"
def set_name(self, name):
raise TypeError('Something went wrong')
with self.assertRaises(TypeError):
self.d['example'] = ErrorObject()
## Instruction:
Add a simple test for calculating the size of a structure
## Code After:
import steel
import unittest
class NameAwareOrderedDictTests(unittest.TestCase):
def setUp(self):
self.d = steel.NameAwareOrderedDict()
def test_ignore_object(self):
# Objects without a set_name() method should be ignored
self.d['example'] = object()
self.assertFalse(hasattr(self.d['example'], 'name'))
def test_auto_name(self):
# Objects with a set_name() method should be told their name
class NamedObject(object):
def set_name(self, name):
self.name = name
self.d['example'] = NamedObject()
self.assertEqual(self.d['example'].name, 'example')
def test_errors(self):
# Make sure set_name() errors are raised, not swallowed
class ErrorObject(object):
"Just a simple object that errors out while setting its name"
def set_name(self, name):
raise TypeError('Something went wrong')
with self.assertRaises(TypeError):
self.d['example'] = ErrorObject()
class SizeTests(unittest.TestCase):
def test_explicit_sizes(self):
class Test(steel.Structure):
field1 = steel.Bytes(size=2)
field2 = steel.Bytes(size=4)
self.assertEqual(Test.size, 6)
|
82b7e46ebdeb154963520fec1d41cc624ceb806d | tests/test_vendcrawler.py | tests/test_vendcrawler.py | import unittest
from vendcrawler.scripts.vendcrawler import VendCrawler
class TestVendCrawlerMethods(unittest.TestCase):
def test_get_links(self):
links = VendCrawler().get_links(2)
self.assertEqual(links,
['https://sarahserver.net/?module=vendor&p=1',
'https://sarahserver.net/?module=vendor&p=2'])
def test_get_page_count(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
page_count = VendCrawler().get_page_count(str(data))
self.assertEqual(int(page_count), 84)
if __name__ == '__main__':
unittest.main()
| import unittest
from vendcrawler.scripts.vendcrawler import VendCrawler
class TestVendCrawlerMethods(unittest.TestCase):
def test_get_links(self):
links = VendCrawler('a', 'b', 'c').get_links(2)
self.assertEqual(links,
['https://sarahserver.net/?module=vendor&p=1',
'https://sarahserver.net/?module=vendor&p=2'])
def test_get_page_count(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
page_count = VendCrawler('a', 'b', 'c').get_page_count(str(data))
self.assertEqual(int(page_count), 84)
if __name__ == '__main__':
unittest.main()
| Fix test by passing placeholder variables. | Fix test by passing placeholder variables.
| Python | mit | josetaas/vendcrawler,josetaas/vendcrawler,josetaas/vendcrawler | import unittest
from vendcrawler.scripts.vendcrawler import VendCrawler
class TestVendCrawlerMethods(unittest.TestCase):
def test_get_links(self):
- links = VendCrawler().get_links(2)
+ links = VendCrawler('a', 'b', 'c').get_links(2)
self.assertEqual(links,
['https://sarahserver.net/?module=vendor&p=1',
'https://sarahserver.net/?module=vendor&p=2'])
def test_get_page_count(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
- page_count = VendCrawler().get_page_count(str(data))
+ page_count = VendCrawler('a', 'b', 'c').get_page_count(str(data))
self.assertEqual(int(page_count), 84)
if __name__ == '__main__':
unittest.main()
| Fix test by passing placeholder variables. | ## Code Before:
import unittest
from vendcrawler.scripts.vendcrawler import VendCrawler
class TestVendCrawlerMethods(unittest.TestCase):
def test_get_links(self):
links = VendCrawler().get_links(2)
self.assertEqual(links,
['https://sarahserver.net/?module=vendor&p=1',
'https://sarahserver.net/?module=vendor&p=2'])
def test_get_page_count(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
page_count = VendCrawler().get_page_count(str(data))
self.assertEqual(int(page_count), 84)
if __name__ == '__main__':
unittest.main()
## Instruction:
Fix test by passing placeholder variables.
## Code After:
import unittest
from vendcrawler.scripts.vendcrawler import VendCrawler
class TestVendCrawlerMethods(unittest.TestCase):
def test_get_links(self):
links = VendCrawler('a', 'b', 'c').get_links(2)
self.assertEqual(links,
['https://sarahserver.net/?module=vendor&p=1',
'https://sarahserver.net/?module=vendor&p=2'])
def test_get_page_count(self):
with open('test_vendcrawler.html', 'r') as f:
data = f.read()
page_count = VendCrawler('a', 'b', 'c').get_page_count(str(data))
self.assertEqual(int(page_count), 84)
if __name__ == '__main__':
unittest.main()
|
8ce1def3020570c8a3e370261fc9c7f027202bdf | owapi/util.py | owapi/util.py | import json
from kyokai import Request
from kyokai.context import HTTPRequestContext
def jsonify(func):
"""
JSON-ify the response from a function.
"""
async def res(ctx: HTTPRequestContext):
result = await func(ctx)
assert isinstance(ctx.request, Request)
if isinstance(result, tuple):
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result[0]}
if len(result) == 1:
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
elif len(result) == 2:
return json.dumps(new_result[0]), result[1], {"Content-Type": "application/json"}
else:
return json.dumps(new_result), result[1], {**{"Content-Type": "application/json"}, **result[2]}
else:
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result}
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
return res
| import json
import aioredis
from kyokai import Request
from kyokai.context import HTTPRequestContext
async def with_cache(ctx: HTTPRequestContext, func, *args, expires=300):
"""
Run a coroutine with cache.
Stores the result in redis.
"""
assert isinstance(ctx.redis, aioredis.Redis)
built = func.__name__ + repr(args)
# Check for the key.
# Uses a simple func name + repr(args) as the key to use.
got = await ctx.redis.get(built)
if got:
return got.decode()
# Call the function.
result = await func(ctx, *args)
# Store the result as cached.
await ctx.redis.set(built, result, expire=expires)
return result
def jsonify(func):
"""
JSON-ify the response from a function.
"""
async def res(ctx: HTTPRequestContext):
result = await func(ctx)
assert isinstance(ctx.request, Request)
if isinstance(result, tuple):
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result[0]}
if len(result) == 1:
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
elif len(result) == 2:
return json.dumps(new_result[0]), result[1], {"Content-Type": "application/json"}
else:
return json.dumps(new_result), result[1], {**{"Content-Type": "application/json"}, **result[2]}
else:
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result}
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
return res
| Add with_cache function for storing cached data | Add with_cache function for storing cached data
| Python | mit | azah/OWAPI,SunDwarf/OWAPI | import json
+ import aioredis
from kyokai import Request
from kyokai.context import HTTPRequestContext
+
+
+ async def with_cache(ctx: HTTPRequestContext, func, *args, expires=300):
+ """
+ Run a coroutine with cache.
+
+ Stores the result in redis.
+ """
+ assert isinstance(ctx.redis, aioredis.Redis)
+ built = func.__name__ + repr(args)
+ # Check for the key.
+ # Uses a simple func name + repr(args) as the key to use.
+ got = await ctx.redis.get(built)
+ if got:
+ return got.decode()
+
+ # Call the function.
+ result = await func(ctx, *args)
+
+ # Store the result as cached.
+ await ctx.redis.set(built, result, expire=expires)
+ return result
def jsonify(func):
"""
JSON-ify the response from a function.
"""
async def res(ctx: HTTPRequestContext):
result = await func(ctx)
assert isinstance(ctx.request, Request)
if isinstance(result, tuple):
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result[0]}
if len(result) == 1:
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
elif len(result) == 2:
return json.dumps(new_result[0]), result[1], {"Content-Type": "application/json"}
else:
return json.dumps(new_result), result[1], {**{"Content-Type": "application/json"}, **result[2]}
else:
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result}
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
return res
| Add with_cache function for storing cached data | ## Code Before:
import json
from kyokai import Request
from kyokai.context import HTTPRequestContext
def jsonify(func):
"""
JSON-ify the response from a function.
"""
async def res(ctx: HTTPRequestContext):
result = await func(ctx)
assert isinstance(ctx.request, Request)
if isinstance(result, tuple):
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result[0]}
if len(result) == 1:
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
elif len(result) == 2:
return json.dumps(new_result[0]), result[1], {"Content-Type": "application/json"}
else:
return json.dumps(new_result), result[1], {**{"Content-Type": "application/json"}, **result[2]}
else:
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result}
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
return res
## Instruction:
Add with_cache function for storing cached data
## Code After:
import json
import aioredis
from kyokai import Request
from kyokai.context import HTTPRequestContext
async def with_cache(ctx: HTTPRequestContext, func, *args, expires=300):
"""
Run a coroutine with cache.
Stores the result in redis.
"""
assert isinstance(ctx.redis, aioredis.Redis)
built = func.__name__ + repr(args)
# Check for the key.
# Uses a simple func name + repr(args) as the key to use.
got = await ctx.redis.get(built)
if got:
return got.decode()
# Call the function.
result = await func(ctx, *args)
# Store the result as cached.
await ctx.redis.set(built, result, expire=expires)
return result
def jsonify(func):
"""
JSON-ify the response from a function.
"""
async def res(ctx: HTTPRequestContext):
result = await func(ctx)
assert isinstance(ctx.request, Request)
if isinstance(result, tuple):
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result[0]}
if len(result) == 1:
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
elif len(result) == 2:
return json.dumps(new_result[0]), result[1], {"Content-Type": "application/json"}
else:
return json.dumps(new_result), result[1], {**{"Content-Type": "application/json"}, **result[2]}
else:
new_result = {**{"_request": {"route": ctx.request.path, "api_ver": 1}},
**result}
return json.dumps(new_result), 200, {"Content-Type": "application/json"}
return res
|
106ea580471387a3645877f52018ff2880db34f3 | live_studio/config/forms.py | live_studio/config/forms.py | from django import forms
from .models import Config
class ConfigForm(forms.ModelForm):
class Meta:
model = Config
exclude = ('created', 'user')
PAGES = (
('base',),
('distribution',),
('media_type',),
('architecture',),
('installer',),
('locale', 'keyboard_layout'),
)
WIZARD_FORMS = []
for fields in PAGES:
meta = type('Meta', (), {
'model': Config,
'fields': fields,
})
WIZARD_FORMS.append(type('', (forms.ModelForm,), {'Meta': meta}))
| from django import forms
from .models import Config
class ConfigForm(forms.ModelForm):
class Meta:
model = Config
exclude = ('created', 'user')
PAGES = (
('base',),
('distribution',),
('media_type',),
('architecture',),
('installer',),
('locale', 'keyboard_layout'),
)
WIZARD_FORMS = []
for fields in PAGES:
meta = type('Meta', (), {
'model': Config,
'fields': fields,
'widgets': {
'base': forms.RadioSelect(),
'distribution': forms.RadioSelect(),
'media_type': forms.RadioSelect(),
'architecture': forms.RadioSelect(),
'installer': forms.RadioSelect(),
},
})
WIZARD_FORMS.append(type('', (forms.ModelForm,), {'Meta': meta}))
| Use radio buttons for most of the interface. | Use radio buttons for most of the interface.
Signed-off-by: Chris Lamb <29e6d179a8d73471df7861382db6dd7e64138033@debian.org>
| Python | agpl-3.0 | lamby/live-studio,lamby/live-studio,lamby/live-studio,debian-live/live-studio,debian-live/live-studio,debian-live/live-studio | from django import forms
from .models import Config
class ConfigForm(forms.ModelForm):
class Meta:
model = Config
exclude = ('created', 'user')
PAGES = (
('base',),
('distribution',),
('media_type',),
('architecture',),
('installer',),
('locale', 'keyboard_layout'),
)
WIZARD_FORMS = []
for fields in PAGES:
meta = type('Meta', (), {
'model': Config,
'fields': fields,
+ 'widgets': {
+ 'base': forms.RadioSelect(),
+ 'distribution': forms.RadioSelect(),
+ 'media_type': forms.RadioSelect(),
+ 'architecture': forms.RadioSelect(),
+ 'installer': forms.RadioSelect(),
+ },
})
WIZARD_FORMS.append(type('', (forms.ModelForm,), {'Meta': meta}))
| Use radio buttons for most of the interface. | ## Code Before:
from django import forms
from .models import Config
class ConfigForm(forms.ModelForm):
class Meta:
model = Config
exclude = ('created', 'user')
PAGES = (
('base',),
('distribution',),
('media_type',),
('architecture',),
('installer',),
('locale', 'keyboard_layout'),
)
WIZARD_FORMS = []
for fields in PAGES:
meta = type('Meta', (), {
'model': Config,
'fields': fields,
})
WIZARD_FORMS.append(type('', (forms.ModelForm,), {'Meta': meta}))
## Instruction:
Use radio buttons for most of the interface.
## Code After:
from django import forms
from .models import Config
class ConfigForm(forms.ModelForm):
class Meta:
model = Config
exclude = ('created', 'user')
PAGES = (
('base',),
('distribution',),
('media_type',),
('architecture',),
('installer',),
('locale', 'keyboard_layout'),
)
WIZARD_FORMS = []
for fields in PAGES:
meta = type('Meta', (), {
'model': Config,
'fields': fields,
'widgets': {
'base': forms.RadioSelect(),
'distribution': forms.RadioSelect(),
'media_type': forms.RadioSelect(),
'architecture': forms.RadioSelect(),
'installer': forms.RadioSelect(),
},
})
WIZARD_FORMS.append(type('', (forms.ModelForm,), {'Meta': meta}))
|