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 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
84f913d928d28bc193d21eb223e7815f69c53a22
|
plugins/jira.py
|
plugins/jira.py
|
from neb.engine import Plugin, Command
import requests
class JiraPlugin(Plugin):
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on Matrix JIRA.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
return self._body("Boo")
def sync(self, matrix, initial_sync):
pass
|
from neb.engine import Plugin, Command, KeyValueStore
import json
import requests
class JiraPlugin(Plugin):
def __init__(self, config="jira.json"):
self.store = KeyValueStore(config)
if not self.store.has("url"):
url = raw_input("JIRA URL: ").strip()
self.store.set("url", url)
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
if len(args) == 1:
return self._body("Perform commands on a JIRA platform.")
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
url = self._url("/rest/api/2/serverInfo")
response = json.loads(requests.get(url).text)
info = "%s : version %s : build %s" % (response["serverTitle"],
response["version"], response["buildNumber"])
return self._body(info)
def sync(self, matrix, initial_sync):
pass
def _url(self, path):
return self.store.get("url") + path
|
Make the plugin request server info from JIRA.
|
Make the plugin request server info from JIRA.
|
Python
|
apache-2.0
|
Kegsay/Matrix-NEB,matrix-org/Matrix-NEB,illicitonion/Matrix-NEB
|
- from neb.engine import Plugin, Command
+ from neb.engine import Plugin, Command, KeyValueStore
+ import json
import requests
+
class JiraPlugin(Plugin):
+ def __init__(self, config="jira.json"):
+ self.store = KeyValueStore(config)
+
+ if not self.store.has("url"):
+ url = raw_input("JIRA URL: ").strip()
+ self.store.set("url", url)
+
def get_commands(self):
"""Return human readable commands with descriptions.
-
+
Returns:
list[Command]
"""
return [
- Command("jira", self.jira, "Perform commands on Matrix JIRA.", [
+ Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
]),
]
-
+
def jira(self, event, args):
+ if len(args) == 1:
+ return self._body("Perform commands on a JIRA platform.")
+
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
-
+
def _server_info(self, event, args):
+ url = self._url("/rest/api/2/serverInfo")
+ response = json.loads(requests.get(url).text)
+
+ info = "%s : version %s : build %s" % (response["serverTitle"],
+ response["version"], response["buildNumber"])
+
- return self._body("Boo")
+ return self._body(info)
-
+
def sync(self, matrix, initial_sync):
pass
-
-
+ def _url(self, path):
+ return self.store.get("url") + path
+
+
+
|
Make the plugin request server info from JIRA.
|
## Code Before:
from neb.engine import Plugin, Command
import requests
class JiraPlugin(Plugin):
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on Matrix JIRA.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
return self._body("Boo")
def sync(self, matrix, initial_sync):
pass
## Instruction:
Make the plugin request server info from JIRA.
## Code After:
from neb.engine import Plugin, Command, KeyValueStore
import json
import requests
class JiraPlugin(Plugin):
def __init__(self, config="jira.json"):
self.store = KeyValueStore(config)
if not self.store.has("url"):
url = raw_input("JIRA URL: ").strip()
self.store.set("url", url)
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
]),
]
def jira(self, event, args):
if len(args) == 1:
return self._body("Perform commands on a JIRA platform.")
action = args[1]
actions = {
"server-info": self._server_info
}
return actions[action](event, args)
def _server_info(self, event, args):
url = self._url("/rest/api/2/serverInfo")
response = json.loads(requests.get(url).text)
info = "%s : version %s : build %s" % (response["serverTitle"],
response["version"], response["buildNumber"])
return self._body(info)
def sync(self, matrix, initial_sync):
pass
def _url(self, path):
return self.store.get("url") + path
|
# ... existing code ...
from neb.engine import Plugin, Command, KeyValueStore
import json
import requests
# ... modified code ...
def __init__(self, config="jira.json"):
self.store = KeyValueStore(config)
if not self.store.has("url"):
url = raw_input("JIRA URL: ").strip()
self.store.set("url", url)
def get_commands(self):
...
"""Return human readable commands with descriptions.
Returns:
...
return [
Command("jira", self.jira, "Perform commands on a JIRA platform.", [
"server-info - Retrieve server information."
...
]
def jira(self, event, args):
if len(args) == 1:
return self._body("Perform commands on a JIRA platform.")
action = args[1]
...
return actions[action](event, args)
def _server_info(self, event, args):
url = self._url("/rest/api/2/serverInfo")
response = json.loads(requests.get(url).text)
info = "%s : version %s : build %s" % (response["serverTitle"],
response["version"], response["buildNumber"])
return self._body(info)
def sync(self, matrix, initial_sync):
...
pass
def _url(self, path):
return self.store.get("url") + path
# ... rest of the code ...
|
6e67e2882c71e291dc1f161ffc7638f42c86ddbc
|
dmdlib/randpatterns/ephys_comms.py
|
dmdlib/randpatterns/ephys_comms.py
|
import zmq
def send_message(msg, hostname='localhost', port=5556):
"""
sends a message to openephys ZMQ socket.
:param msg: string
:param hostname: ip address to send to
:param port: zmq port number
:return: none
"""
with zmq.Context() as ctx:
with ctx.socket(zmq.REQ) as sock:
sock.connect('tcp://{}:{}'.format(hostname, port))
sock.send_string(msg)
_ = sock.recv_string()
return
|
import zmq
TIMEOUT_MS = 250 # time to wait for ZMQ socket to respond before error.
HOSTNAME = 'localhost'
PORT = 5556
_ctx = zmq.Context() # should be only one made per process.
def send_message(msg, hostname=HOSTNAME, port=PORT):
"""
sends a message to openephys ZMQ socket.
Raises OpenEphysError if port is unresponsive.
:param msg: string
:param hostname: ip address to send to
:param port: zmq port number
:return: none
"""
failed = False
with _ctx.socket(zmq.REQ) as sock:
sock.connect('tcp://{}:{}'.format(hostname, port))
sock.send_string(msg, zmq.NOBLOCK)
evs = sock.poll(TIMEOUT_MS) # wait for host process to respond.
# Poll returns 0 after timeout if no events detected. This means that openephys is broken, so error:
if evs < 1:
failed = True
else:
sock.recv_string()
if failed: # raise out of context (after socket is closed...)
raise OpenEphysError('Cannot connect to OpenEphys.')
def record_start(uuid, filepath, hostname=HOSTNAME, port=PORT):
"""
Convenience function for sending data about the start of a recording to OpenEphys
:param uuid:
:param filepath:
:param hostname:
:param port:
:return:
"""
msg = 'Pattern file saved at: {}.'.format(filepath)
send_message(msg, hostname, port)
msg2 = 'Pattern file uuid: {}.'.format(uuid)
send_message(msg2, hostname, port)
def record_presentation(name, hostname=HOSTNAME, port=PORT):
"""
Convenience function for sending data about start of a presentation epoch.
:param name: name of the epoch (ie AAA, AAB, etc).
:param hostname: default 'localhost'
:param port: default 5556
"""
msg = 'Starting presentation {}'.format(name)
send_message(msg, hostname, port)
class OpenEphysError(Exception):
pass
|
Fix zmq communications module Does not hang when connection is unavailable
|
Fix zmq communications module
Does not hang when connection is unavailable
|
Python
|
mit
|
olfa-lab/DmdLib
|
import zmq
+ TIMEOUT_MS = 250 # time to wait for ZMQ socket to respond before error.
+ HOSTNAME = 'localhost'
+ PORT = 5556
- def send_message(msg, hostname='localhost', port=5556):
+ _ctx = zmq.Context() # should be only one made per process.
+
+
+ def send_message(msg, hostname=HOSTNAME, port=PORT):
"""
sends a message to openephys ZMQ socket.
+
+ Raises OpenEphysError if port is unresponsive.
+
:param msg: string
:param hostname: ip address to send to
:param port: zmq port number
:return: none
"""
- with zmq.Context() as ctx:
+
+ failed = False
- with ctx.socket(zmq.REQ) as sock:
+ with _ctx.socket(zmq.REQ) as sock:
- sock.connect('tcp://{}:{}'.format(hostname, port))
+ sock.connect('tcp://{}:{}'.format(hostname, port))
- sock.send_string(msg)
+ sock.send_string(msg, zmq.NOBLOCK)
+ evs = sock.poll(TIMEOUT_MS) # wait for host process to respond.
+
+ # Poll returns 0 after timeout if no events detected. This means that openephys is broken, so error:
+ if evs < 1:
+ failed = True
+ else:
- _ = sock.recv_string()
+ sock.recv_string()
+ if failed: # raise out of context (after socket is closed...)
+ raise OpenEphysError('Cannot connect to OpenEphys.')
+
+ def record_start(uuid, filepath, hostname=HOSTNAME, port=PORT):
+ """
+ Convenience function for sending data about the start of a recording to OpenEphys
+ :param uuid:
+ :param filepath:
+ :param hostname:
+ :param port:
- return
+ :return:
+ """
+ msg = 'Pattern file saved at: {}.'.format(filepath)
+ send_message(msg, hostname, port)
+ msg2 = 'Pattern file uuid: {}.'.format(uuid)
+ send_message(msg2, hostname, port)
+ def record_presentation(name, hostname=HOSTNAME, port=PORT):
+ """
+ Convenience function for sending data about start of a presentation epoch.
+
+ :param name: name of the epoch (ie AAA, AAB, etc).
+ :param hostname: default 'localhost'
+ :param port: default 5556
+ """
+ msg = 'Starting presentation {}'.format(name)
+ send_message(msg, hostname, port)
+
+
+ class OpenEphysError(Exception):
+ pass
+
|
Fix zmq communications module Does not hang when connection is unavailable
|
## Code Before:
import zmq
def send_message(msg, hostname='localhost', port=5556):
"""
sends a message to openephys ZMQ socket.
:param msg: string
:param hostname: ip address to send to
:param port: zmq port number
:return: none
"""
with zmq.Context() as ctx:
with ctx.socket(zmq.REQ) as sock:
sock.connect('tcp://{}:{}'.format(hostname, port))
sock.send_string(msg)
_ = sock.recv_string()
return
## Instruction:
Fix zmq communications module Does not hang when connection is unavailable
## Code After:
import zmq
TIMEOUT_MS = 250 # time to wait for ZMQ socket to respond before error.
HOSTNAME = 'localhost'
PORT = 5556
_ctx = zmq.Context() # should be only one made per process.
def send_message(msg, hostname=HOSTNAME, port=PORT):
"""
sends a message to openephys ZMQ socket.
Raises OpenEphysError if port is unresponsive.
:param msg: string
:param hostname: ip address to send to
:param port: zmq port number
:return: none
"""
failed = False
with _ctx.socket(zmq.REQ) as sock:
sock.connect('tcp://{}:{}'.format(hostname, port))
sock.send_string(msg, zmq.NOBLOCK)
evs = sock.poll(TIMEOUT_MS) # wait for host process to respond.
# Poll returns 0 after timeout if no events detected. This means that openephys is broken, so error:
if evs < 1:
failed = True
else:
sock.recv_string()
if failed: # raise out of context (after socket is closed...)
raise OpenEphysError('Cannot connect to OpenEphys.')
def record_start(uuid, filepath, hostname=HOSTNAME, port=PORT):
"""
Convenience function for sending data about the start of a recording to OpenEphys
:param uuid:
:param filepath:
:param hostname:
:param port:
:return:
"""
msg = 'Pattern file saved at: {}.'.format(filepath)
send_message(msg, hostname, port)
msg2 = 'Pattern file uuid: {}.'.format(uuid)
send_message(msg2, hostname, port)
def record_presentation(name, hostname=HOSTNAME, port=PORT):
"""
Convenience function for sending data about start of a presentation epoch.
:param name: name of the epoch (ie AAA, AAB, etc).
:param hostname: default 'localhost'
:param port: default 5556
"""
msg = 'Starting presentation {}'.format(name)
send_message(msg, hostname, port)
class OpenEphysError(Exception):
pass
|
// ... existing code ...
TIMEOUT_MS = 250 # time to wait for ZMQ socket to respond before error.
HOSTNAME = 'localhost'
PORT = 5556
_ctx = zmq.Context() # should be only one made per process.
def send_message(msg, hostname=HOSTNAME, port=PORT):
"""
// ... modified code ...
sends a message to openephys ZMQ socket.
Raises OpenEphysError if port is unresponsive.
:param msg: string
...
"""
failed = False
with _ctx.socket(zmq.REQ) as sock:
sock.connect('tcp://{}:{}'.format(hostname, port))
sock.send_string(msg, zmq.NOBLOCK)
evs = sock.poll(TIMEOUT_MS) # wait for host process to respond.
# Poll returns 0 after timeout if no events detected. This means that openephys is broken, so error:
if evs < 1:
failed = True
else:
sock.recv_string()
if failed: # raise out of context (after socket is closed...)
raise OpenEphysError('Cannot connect to OpenEphys.')
def record_start(uuid, filepath, hostname=HOSTNAME, port=PORT):
"""
Convenience function for sending data about the start of a recording to OpenEphys
:param uuid:
:param filepath:
:param hostname:
:param port:
:return:
"""
msg = 'Pattern file saved at: {}.'.format(filepath)
send_message(msg, hostname, port)
msg2 = 'Pattern file uuid: {}.'.format(uuid)
send_message(msg2, hostname, port)
def record_presentation(name, hostname=HOSTNAME, port=PORT):
"""
Convenience function for sending data about start of a presentation epoch.
:param name: name of the epoch (ie AAA, AAB, etc).
:param hostname: default 'localhost'
:param port: default 5556
"""
msg = 'Starting presentation {}'.format(name)
send_message(msg, hostname, port)
class OpenEphysError(Exception):
pass
// ... rest of the code ...
|
4d1b96792f73777adaa0a79341901ca82f57839b
|
use/functional.py
|
use/functional.py
|
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
|
import collections
import functools
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
class memoize(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
|
Add a simple memoize function
|
Add a simple memoize function
|
Python
|
mit
|
log0ymxm/corgi
|
+ import collections
+ import functools
+
+
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
+
+ class memoize(object):
+ '''Decorator. Caches a function's return value each time it is called.
+ If called later with the same arguments, the cached value is returned
+ (not reevaluated).
+ '''
+
+ def __init__(self, func):
+ self.func = func
+ self.cache = {}
+
+ def __call__(self, *args):
+ if not isinstance(args, collections.Hashable):
+ # uncacheable. a list, for instance.
+ # better to not cache than blow up.
+ return self.func(*args)
+ if args in self.cache:
+ return self.cache[args]
+ else:
+ value = self.func(*args)
+ self.cache[args] = value
+ return value
+
+ def __repr__(self):
+ '''Return the function's docstring.'''
+ return self.func.__doc__
+
+ def __get__(self, obj, objtype):
+ '''Support instance methods.'''
+ return functools.partial(self.__call__, obj)
+
|
Add a simple memoize function
|
## Code Before:
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
## Instruction:
Add a simple memoize function
## Code After:
import collections
import functools
def pipe(*functions):
def closure(x):
for fn in functions:
if not out:
out = fn(x)
else:
out = fn(out)
return out
return closure
class memoize(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
|
...
import collections
import functools
def pipe(*functions):
...
return closure
class memoize(object):
'''Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
'''
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
if not isinstance(args, collections.Hashable):
# uncacheable. a list, for instance.
# better to not cache than blow up.
return self.func(*args)
if args in self.cache:
return self.cache[args]
else:
value = self.func(*args)
self.cache[args] = value
return value
def __repr__(self):
'''Return the function's docstring.'''
return self.func.__doc__
def __get__(self, obj, objtype):
'''Support instance methods.'''
return functools.partial(self.__call__, obj)
...
|
3fa49eda98233f4cd76cf4f3b9b1fc02006fb2de
|
website/search/mutation_result.py
|
website/search/mutation_result.py
|
from models import Protein, Mutation
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self.__dict__.update(kwargs)
def __getstate__(self):
state = self.__dict__.copy()
state['protein_refseq'] = self.protein.refseq
del state['protein']
state['mutation_kwargs'] = {
'position': self.mutation.position,
'alt': self.mutation.alt
}
del state['mutation']
state['meta_user'].mutation = None
return state
def __setstate__(self, state):
state['protein'] = Protein.query.filter_by(
refseq=state['protein_refseq']
).one()
del state['protein_refseq']
state['mutation'] = Mutation.query.filter_by(
protein=state['protein'],
**state['mutation_kwargs']
).one()
del state['mutation_kwargs']
state['meta_user'].mutation = state['mutation']
state['mutation'].meta_user = state['meta_user']
self.__dict__.update(state)
|
from models import Protein, Mutation
from database import get_or_create
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self.__dict__.update(kwargs)
def __getstate__(self):
state = self.__dict__.copy()
state['protein_refseq'] = self.protein.refseq
del state['protein']
state['mutation_kwargs'] = {
'position': self.mutation.position,
'alt': self.mutation.alt
}
del state['mutation']
state['meta_user'].mutation = None
return state
def __setstate__(self, state):
state['protein'] = Protein.query.filter_by(
refseq=state['protein_refseq']
).one()
del state['protein_refseq']
state['mutation'], created = get_or_create(
Mutation,
protein=state['protein'],
**state['mutation_kwargs']
)
del state['mutation_kwargs']
state['meta_user'].mutation = state['mutation']
state['mutation'].meta_user = state['meta_user']
self.__dict__.update(state)
|
Fix result loading for novel mutations
|
Fix result loading for novel mutations
|
Python
|
lgpl-2.1
|
reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations
|
from models import Protein, Mutation
+ from database import get_or_create
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self.__dict__.update(kwargs)
def __getstate__(self):
state = self.__dict__.copy()
state['protein_refseq'] = self.protein.refseq
del state['protein']
state['mutation_kwargs'] = {
'position': self.mutation.position,
'alt': self.mutation.alt
}
del state['mutation']
state['meta_user'].mutation = None
return state
def __setstate__(self, state):
state['protein'] = Protein.query.filter_by(
refseq=state['protein_refseq']
).one()
del state['protein_refseq']
- state['mutation'] = Mutation.query.filter_by(
+ state['mutation'], created = get_or_create(
+ Mutation,
protein=state['protein'],
**state['mutation_kwargs']
- ).one()
+ )
del state['mutation_kwargs']
state['meta_user'].mutation = state['mutation']
state['mutation'].meta_user = state['meta_user']
self.__dict__.update(state)
|
Fix result loading for novel mutations
|
## Code Before:
from models import Protein, Mutation
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self.__dict__.update(kwargs)
def __getstate__(self):
state = self.__dict__.copy()
state['protein_refseq'] = self.protein.refseq
del state['protein']
state['mutation_kwargs'] = {
'position': self.mutation.position,
'alt': self.mutation.alt
}
del state['mutation']
state['meta_user'].mutation = None
return state
def __setstate__(self, state):
state['protein'] = Protein.query.filter_by(
refseq=state['protein_refseq']
).one()
del state['protein_refseq']
state['mutation'] = Mutation.query.filter_by(
protein=state['protein'],
**state['mutation_kwargs']
).one()
del state['mutation_kwargs']
state['meta_user'].mutation = state['mutation']
state['mutation'].meta_user = state['meta_user']
self.__dict__.update(state)
## Instruction:
Fix result loading for novel mutations
## Code After:
from models import Protein, Mutation
from database import get_or_create
class SearchResult:
def __init__(self, protein, mutation, is_mutation_novel, type, **kwargs):
self.protein = protein
self.mutation = mutation
self.is_mutation_novel = is_mutation_novel
self.type = type
self.meta_user = None
self.__dict__.update(kwargs)
def __getstate__(self):
state = self.__dict__.copy()
state['protein_refseq'] = self.protein.refseq
del state['protein']
state['mutation_kwargs'] = {
'position': self.mutation.position,
'alt': self.mutation.alt
}
del state['mutation']
state['meta_user'].mutation = None
return state
def __setstate__(self, state):
state['protein'] = Protein.query.filter_by(
refseq=state['protein_refseq']
).one()
del state['protein_refseq']
state['mutation'], created = get_or_create(
Mutation,
protein=state['protein'],
**state['mutation_kwargs']
)
del state['mutation_kwargs']
state['meta_user'].mutation = state['mutation']
state['mutation'].meta_user = state['meta_user']
self.__dict__.update(state)
|
# ... existing code ...
from models import Protein, Mutation
from database import get_or_create
# ... modified code ...
state['mutation'], created = get_or_create(
Mutation,
protein=state['protein'],
...
**state['mutation_kwargs']
)
del state['mutation_kwargs']
# ... rest of the code ...
|
7793f135808c1c133187f1d0a053b4f5549b58e8
|
lgogwebui.py
|
lgogwebui.py
|
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json')) as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
Correct UTF encoding of lgogdownloader json file.
|
Correct UTF encoding of lgogdownloader json file.
|
Python
|
bsd-2-clause
|
graag/lgogwebui,graag/lgogwebui,graag/lgogwebui
|
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
- with open(os.path.join(config.lgog_cache, 'gamedetails.json')) as f:
+ with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
Correct UTF encoding of lgogdownloader json file.
|
## Code Before:
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json')) as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
## Instruction:
Correct UTF encoding of lgogdownloader json file.
## Code After:
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
if data is None:
return "Unable to load the GOG games database."
for game in data['games']:
game['download'] = -1
state = session.query(Game.state).filter(Game.name == game['gamename']).one()
if state == 'queue':
game['download'] = 0
elif state == 'running':
game['download'] = 0
elif os.path.isdir(os.path.join(config.lgog_library, game['gamename'])):
game['download'] = 1
return render_template('library.html', data=data['games'])
@app.route('/download/<game>')
def download(game):
db_game = session.query(Game).filter(Game.name == game).one()
if db_game.state != 'running':
db_game.state = 'queue'
session.commit()
return redirect(url_for('library'))
|
// ... existing code ...
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data = json.load(f)
// ... rest of the code ...
|
b3413818bf651c13cef047132813fb26a185cd33
|
indra/tests/test_reading_files.py
|
indra/tests/test_reading_files.py
|
from os import path
from indra.tools.reading.read_files import read_files, get_readers
from nose.plugins.attrib import attr
@attr('slow', 'nonpublic')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
readers = get_readers()
outputs = read_files(example_files, readers)
N_out = len(outputs)
N_exp = 2*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
|
from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
reader_classes = get_reader_classes()
readers = []
for rc in reader_classes:
readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
|
Fix the reading files test.
|
Fix the reading files test.
|
Python
|
bsd-2-clause
|
johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,pvtodorov/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/belpy
|
from os import path
- from indra.tools.reading.read_files import read_files, get_readers
+ from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
+ from indra.tools.reading.readers import EmptyReader
+
- @attr('slow', 'nonpublic')
+ @attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
- readers = get_readers()
+ reader_classes = get_reader_classes()
+ readers = []
+ for rc in reader_classes:
+ readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
+ proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
- N_exp = 2*len(example_files)
+ N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
|
Fix the reading files test.
|
## Code Before:
from os import path
from indra.tools.reading.read_files import read_files, get_readers
from nose.plugins.attrib import attr
@attr('slow', 'nonpublic')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
readers = get_readers()
outputs = read_files(example_files, readers)
N_out = len(outputs)
N_exp = 2*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
## Instruction:
Fix the reading files test.
## Code After:
from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
from nose.plugins.attrib import attr
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
"Test that the system can read files."
# Create the test files.
example_files = []
# Get txt content
abstract_txt = ("This is a paper that contains the phrase: MEK "
"phosphorylates ERK.")
with open('test_abstract.txt', 'w') as f:
f.write(abstract_txt)
example_files.append('test_abstract.txt')
# Get nxml content
pmc_test_fpath = path.join(path.dirname(path.abspath(__file__)),
'pmc_cont_example.nxml')
if path.exists(pmc_test_fpath):
example_files.append(pmc_test_fpath)
assert len(example_files), "No content available to test."
# Now read them.
reader_classes = get_reader_classes()
readers = []
for rc in reader_classes:
readers.append(rc())
outputs = read_files(example_files, readers)
N_out = len(outputs)
proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
|
# ... existing code ...
from os import path
from indra.tools.reading.read_files import read_files, get_reader_classes
# ... modified code ...
from indra.tools.reading.readers import EmptyReader
@attr('slow', 'nonpublic', 'notravis')
def test_read_files():
...
# Now read them.
reader_classes = get_reader_classes()
readers = []
for rc in reader_classes:
readers.append(rc())
outputs = read_files(example_files, readers)
...
N_out = len(outputs)
proper_readers = [r for r in readers if not isinstance(r, EmptyReader)]
N_exp = len(proper_readers)*len(example_files)
assert N_out == N_exp, "Expected %d outputs, got %d." % (N_exp, N_out)
# ... rest of the code ...
|
8b5f3576ee30c1f50b3d3c5bd477b85ba4ec760e
|
plinth/modules/sso/__init__.py
|
plinth/modules/sso/__init__.py
|
from plinth import actions
from django.utils.translation import ugettext_lazy as _
version = 1
is_essential = True
depends = ['security', 'apache']
name = _('Single Sign On')
managed_packages = ['libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl', 'flite']
def setup(helper, old_version=None):
"""Install the required packages"""
helper.install(managed_packages)
actions.superuser_run('auth-pubtkt', ['enable-mod'])
actions.superuser_run('auth-pubtkt', ['create-key-pair'])
|
from plinth import actions
from django.utils.translation import ugettext_lazy as _
version = 1
is_essential = True
depends = ['security', 'apache']
name = _('Single Sign On')
managed_packages = [
'libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl', 'flite',
'ttf-bitstream-vera'
]
def setup(helper, old_version=None):
"""Install the required packages"""
helper.install(managed_packages)
actions.superuser_run('auth-pubtkt', ['enable-mod'])
actions.superuser_run('auth-pubtkt', ['create-key-pair'])
|
Make ttf-bitstream-vera a managed package
|
captcha: Make ttf-bitstream-vera a managed package
Signed-off-by: Joseph Nuthalpati <[email protected]>
Reviewed-by: James Valleroy <[email protected]>
|
Python
|
agpl-3.0
|
harry-7/Plinth,harry-7/Plinth,harry-7/Plinth,harry-7/Plinth,harry-7/Plinth
|
from plinth import actions
from django.utils.translation import ugettext_lazy as _
version = 1
is_essential = True
depends = ['security', 'apache']
name = _('Single Sign On')
+ managed_packages = [
- managed_packages = ['libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl', 'flite']
+ 'libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl', 'flite',
+ 'ttf-bitstream-vera'
+ ]
def setup(helper, old_version=None):
"""Install the required packages"""
helper.install(managed_packages)
actions.superuser_run('auth-pubtkt', ['enable-mod'])
actions.superuser_run('auth-pubtkt', ['create-key-pair'])
|
Make ttf-bitstream-vera a managed package
|
## Code Before:
from plinth import actions
from django.utils.translation import ugettext_lazy as _
version = 1
is_essential = True
depends = ['security', 'apache']
name = _('Single Sign On')
managed_packages = ['libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl', 'flite']
def setup(helper, old_version=None):
"""Install the required packages"""
helper.install(managed_packages)
actions.superuser_run('auth-pubtkt', ['enable-mod'])
actions.superuser_run('auth-pubtkt', ['create-key-pair'])
## Instruction:
Make ttf-bitstream-vera a managed package
## Code After:
from plinth import actions
from django.utils.translation import ugettext_lazy as _
version = 1
is_essential = True
depends = ['security', 'apache']
name = _('Single Sign On')
managed_packages = [
'libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl', 'flite',
'ttf-bitstream-vera'
]
def setup(helper, old_version=None):
"""Install the required packages"""
helper.install(managed_packages)
actions.superuser_run('auth-pubtkt', ['enable-mod'])
actions.superuser_run('auth-pubtkt', ['create-key-pair'])
|
...
managed_packages = [
'libapache2-mod-auth-pubtkt', 'openssl', 'python3-openssl', 'flite',
'ttf-bitstream-vera'
]
...
|
07455e5821d21c988c7c5fcda9345e99355eb4e7
|
redash/__init__.py
|
redash/__init__.py
|
import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=settings.STATIC_ASSETS_PATH,
static_path='/static')
api = Api(app)
# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
db = Database(app)
from redash.authentication import setup_authentication
auth = setup_authentication(app)
@api.representation('application/json')
def json_representation(data, code, headers=None):
resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
resp.headers.extend(headers or {})
return resp
redis_url = urlparse.urlparse(settings.REDIS_URL)
redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=0, password=redis_url.password)
from redash import data
data_manager = data.Manager(redis_connection, db)
from redash import controllers
|
import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=settings.STATIC_ASSETS_PATH,
static_path='/static')
api = Api(app)
# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
db = Database(app)
from redash.authentication import setup_authentication
auth = setup_authentication(app)
@api.representation('application/json')
def json_representation(data, code, headers=None):
resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
resp.headers.extend(headers or {})
return resp
redis_url = urlparse.urlparse(settings.REDIS_URL)
if redis_url.path:
redis_db = redis_url.path[1]
else:
redis_db = 0
redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_url.password)
from redash import data
data_manager = data.Manager(redis_connection, db)
from redash import controllers
|
Use database number from redis url if available.
|
Use database number from redis url if available.
|
Python
|
bsd-2-clause
|
chriszs/redash,imsally/redash,44px/redash,guaguadev/redash,denisov-vlad/redash,rockwotj/redash,44px/redash,rockwotj/redash,getredash/redash,ninneko/redash,akariv/redash,amino-data/redash,akariv/redash,imsally/redash,EverlyWell/redash,getredash/redash,easytaxibr/redash,M32Media/redash,vishesh92/redash,ninneko/redash,getredash/redash,easytaxibr/redash,crowdworks/redash,hudl/redash,ninneko/redash,denisov-vlad/redash,stefanseifert/redash,amino-data/redash,useabode/redash,guaguadev/redash,jmvasquez/redashtest,alexanderlz/redash,moritz9/redash,pubnative/redash,denisov-vlad/redash,imsally/redash,rockwotj/redash,pubnative/redash,vishesh92/redash,useabode/redash,crowdworks/redash,akariv/redash,44px/redash,easytaxibr/redash,getredash/redash,chriszs/redash,akariv/redash,guaguadev/redash,44px/redash,stefanseifert/redash,denisov-vlad/redash,amino-data/redash,moritz9/redash,M32Media/redash,crowdworks/redash,M32Media/redash,M32Media/redash,alexanderlz/redash,crowdworks/redash,jmvasquez/redashtest,stefanseifert/redash,denisov-vlad/redash,pubnative/redash,EverlyWell/redash,moritz9/redash,stefanseifert/redash,stefanseifert/redash,pubnative/redash,imsally/redash,EverlyWell/redash,akariv/redash,ninneko/redash,moritz9/redash,jmvasquez/redashtest,useabode/redash,vishesh92/redash,chriszs/redash,getredash/redash,jmvasquez/redashtest,useabode/redash,easytaxibr/redash,ninneko/redash,amino-data/redash,pubnative/redash,hudl/redash,EverlyWell/redash,guaguadev/redash,jmvasquez/redashtest,easytaxibr/redash,hudl/redash,vishesh92/redash,chriszs/redash,rockwotj/redash,alexanderlz/redash,hudl/redash,alexanderlz/redash,guaguadev/redash
|
import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=settings.STATIC_ASSETS_PATH,
static_path='/static')
api = Api(app)
# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
db = Database(app)
from redash.authentication import setup_authentication
auth = setup_authentication(app)
@api.representation('application/json')
def json_representation(data, code, headers=None):
resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
resp.headers.extend(headers or {})
return resp
redis_url = urlparse.urlparse(settings.REDIS_URL)
+ if redis_url.path:
+ redis_db = redis_url.path[1]
+ else:
+ redis_db = 0
- redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=0, password=redis_url.password)
+ redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_url.password)
from redash import data
data_manager = data.Manager(redis_connection, db)
from redash import controllers
|
Use database number from redis url if available.
|
## Code Before:
import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=settings.STATIC_ASSETS_PATH,
static_path='/static')
api = Api(app)
# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
db = Database(app)
from redash.authentication import setup_authentication
auth = setup_authentication(app)
@api.representation('application/json')
def json_representation(data, code, headers=None):
resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
resp.headers.extend(headers or {})
return resp
redis_url = urlparse.urlparse(settings.REDIS_URL)
redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=0, password=redis_url.password)
from redash import data
data_manager = data.Manager(redis_connection, db)
from redash import controllers
## Instruction:
Use database number from redis url if available.
## Code After:
import json
import urlparse
from flask import Flask, make_response
from flask.ext.restful import Api
from flask_peewee.db import Database
import redis
from redash import settings, utils
__version__ = '0.3.2'
app = Flask(__name__,
template_folder=settings.STATIC_ASSETS_PATH,
static_folder=settings.STATIC_ASSETS_PATH,
static_path='/static')
api = Api(app)
# configure our database
settings.DATABASE_CONFIG.update({'threadlocals': True})
app.config['DATABASE'] = settings.DATABASE_CONFIG
db = Database(app)
from redash.authentication import setup_authentication
auth = setup_authentication(app)
@api.representation('application/json')
def json_representation(data, code, headers=None):
resp = make_response(json.dumps(data, cls=utils.JSONEncoder), code)
resp.headers.extend(headers or {})
return resp
redis_url = urlparse.urlparse(settings.REDIS_URL)
if redis_url.path:
redis_db = redis_url.path[1]
else:
redis_db = 0
redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_url.password)
from redash import data
data_manager = data.Manager(redis_connection, db)
from redash import controllers
|
...
redis_url = urlparse.urlparse(settings.REDIS_URL)
if redis_url.path:
redis_db = redis_url.path[1]
else:
redis_db = 0
redis_connection = redis.StrictRedis(host=redis_url.hostname, port=redis_url.port, db=redis_db, password=redis_url.password)
...
|
460a2430fbd8832f3fada1a74b754d71a27ac282
|
mockingjay/matcher.py
|
mockingjay/matcher.py
|
import abc
import re
class Matcher(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def assert_request_matched(self, request):
"""
Assert that the request matched the spec in this matcher object.
"""
class HeaderMatcher(Matcher):
"""
Matcher for the request's header.
:param key: the name of the header
:param value: the value of the header
"""
def __init__(self, key, value):
self.key = key
self.value = value
def assert_request_matched(self, request):
assert request.headers.get(self.key) == self.value
class BodyMatcher(Matcher):
"""
Matcher for the request body.
:param body: can either be a string or a :class:`_sre.SRE_Pattern`: object
"""
def __init__(self, body):
self.body = body
def assert_request_matched(self, request):
if isinstance(self.body, re._pattern_type):
assert self.body.search(request.body) is not None
else:
assert request.body == self.body
|
import abc
import re
class StringOrPattern(object):
"""
A decorator object that wraps a string or a regex pattern so that it can
be compared against another string either literally or using the pattern.
"""
def __init__(self, subject):
self.subject = subject
def __eq__(self, other_str):
if isinstance(self.subject, re._pattern_type):
return self.subject.search(other_str) is not None
else:
return self.subject == other_str
def __hash__(self):
return self.subject.__hash__()
class Matcher(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def assert_request_matched(self, request):
"""
Assert that the request matched the spec in this matcher object.
"""
class HeaderMatcher(Matcher):
"""
Matcher for the request's header.
:param key: the name of the header
:param value: the value of the header
"""
def __init__(self, key, value):
self.key = key
self.value = StringOrPattern(value)
def assert_request_matched(self, request):
assert request.headers.get(self.key) == self.value
class BodyMatcher(Matcher):
"""
Matcher for the request body.
:param body: can either be a string or a :class:`_sre.SRE_Pattern`: object
"""
def __init__(self, body):
self.body = StringOrPattern(body)
def assert_request_matched(self, request):
assert request.body == self.body
|
Allow all values to be compared with either literally or with a pattern
|
Allow all values to be compared with either literally or with a pattern
|
Python
|
bsd-3-clause
|
kevinjqiu/mockingjay
|
import abc
import re
+
+
+ class StringOrPattern(object):
+ """
+ A decorator object that wraps a string or a regex pattern so that it can
+ be compared against another string either literally or using the pattern.
+ """
+ def __init__(self, subject):
+ self.subject = subject
+
+ def __eq__(self, other_str):
+ if isinstance(self.subject, re._pattern_type):
+ return self.subject.search(other_str) is not None
+ else:
+ return self.subject == other_str
+
+ def __hash__(self):
+ return self.subject.__hash__()
class Matcher(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def assert_request_matched(self, request):
"""
Assert that the request matched the spec in this matcher object.
"""
class HeaderMatcher(Matcher):
"""
Matcher for the request's header.
:param key: the name of the header
:param value: the value of the header
"""
def __init__(self, key, value):
self.key = key
- self.value = value
+ self.value = StringOrPattern(value)
def assert_request_matched(self, request):
assert request.headers.get(self.key) == self.value
class BodyMatcher(Matcher):
"""
Matcher for the request body.
:param body: can either be a string or a :class:`_sre.SRE_Pattern`: object
"""
def __init__(self, body):
- self.body = body
+ self.body = StringOrPattern(body)
def assert_request_matched(self, request):
- if isinstance(self.body, re._pattern_type):
- assert self.body.search(request.body) is not None
- else:
- assert request.body == self.body
+ assert request.body == self.body
|
Allow all values to be compared with either literally or with a pattern
|
## Code Before:
import abc
import re
class Matcher(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def assert_request_matched(self, request):
"""
Assert that the request matched the spec in this matcher object.
"""
class HeaderMatcher(Matcher):
"""
Matcher for the request's header.
:param key: the name of the header
:param value: the value of the header
"""
def __init__(self, key, value):
self.key = key
self.value = value
def assert_request_matched(self, request):
assert request.headers.get(self.key) == self.value
class BodyMatcher(Matcher):
"""
Matcher for the request body.
:param body: can either be a string or a :class:`_sre.SRE_Pattern`: object
"""
def __init__(self, body):
self.body = body
def assert_request_matched(self, request):
if isinstance(self.body, re._pattern_type):
assert self.body.search(request.body) is not None
else:
assert request.body == self.body
## Instruction:
Allow all values to be compared with either literally or with a pattern
## Code After:
import abc
import re
class StringOrPattern(object):
"""
A decorator object that wraps a string or a regex pattern so that it can
be compared against another string either literally or using the pattern.
"""
def __init__(self, subject):
self.subject = subject
def __eq__(self, other_str):
if isinstance(self.subject, re._pattern_type):
return self.subject.search(other_str) is not None
else:
return self.subject == other_str
def __hash__(self):
return self.subject.__hash__()
class Matcher(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def assert_request_matched(self, request):
"""
Assert that the request matched the spec in this matcher object.
"""
class HeaderMatcher(Matcher):
"""
Matcher for the request's header.
:param key: the name of the header
:param value: the value of the header
"""
def __init__(self, key, value):
self.key = key
self.value = StringOrPattern(value)
def assert_request_matched(self, request):
assert request.headers.get(self.key) == self.value
class BodyMatcher(Matcher):
"""
Matcher for the request body.
:param body: can either be a string or a :class:`_sre.SRE_Pattern`: object
"""
def __init__(self, body):
self.body = StringOrPattern(body)
def assert_request_matched(self, request):
assert request.body == self.body
|
// ... existing code ...
import re
class StringOrPattern(object):
"""
A decorator object that wraps a string or a regex pattern so that it can
be compared against another string either literally or using the pattern.
"""
def __init__(self, subject):
self.subject = subject
def __eq__(self, other_str):
if isinstance(self.subject, re._pattern_type):
return self.subject.search(other_str) is not None
else:
return self.subject == other_str
def __hash__(self):
return self.subject.__hash__()
// ... modified code ...
self.key = key
self.value = StringOrPattern(value)
...
def __init__(self, body):
self.body = StringOrPattern(body)
...
def assert_request_matched(self, request):
assert request.body == self.body
// ... rest of the code ...
|
f55f965c4102e2d7230ace39a0eecdaf585538ea
|
blaze/expr/scalar/boolean.py
|
blaze/expr/scalar/boolean.py
|
import operator
from datashape import dshape
from .core import Scalar, BinOp, UnaryOp
class BooleanInterface(Scalar):
def __not__(self):
return Not(self)
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
class Boolean(BooleanInterface):
@property
def dshape(self):
return dshape('bool')
class Relational(BinOp, Boolean):
pass
class Eq(Relational):
symbol = '=='
op = operator.eq
class Ne(Relational):
symbol = '!='
op = operator.ne
class Ge(Relational):
symbol = '>='
op = operator.ge
class Le(Relational):
symbol = '<='
op = operator.le
class Gt(Relational):
symbol = '>'
op = operator.gt
class Lt(Relational):
symbol = '<'
op = operator.lt
class And(BinOp, Boolean):
symbol = '&'
op = operator.and_
class Or(BinOp, Boolean):
symbol = '|'
op = operator.or_
class Not(UnaryOp, Boolean):
op = operator.not_
Invert = Not
BitAnd = And
BitOr = Or
|
import operator
from datashape import dshape
from .core import Scalar, BinOp, UnaryOp
class BooleanInterface(Scalar):
def __invert__(self):
return Invert(self)
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
class Boolean(BooleanInterface):
@property
def dshape(self):
return dshape('bool')
class Relational(BinOp, Boolean):
pass
class Eq(Relational):
symbol = '=='
op = operator.eq
class Ne(Relational):
symbol = '!='
op = operator.ne
class Ge(Relational):
symbol = '>='
op = operator.ge
class Le(Relational):
symbol = '<='
op = operator.le
class Gt(Relational):
symbol = '>'
op = operator.gt
class Lt(Relational):
symbol = '<'
op = operator.lt
class And(BinOp, Boolean):
symbol = '&'
op = operator.and_
class Or(BinOp, Boolean):
symbol = '|'
op = operator.or_
class Not(UnaryOp, Boolean):
symbol = '~'
op = operator.not_
Invert = Not
BitAnd = And
BitOr = Or
|
Use __invert__ instead of __not__
|
Use __invert__ instead of __not__
|
Python
|
bsd-3-clause
|
LiaoPan/blaze,caseyclements/blaze,cpcloud/blaze,cowlicks/blaze,caseyclements/blaze,jdmcbr/blaze,dwillmer/blaze,nkhuyu/blaze,scls19fr/blaze,mrocklin/blaze,cowlicks/blaze,dwillmer/blaze,cpcloud/blaze,xlhtc007/blaze,jcrist/blaze,maxalbert/blaze,jdmcbr/blaze,ChinaQuants/blaze,ContinuumIO/blaze,maxalbert/blaze,mrocklin/blaze,nkhuyu/blaze,jcrist/blaze,LiaoPan/blaze,xlhtc007/blaze,ChinaQuants/blaze,scls19fr/blaze,ContinuumIO/blaze,alexmojaki/blaze,alexmojaki/blaze
|
import operator
from datashape import dshape
from .core import Scalar, BinOp, UnaryOp
class BooleanInterface(Scalar):
- def __not__(self):
+ def __invert__(self):
- return Not(self)
+ return Invert(self)
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
class Boolean(BooleanInterface):
@property
def dshape(self):
return dshape('bool')
class Relational(BinOp, Boolean):
pass
class Eq(Relational):
symbol = '=='
op = operator.eq
class Ne(Relational):
symbol = '!='
op = operator.ne
class Ge(Relational):
symbol = '>='
op = operator.ge
class Le(Relational):
symbol = '<='
op = operator.le
class Gt(Relational):
symbol = '>'
op = operator.gt
class Lt(Relational):
symbol = '<'
op = operator.lt
class And(BinOp, Boolean):
symbol = '&'
op = operator.and_
class Or(BinOp, Boolean):
symbol = '|'
op = operator.or_
class Not(UnaryOp, Boolean):
+ symbol = '~'
op = operator.not_
Invert = Not
BitAnd = And
BitOr = Or
|
Use __invert__ instead of __not__
|
## Code Before:
import operator
from datashape import dshape
from .core import Scalar, BinOp, UnaryOp
class BooleanInterface(Scalar):
def __not__(self):
return Not(self)
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
class Boolean(BooleanInterface):
@property
def dshape(self):
return dshape('bool')
class Relational(BinOp, Boolean):
pass
class Eq(Relational):
symbol = '=='
op = operator.eq
class Ne(Relational):
symbol = '!='
op = operator.ne
class Ge(Relational):
symbol = '>='
op = operator.ge
class Le(Relational):
symbol = '<='
op = operator.le
class Gt(Relational):
symbol = '>'
op = operator.gt
class Lt(Relational):
symbol = '<'
op = operator.lt
class And(BinOp, Boolean):
symbol = '&'
op = operator.and_
class Or(BinOp, Boolean):
symbol = '|'
op = operator.or_
class Not(UnaryOp, Boolean):
op = operator.not_
Invert = Not
BitAnd = And
BitOr = Or
## Instruction:
Use __invert__ instead of __not__
## Code After:
import operator
from datashape import dshape
from .core import Scalar, BinOp, UnaryOp
class BooleanInterface(Scalar):
def __invert__(self):
return Invert(self)
def __and__(self, other):
return And(self, other)
def __or__(self, other):
return Or(self, other)
class Boolean(BooleanInterface):
@property
def dshape(self):
return dshape('bool')
class Relational(BinOp, Boolean):
pass
class Eq(Relational):
symbol = '=='
op = operator.eq
class Ne(Relational):
symbol = '!='
op = operator.ne
class Ge(Relational):
symbol = '>='
op = operator.ge
class Le(Relational):
symbol = '<='
op = operator.le
class Gt(Relational):
symbol = '>'
op = operator.gt
class Lt(Relational):
symbol = '<'
op = operator.lt
class And(BinOp, Boolean):
symbol = '&'
op = operator.and_
class Or(BinOp, Boolean):
symbol = '|'
op = operator.or_
class Not(UnaryOp, Boolean):
symbol = '~'
op = operator.not_
Invert = Not
BitAnd = And
BitOr = Or
|
// ... existing code ...
class BooleanInterface(Scalar):
def __invert__(self):
return Invert(self)
// ... modified code ...
class Not(UnaryOp, Boolean):
symbol = '~'
op = operator.not_
// ... rest of the code ...
|
edf38ad11631ad5e793eb9ac95dbc865595d517b
|
glue_vispy_viewers/common/layer_state.py
|
glue_vispy_viewers/common/layer_state.py
|
from __future__ import absolute_import, division, print_function
from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
__all__ = ['VispyLayerState']
class VispyLayerState(State):
"""
A base state object for all Vispy layers
"""
layer = CallbackProperty()
visible = CallbackProperty(True)
zorder = CallbackProperty(0)
color = CallbackProperty()
alpha = CallbackProperty()
def __init__(self, **kwargs):
super(VispyLayerState, self).__init__(**kwargs)
self._sync_color = None
self._sync_alpha = None
self.add_callback('layer', self._layer_changed)
self._layer_changed()
def _layer_changed(self):
if self._sync_color is not None:
self._sync_color.stop_syncing()
if self._sync_alpha is not None:
self._sync_alpha.stop_syncing()
if self.layer is not None:
self.color = self.layer.style.color
self.alpha = self.layer.style.alpha
self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')
|
from __future__ import absolute_import, division, print_function
from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
from glue.core.message import LayerArtistUpdatedMessage
__all__ = ['VispyLayerState']
class VispyLayerState(State):
"""
A base state object for all Vispy layers
"""
layer = CallbackProperty()
visible = CallbackProperty(True)
zorder = CallbackProperty(0)
color = CallbackProperty()
alpha = CallbackProperty()
def __init__(self, **kwargs):
super(VispyLayerState, self).__init__(**kwargs)
self._sync_color = None
self._sync_alpha = None
self.add_callback('layer', self._layer_changed)
self._layer_changed()
self.add_global_callback(self._notify_layer_update)
def _notify_layer_update(self, **kwargs):
message = LayerArtistUpdatedMessage(self)
if self.layer is not None and self.layer.hub is not None:
self.layer.hub.broadcast(message)
def _layer_changed(self):
if self._sync_color is not None:
self._sync_color.stop_syncing()
if self._sync_alpha is not None:
self._sync_alpha.stop_syncing()
if self.layer is not None:
self.color = self.layer.style.color
self.alpha = self.layer.style.alpha
self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')
|
Make sure layer artist icon updates when changing the color mode or colormaps
|
Make sure layer artist icon updates when changing the color mode or colormaps
|
Python
|
bsd-2-clause
|
glue-viz/glue-vispy-viewers,PennyQ/astro-vispy,astrofrog/glue-3d-viewer,glue-viz/glue-3d-viewer,astrofrog/glue-vispy-viewers
|
from __future__ import absolute_import, division, print_function
from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
+ from glue.core.message import LayerArtistUpdatedMessage
__all__ = ['VispyLayerState']
class VispyLayerState(State):
"""
A base state object for all Vispy layers
"""
layer = CallbackProperty()
visible = CallbackProperty(True)
zorder = CallbackProperty(0)
color = CallbackProperty()
alpha = CallbackProperty()
def __init__(self, **kwargs):
super(VispyLayerState, self).__init__(**kwargs)
self._sync_color = None
self._sync_alpha = None
self.add_callback('layer', self._layer_changed)
self._layer_changed()
+ self.add_global_callback(self._notify_layer_update)
+
+ def _notify_layer_update(self, **kwargs):
+ message = LayerArtistUpdatedMessage(self)
+ if self.layer is not None and self.layer.hub is not None:
+ self.layer.hub.broadcast(message)
+
def _layer_changed(self):
if self._sync_color is not None:
self._sync_color.stop_syncing()
if self._sync_alpha is not None:
self._sync_alpha.stop_syncing()
if self.layer is not None:
self.color = self.layer.style.color
self.alpha = self.layer.style.alpha
self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')
|
Make sure layer artist icon updates when changing the color mode or colormaps
|
## Code Before:
from __future__ import absolute_import, division, print_function
from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
__all__ = ['VispyLayerState']
class VispyLayerState(State):
"""
A base state object for all Vispy layers
"""
layer = CallbackProperty()
visible = CallbackProperty(True)
zorder = CallbackProperty(0)
color = CallbackProperty()
alpha = CallbackProperty()
def __init__(self, **kwargs):
super(VispyLayerState, self).__init__(**kwargs)
self._sync_color = None
self._sync_alpha = None
self.add_callback('layer', self._layer_changed)
self._layer_changed()
def _layer_changed(self):
if self._sync_color is not None:
self._sync_color.stop_syncing()
if self._sync_alpha is not None:
self._sync_alpha.stop_syncing()
if self.layer is not None:
self.color = self.layer.style.color
self.alpha = self.layer.style.alpha
self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')
## Instruction:
Make sure layer artist icon updates when changing the color mode or colormaps
## Code After:
from __future__ import absolute_import, division, print_function
from glue.external.echo import CallbackProperty, keep_in_sync
from glue.core.state_objects import State
from glue.core.message import LayerArtistUpdatedMessage
__all__ = ['VispyLayerState']
class VispyLayerState(State):
"""
A base state object for all Vispy layers
"""
layer = CallbackProperty()
visible = CallbackProperty(True)
zorder = CallbackProperty(0)
color = CallbackProperty()
alpha = CallbackProperty()
def __init__(self, **kwargs):
super(VispyLayerState, self).__init__(**kwargs)
self._sync_color = None
self._sync_alpha = None
self.add_callback('layer', self._layer_changed)
self._layer_changed()
self.add_global_callback(self._notify_layer_update)
def _notify_layer_update(self, **kwargs):
message = LayerArtistUpdatedMessage(self)
if self.layer is not None and self.layer.hub is not None:
self.layer.hub.broadcast(message)
def _layer_changed(self):
if self._sync_color is not None:
self._sync_color.stop_syncing()
if self._sync_alpha is not None:
self._sync_alpha.stop_syncing()
if self.layer is not None:
self.color = self.layer.style.color
self.alpha = self.layer.style.alpha
self._sync_color = keep_in_sync(self, 'color', self.layer.style, 'color')
self._sync_alpha = keep_in_sync(self, 'alpha', self.layer.style, 'alpha')
|
# ... existing code ...
from glue.core.state_objects import State
from glue.core.message import LayerArtistUpdatedMessage
# ... modified code ...
self.add_global_callback(self._notify_layer_update)
def _notify_layer_update(self, **kwargs):
message = LayerArtistUpdatedMessage(self)
if self.layer is not None and self.layer.hub is not None:
self.layer.hub.broadcast(message)
def _layer_changed(self):
# ... rest of the code ...
|
fb10e4b8ae37f1442bdb643c27ea0b984da6a374
|
cherrypy/test/test_httputil.py
|
cherrypy/test/test_httputil.py
|
"""Tests for cherrypy/lib/httputil.py."""
import unittest
from cherrypy.lib import httputil
class UtilityTests(unittest.TestCase):
def test_urljoin(self):
# Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO
self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/')
self.assertEqual(httputil.urljoin('/sn/', '/pi'), '/sn/pi')
self.assertEqual(httputil.urljoin('/sn/', '/'), '/sn/')
self.assertEqual(httputil.urljoin('/sn/', ''), '/sn/')
self.assertEqual(httputil.urljoin('/sn', '/pi/'), '/sn/pi/')
self.assertEqual(httputil.urljoin('/sn', '/pi'), '/sn/pi')
self.assertEqual(httputil.urljoin('/sn', '/'), '/sn/')
self.assertEqual(httputil.urljoin('/sn', ''), '/sn')
self.assertEqual(httputil.urljoin('/', '/pi/'), '/pi/')
self.assertEqual(httputil.urljoin('/', '/pi'), '/pi')
self.assertEqual(httputil.urljoin('/', '/'), '/')
self.assertEqual(httputil.urljoin('/', ''), '/')
self.assertEqual(httputil.urljoin('', '/pi/'), '/pi/')
self.assertEqual(httputil.urljoin('', '/pi'), '/pi')
self.assertEqual(httputil.urljoin('', '/'), '/')
self.assertEqual(httputil.urljoin('', ''), '/')
if __name__ == '__main__':
unittest.main()
|
"""Tests for ``cherrypy.lib.httputil``."""
import pytest
from cherrypy.lib import httputil
class TestUtility(object):
@pytest.mark.parametrize(
'script_name,path_info,expected_url',
[
('/sn/', '/pi/', '/sn/pi/'),
('/sn/', '/pi', '/sn/pi'),
('/sn/', '/', '/sn/'),
('/sn/', '', '/sn/'),
('/sn', '/pi/', '/sn/pi/'),
('/sn', '/pi', '/sn/pi'),
('/sn', '/', '/sn/'),
('/sn', '', '/sn'),
('/', '/pi/', '/pi/'),
('/', '/pi', '/pi'),
('/', '/', '/'),
('/', '', '/'),
('', '/pi/', '/pi/'),
('', '/pi', '/pi'),
('', '/', '/'),
('', '', '/'),
]
)
def test_urljoin(self, script_name, path_info, expected_url):
"""Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO."""
actual_url = httputil.urljoin(script_name, path_info)
assert actual_url == expected_url
|
Rewrite httputil test module via pytest
|
Rewrite httputil test module via pytest
|
Python
|
bsd-3-clause
|
cherrypy/cherrypy,Safihre/cherrypy,Safihre/cherrypy,cherrypy/cherrypy
|
- """Tests for cherrypy/lib/httputil.py."""
+ """Tests for ``cherrypy.lib.httputil``."""
+ import pytest
- import unittest
from cherrypy.lib import httputil
- class UtilityTests(unittest.TestCase):
+ class TestUtility(object):
+ @pytest.mark.parametrize(
+ 'script_name,path_info,expected_url',
+ [
+ ('/sn/', '/pi/', '/sn/pi/'),
+ ('/sn/', '/pi', '/sn/pi'),
+ ('/sn/', '/', '/sn/'),
+ ('/sn/', '', '/sn/'),
+ ('/sn', '/pi/', '/sn/pi/'),
+ ('/sn', '/pi', '/sn/pi'),
+ ('/sn', '/', '/sn/'),
+ ('/sn', '', '/sn'),
+ ('/', '/pi/', '/pi/'),
+ ('/', '/pi', '/pi'),
+ ('/', '/', '/'),
+ ('/', '', '/'),
+ ('', '/pi/', '/pi/'),
+ ('', '/pi', '/pi'),
+ ('', '/', '/'),
+ ('', '', '/'),
+ ]
+ )
+ def test_urljoin(self, script_name, path_info, expected_url):
+ """Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO."""
+ actual_url = httputil.urljoin(script_name, path_info)
+ assert actual_url == expected_url
- def test_urljoin(self):
- # Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO
- self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/')
- self.assertEqual(httputil.urljoin('/sn/', '/pi'), '/sn/pi')
- self.assertEqual(httputil.urljoin('/sn/', '/'), '/sn/')
- self.assertEqual(httputil.urljoin('/sn/', ''), '/sn/')
- self.assertEqual(httputil.urljoin('/sn', '/pi/'), '/sn/pi/')
- self.assertEqual(httputil.urljoin('/sn', '/pi'), '/sn/pi')
- self.assertEqual(httputil.urljoin('/sn', '/'), '/sn/')
- self.assertEqual(httputil.urljoin('/sn', ''), '/sn')
- self.assertEqual(httputil.urljoin('/', '/pi/'), '/pi/')
- self.assertEqual(httputil.urljoin('/', '/pi'), '/pi')
- self.assertEqual(httputil.urljoin('/', '/'), '/')
- self.assertEqual(httputil.urljoin('/', ''), '/')
- self.assertEqual(httputil.urljoin('', '/pi/'), '/pi/')
- self.assertEqual(httputil.urljoin('', '/pi'), '/pi')
- self.assertEqual(httputil.urljoin('', '/'), '/')
- self.assertEqual(httputil.urljoin('', ''), '/')
-
-
- if __name__ == '__main__':
- unittest.main()
-
|
Rewrite httputil test module via pytest
|
## Code Before:
"""Tests for cherrypy/lib/httputil.py."""
import unittest
from cherrypy.lib import httputil
class UtilityTests(unittest.TestCase):
def test_urljoin(self):
# Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO
self.assertEqual(httputil.urljoin('/sn/', '/pi/'), '/sn/pi/')
self.assertEqual(httputil.urljoin('/sn/', '/pi'), '/sn/pi')
self.assertEqual(httputil.urljoin('/sn/', '/'), '/sn/')
self.assertEqual(httputil.urljoin('/sn/', ''), '/sn/')
self.assertEqual(httputil.urljoin('/sn', '/pi/'), '/sn/pi/')
self.assertEqual(httputil.urljoin('/sn', '/pi'), '/sn/pi')
self.assertEqual(httputil.urljoin('/sn', '/'), '/sn/')
self.assertEqual(httputil.urljoin('/sn', ''), '/sn')
self.assertEqual(httputil.urljoin('/', '/pi/'), '/pi/')
self.assertEqual(httputil.urljoin('/', '/pi'), '/pi')
self.assertEqual(httputil.urljoin('/', '/'), '/')
self.assertEqual(httputil.urljoin('/', ''), '/')
self.assertEqual(httputil.urljoin('', '/pi/'), '/pi/')
self.assertEqual(httputil.urljoin('', '/pi'), '/pi')
self.assertEqual(httputil.urljoin('', '/'), '/')
self.assertEqual(httputil.urljoin('', ''), '/')
if __name__ == '__main__':
unittest.main()
## Instruction:
Rewrite httputil test module via pytest
## Code After:
"""Tests for ``cherrypy.lib.httputil``."""
import pytest
from cherrypy.lib import httputil
class TestUtility(object):
@pytest.mark.parametrize(
'script_name,path_info,expected_url',
[
('/sn/', '/pi/', '/sn/pi/'),
('/sn/', '/pi', '/sn/pi'),
('/sn/', '/', '/sn/'),
('/sn/', '', '/sn/'),
('/sn', '/pi/', '/sn/pi/'),
('/sn', '/pi', '/sn/pi'),
('/sn', '/', '/sn/'),
('/sn', '', '/sn'),
('/', '/pi/', '/pi/'),
('/', '/pi', '/pi'),
('/', '/', '/'),
('/', '', '/'),
('', '/pi/', '/pi/'),
('', '/pi', '/pi'),
('', '/', '/'),
('', '', '/'),
]
)
def test_urljoin(self, script_name, path_info, expected_url):
"""Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO."""
actual_url = httputil.urljoin(script_name, path_info)
assert actual_url == expected_url
|
# ... existing code ...
"""Tests for ``cherrypy.lib.httputil``."""
import pytest
from cherrypy.lib import httputil
# ... modified code ...
class TestUtility(object):
@pytest.mark.parametrize(
'script_name,path_info,expected_url',
[
('/sn/', '/pi/', '/sn/pi/'),
('/sn/', '/pi', '/sn/pi'),
('/sn/', '/', '/sn/'),
('/sn/', '', '/sn/'),
('/sn', '/pi/', '/sn/pi/'),
('/sn', '/pi', '/sn/pi'),
('/sn', '/', '/sn/'),
('/sn', '', '/sn'),
('/', '/pi/', '/pi/'),
('/', '/pi', '/pi'),
('/', '/', '/'),
('/', '', '/'),
('', '/pi/', '/pi/'),
('', '/pi', '/pi'),
('', '/', '/'),
('', '', '/'),
]
)
def test_urljoin(self, script_name, path_info, expected_url):
"""Test all slash+atom combinations for SCRIPT_NAME and PATH_INFO."""
actual_url = httputil.urljoin(script_name, path_info)
assert actual_url == expected_url
# ... rest of the code ...
|
0b82a5c10a9e728f6f5424429a70fd2951c9b5c5
|
pythonmisp/__init__.py
|
pythonmisp/__init__.py
|
from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute
|
from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute, MispTransportError
|
Add MispTransportError in package import
|
Add MispTransportError in package import
|
Python
|
apache-2.0
|
nbareil/python-misp
|
- from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute
+ from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute, MispTransportError
|
Add MispTransportError in package import
|
## Code Before:
from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute
## Instruction:
Add MispTransportError in package import
## Code After:
from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute, MispTransportError
|
// ... existing code ...
from .misp import MispTag, MispEvent, MispServer, MispAttribute, MispShadowAttribute, MispTransportError
// ... rest of the code ...
|
df98c8bd70f25727810e6eb9d359cf1e14fd6645
|
update_prices.py
|
update_prices.py
|
import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
ITEMS = [
34, # Tritanium
35, # Pyerite
36, # Mexallon
37, # Isogen
38, # Nocxium
39, # Zydrine
40, # Megacyte
11399, # Morphite
]
def main():
conn = sqlite3.connect('everdi.db')
cur = conn.cursor()
url = MARKET_URL % ('&'.join('typeid=%s' % i for i in ITEMS))
f = urllib2.urlopen(url)
data = f.read()
f.close()
#open('data.txt', 'w').write(data)
#data = open('data.txt').read()
root = ET.fromstring(data)
for t in root.findall('marketstat/type'):
typeid = t.get('id')
sell_median = t.find('sell/median').text
buy_median = t.find('buy/median').text
cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))
conn.commit()
if __name__ == '__main__':
main()
|
import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
def main():
conn = sqlite3.connect('everdi.db')
cur = conn.cursor()
# Get all items used in current BlueprintInstances
cur.execute("""
SELECT DISTINCT c.item_id
FROM blueprints_blueprintcomponent c
INNER JOIN blueprints_blueprintinstance AS bi
ON c.blueprint_id = bi.blueprint_id
""")
rows = cur.fetchall()
for i in range(0, len(rows), 20):
url = MARKET_URL % ('&'.join('typeid=%s' % item for item in rows[i:i+20]))
f = urllib2.urlopen(url)
data = f.read()
f.close()
#open('data.txt', 'w').write(data)
#data = open('data.txt').read()
root = ET.fromstring(data)
for t in root.findall('marketstat/type'):
typeid = t.get('id')
sell_median = t.find('sell/median').text
buy_median = t.find('buy/median').text
cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))
conn.commit()
if __name__ == '__main__':
main()
|
Update prices for all BlueprintInstances we currently have
|
Update prices for all BlueprintInstances we currently have
|
Python
|
bsd-2-clause
|
madcowfred/evething,Gillingham/evething,cmptrgeekken/evething,madcowfred/evething,cmptrgeekken/evething,cmptrgeekken/evething,cmptrgeekken/evething,madcowfred/evething,Gillingham/evething,madcowfred/evething,cmptrgeekken/evething,Gillingham/evething,Gillingham/evething
|
import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
- ITEMS = [
- 34, # Tritanium
- 35, # Pyerite
- 36, # Mexallon
- 37, # Isogen
- 38, # Nocxium
- 39, # Zydrine
- 40, # Megacyte
- 11399, # Morphite
- ]
-
def main():
conn = sqlite3.connect('everdi.db')
cur = conn.cursor()
- url = MARKET_URL % ('&'.join('typeid=%s' % i for i in ITEMS))
- f = urllib2.urlopen(url)
- data = f.read()
- f.close()
- #open('data.txt', 'w').write(data)
- #data = open('data.txt').read()
+ # Get all items used in current BlueprintInstances
+ cur.execute("""
+ SELECT DISTINCT c.item_id
+ FROM blueprints_blueprintcomponent c
+ INNER JOIN blueprints_blueprintinstance AS bi
+ ON c.blueprint_id = bi.blueprint_id
+ """)
+ rows = cur.fetchall()
- root = ET.fromstring(data)
- for t in root.findall('marketstat/type'):
- typeid = t.get('id')
- sell_median = t.find('sell/median').text
- buy_median = t.find('buy/median').text
+ for i in range(0, len(rows), 20):
+ url = MARKET_URL % ('&'.join('typeid=%s' % item for item in rows[i:i+20]))
+ f = urllib2.urlopen(url)
+ data = f.read()
+ f.close()
+ #open('data.txt', 'w').write(data)
+ #data = open('data.txt').read()
+ root = ET.fromstring(data)
+ for t in root.findall('marketstat/type'):
+ typeid = t.get('id')
+ sell_median = t.find('sell/median').text
+ buy_median = t.find('buy/median').text
+
- cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))
+ cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))
-
+
- conn.commit()
+ conn.commit()
if __name__ == '__main__':
main()
|
Update prices for all BlueprintInstances we currently have
|
## Code Before:
import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
ITEMS = [
34, # Tritanium
35, # Pyerite
36, # Mexallon
37, # Isogen
38, # Nocxium
39, # Zydrine
40, # Megacyte
11399, # Morphite
]
def main():
conn = sqlite3.connect('everdi.db')
cur = conn.cursor()
url = MARKET_URL % ('&'.join('typeid=%s' % i for i in ITEMS))
f = urllib2.urlopen(url)
data = f.read()
f.close()
#open('data.txt', 'w').write(data)
#data = open('data.txt').read()
root = ET.fromstring(data)
for t in root.findall('marketstat/type'):
typeid = t.get('id')
sell_median = t.find('sell/median').text
buy_median = t.find('buy/median').text
cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))
conn.commit()
if __name__ == '__main__':
main()
## Instruction:
Update prices for all BlueprintInstances we currently have
## Code After:
import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
def main():
conn = sqlite3.connect('everdi.db')
cur = conn.cursor()
# Get all items used in current BlueprintInstances
cur.execute("""
SELECT DISTINCT c.item_id
FROM blueprints_blueprintcomponent c
INNER JOIN blueprints_blueprintinstance AS bi
ON c.blueprint_id = bi.blueprint_id
""")
rows = cur.fetchall()
for i in range(0, len(rows), 20):
url = MARKET_URL % ('&'.join('typeid=%s' % item for item in rows[i:i+20]))
f = urllib2.urlopen(url)
data = f.read()
f.close()
#open('data.txt', 'w').write(data)
#data = open('data.txt').read()
root = ET.fromstring(data)
for t in root.findall('marketstat/type'):
typeid = t.get('id')
sell_median = t.find('sell/median').text
buy_median = t.find('buy/median').text
cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))
conn.commit()
if __name__ == '__main__':
main()
|
// ... existing code ...
// ... modified code ...
# Get all items used in current BlueprintInstances
cur.execute("""
SELECT DISTINCT c.item_id
FROM blueprints_blueprintcomponent c
INNER JOIN blueprints_blueprintinstance AS bi
ON c.blueprint_id = bi.blueprint_id
""")
rows = cur.fetchall()
for i in range(0, len(rows), 20):
url = MARKET_URL % ('&'.join('typeid=%s' % item for item in rows[i:i+20]))
f = urllib2.urlopen(url)
data = f.read()
f.close()
#open('data.txt', 'w').write(data)
#data = open('data.txt').read()
root = ET.fromstring(data)
for t in root.findall('marketstat/type'):
typeid = t.get('id')
sell_median = t.find('sell/median').text
buy_median = t.find('buy/median').text
cur.execute('UPDATE blueprints_item SET sell_median=?, buy_median=? WHERE id=?', (sell_median, buy_median, typeid))
conn.commit()
// ... rest of the code ...
|
ffaa2b98305c7a1368587cdb30724a7cabbe3237
|
glitch/apikeys_sample.py
|
glitch/apikeys_sample.py
|
db_connect_string = ""
cookie_monster = "llsfZyohQDa4kRdCCqnoV3gpD8jaHUY0kfkKI3pZlZ4="
# in Python you can generate like this:
# import base64
# import uuid
# print(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes))
# Thanks to https://gist.github.com/didip/823887
# Alternative way to generate a similar-length nonce:
# import base64, os; print(base64.b64encode(os.urandom(33)))
# These settings are used only for the sending of emails. The server will
# start with them at the defaults, but all email sending will fail.
system_email = '[email protected]'
admin_email = '[email protected]'
# Will use default settings if SMTP_SERVER_PORT == 'localhost'
SMTP_SERVER_PORT = "smtp.gmail.com:587"
SMTP_USERNAME = "[email protected]"
SMTP_PASSWORD = "yourpassword"
|
db_connect_string = ""
cookie_monster = "uqHHRiRIUyCIcB0RJJcv+T/Qc3wJS0p/jsyE1x36qBIa"
# Generated like this:
# import base64, os; print(base64.b64encode(os.urandom(33)))
# These settings are used only for the sending of emails. The server will
# start with them at the defaults, but all email sending will fail.
system_email = '[email protected]'
admin_email = '[email protected]'
# Will use default settings if SMTP_SERVER_PORT == 'localhost'
SMTP_SERVER_PORT = "smtp.gmail.com:587"
SMTP_USERNAME = "[email protected]"
SMTP_PASSWORD = "yourpassword"
|
Drop the UUID; just use urandom
|
Drop the UUID; just use urandom
|
Python
|
artistic-2.0
|
Rosuav/appension,Rosuav/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension
|
db_connect_string = ""
+ cookie_monster = "uqHHRiRIUyCIcB0RJJcv+T/Qc3wJS0p/jsyE1x36qBIa"
+ # Generated like this:
- cookie_monster = "llsfZyohQDa4kRdCCqnoV3gpD8jaHUY0kfkKI3pZlZ4="
- # in Python you can generate like this:
- # import base64
- # import uuid
- # print(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes))
- # Thanks to https://gist.github.com/didip/823887
- # Alternative way to generate a similar-length nonce:
# import base64, os; print(base64.b64encode(os.urandom(33)))
# These settings are used only for the sending of emails. The server will
# start with them at the defaults, but all email sending will fail.
system_email = '[email protected]'
admin_email = '[email protected]'
# Will use default settings if SMTP_SERVER_PORT == 'localhost'
SMTP_SERVER_PORT = "smtp.gmail.com:587"
SMTP_USERNAME = "[email protected]"
SMTP_PASSWORD = "yourpassword"
|
Drop the UUID; just use urandom
|
## Code Before:
db_connect_string = ""
cookie_monster = "llsfZyohQDa4kRdCCqnoV3gpD8jaHUY0kfkKI3pZlZ4="
# in Python you can generate like this:
# import base64
# import uuid
# print(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes))
# Thanks to https://gist.github.com/didip/823887
# Alternative way to generate a similar-length nonce:
# import base64, os; print(base64.b64encode(os.urandom(33)))
# These settings are used only for the sending of emails. The server will
# start with them at the defaults, but all email sending will fail.
system_email = '[email protected]'
admin_email = '[email protected]'
# Will use default settings if SMTP_SERVER_PORT == 'localhost'
SMTP_SERVER_PORT = "smtp.gmail.com:587"
SMTP_USERNAME = "[email protected]"
SMTP_PASSWORD = "yourpassword"
## Instruction:
Drop the UUID; just use urandom
## Code After:
db_connect_string = ""
cookie_monster = "uqHHRiRIUyCIcB0RJJcv+T/Qc3wJS0p/jsyE1x36qBIa"
# Generated like this:
# import base64, os; print(base64.b64encode(os.urandom(33)))
# These settings are used only for the sending of emails. The server will
# start with them at the defaults, but all email sending will fail.
system_email = '[email protected]'
admin_email = '[email protected]'
# Will use default settings if SMTP_SERVER_PORT == 'localhost'
SMTP_SERVER_PORT = "smtp.gmail.com:587"
SMTP_USERNAME = "[email protected]"
SMTP_PASSWORD = "yourpassword"
|
// ... existing code ...
db_connect_string = ""
cookie_monster = "uqHHRiRIUyCIcB0RJJcv+T/Qc3wJS0p/jsyE1x36qBIa"
# Generated like this:
# import base64, os; print(base64.b64encode(os.urandom(33)))
// ... rest of the code ...
|
f3eee368e13ee37048d52bde0d067efea057fef8
|
monkeylearn/extraction.py
|
monkeylearn/extraction.py
|
from __future__ import (
print_function, unicode_literals, division, absolute_import)
from six.moves import range
from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin
from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE
class Extraction(SleepRequestsMixin, HandleErrorsMixin):
def __init__(self, token, base_endpoint=DEFAULT_BASE_ENDPOINT):
self.token = token
self.endpoint = base_endpoint + 'extractors/'
def extract(self, module_id, text_list, batch_size=DEFAULT_BATCH_SIZE,
sleep_if_throttled=True):
text_list = list(text_list)
self.check_batch_limits(text_list, batch_size)
url = self.endpoint + module_id + '/extract/'
res = []
responses = []
for i in range(0, len(text_list), batch_size):
data = {
'text_list': text_list[i:i+batch_size]
}
response = self.make_request(url, 'POST', data, sleep_if_throttled)
self.handle_errors(response)
responses.append(response)
res.extend(response.json()['result'])
return MonkeyLearnResponse(res, responses)
|
from __future__ import (
print_function, unicode_literals, division, absolute_import)
from six.moves import range
from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin
from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE
class Extraction(SleepRequestsMixin, HandleErrorsMixin):
def __init__(self, token, base_endpoint=DEFAULT_BASE_ENDPOINT):
self.token = token
self.endpoint = base_endpoint + 'extractors/'
def extract(self, module_id, text_list, batch_size=DEFAULT_BATCH_SIZE,
sleep_if_throttled=True):
text_list = list(text_list)
self.check_batch_limits(text_list, batch_size)
url = self.endpoint + module_id + '/extract/'
res = []
responses = []
for i in range(0, len(text_list), batch_size):
data = {
'text_list': text_list[i:i+batch_size]
}
if kwargs is not None:
for key, value in kwargs.iteritems():
data[key] = value
response = self.make_request(url, 'POST', data, sleep_if_throttled)
self.handle_errors(response)
responses.append(response)
res.extend(response.json()['result'])
return MonkeyLearnResponse(res, responses)
|
Support for extra parameters in extractors
|
Support for extra parameters in extractors
|
Python
|
mit
|
monkeylearn/monkeylearn-python
|
from __future__ import (
print_function, unicode_literals, division, absolute_import)
from six.moves import range
from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin
from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE
class Extraction(SleepRequestsMixin, HandleErrorsMixin):
def __init__(self, token, base_endpoint=DEFAULT_BASE_ENDPOINT):
self.token = token
self.endpoint = base_endpoint + 'extractors/'
def extract(self, module_id, text_list, batch_size=DEFAULT_BATCH_SIZE,
sleep_if_throttled=True):
text_list = list(text_list)
self.check_batch_limits(text_list, batch_size)
url = self.endpoint + module_id + '/extract/'
res = []
responses = []
for i in range(0, len(text_list), batch_size):
data = {
'text_list': text_list[i:i+batch_size]
}
+ if kwargs is not None:
+ for key, value in kwargs.iteritems():
+ data[key] = value
response = self.make_request(url, 'POST', data, sleep_if_throttled)
self.handle_errors(response)
responses.append(response)
res.extend(response.json()['result'])
return MonkeyLearnResponse(res, responses)
|
Support for extra parameters in extractors
|
## Code Before:
from __future__ import (
print_function, unicode_literals, division, absolute_import)
from six.moves import range
from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin
from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE
class Extraction(SleepRequestsMixin, HandleErrorsMixin):
def __init__(self, token, base_endpoint=DEFAULT_BASE_ENDPOINT):
self.token = token
self.endpoint = base_endpoint + 'extractors/'
def extract(self, module_id, text_list, batch_size=DEFAULT_BATCH_SIZE,
sleep_if_throttled=True):
text_list = list(text_list)
self.check_batch_limits(text_list, batch_size)
url = self.endpoint + module_id + '/extract/'
res = []
responses = []
for i in range(0, len(text_list), batch_size):
data = {
'text_list': text_list[i:i+batch_size]
}
response = self.make_request(url, 'POST', data, sleep_if_throttled)
self.handle_errors(response)
responses.append(response)
res.extend(response.json()['result'])
return MonkeyLearnResponse(res, responses)
## Instruction:
Support for extra parameters in extractors
## Code After:
from __future__ import (
print_function, unicode_literals, division, absolute_import)
from six.moves import range
from monkeylearn.utils import SleepRequestsMixin, MonkeyLearnResponse, HandleErrorsMixin
from monkeylearn.settings import DEFAULT_BASE_ENDPOINT, DEFAULT_BATCH_SIZE
class Extraction(SleepRequestsMixin, HandleErrorsMixin):
def __init__(self, token, base_endpoint=DEFAULT_BASE_ENDPOINT):
self.token = token
self.endpoint = base_endpoint + 'extractors/'
def extract(self, module_id, text_list, batch_size=DEFAULT_BATCH_SIZE,
sleep_if_throttled=True):
text_list = list(text_list)
self.check_batch_limits(text_list, batch_size)
url = self.endpoint + module_id + '/extract/'
res = []
responses = []
for i in range(0, len(text_list), batch_size):
data = {
'text_list': text_list[i:i+batch_size]
}
if kwargs is not None:
for key, value in kwargs.iteritems():
data[key] = value
response = self.make_request(url, 'POST', data, sleep_if_throttled)
self.handle_errors(response)
responses.append(response)
res.extend(response.json()['result'])
return MonkeyLearnResponse(res, responses)
|
# ... existing code ...
}
if kwargs is not None:
for key, value in kwargs.iteritems():
data[key] = value
response = self.make_request(url, 'POST', data, sleep_if_throttled)
# ... rest of the code ...
|
70e4c1fe5faefd87d19fa0067010cfdbeb7576c2
|
tests/models.py
|
tests/models.py
|
from django.db import models
from enumfields import Enum, EnumField
class MyModel(models.Model):
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
color = EnumField(Color, max_length=1)
|
from django.db import models
from enum import Enum
from enumfields import EnumField
class MyModel(models.Model):
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
color = EnumField(Color, max_length=1)
|
Use regular Enums in tests
|
Use regular Enums in tests
|
Python
|
mit
|
jessamynsmith/django-enumfields,suutari-ai/django-enumfields,bxm156/django-enumfields,jackyyf/django-enumfields
|
from django.db import models
+ from enum import Enum
- from enumfields import Enum, EnumField
+ from enumfields import EnumField
class MyModel(models.Model):
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
color = EnumField(Color, max_length=1)
|
Use regular Enums in tests
|
## Code Before:
from django.db import models
from enumfields import Enum, EnumField
class MyModel(models.Model):
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
color = EnumField(Color, max_length=1)
## Instruction:
Use regular Enums in tests
## Code After:
from django.db import models
from enum import Enum
from enumfields import EnumField
class MyModel(models.Model):
class Color(Enum):
RED = 'r'
GREEN = 'g'
BLUE = 'b'
color = EnumField(Color, max_length=1)
|
// ... existing code ...
from django.db import models
from enum import Enum
from enumfields import EnumField
// ... rest of the code ...
|
9cd72406d63d1ce3a6cd75a65131c8bde3df95ba
|
push_plugin.py
|
push_plugin.py
|
import requests
class PushClient:
def __init__(self, app):
self.app = app
def handle_new_or_edit(self, post):
data = { 'hub.mode' : 'publish',
'hub.url' : 'http://kylewm.com/all.atom' }
response = requests.post('https://pubsubhubbub.appspot.com/', data)
if response.status_code == 204:
self.app.logger.info('successfully sent PuSH notification')
|
import requests
class PushClient:
def __init__(self, app):
self.app = app
def publish(self, url):
data = { 'hub.mode' : 'publish', 'hub.url' : url }
response = requests.post('https://pubsubhubbub.appspot.com/', data)
if response.status_code == 204:
self.app.logger.info('successfully sent PuSH notification')
else:
self.app.logger.warn('unexpected response from PuSH hub %s', response)
def handle_new_or_edit(self, post):
self.publish('http://kylewm.com/all.atom')
if post.post_type=='article':
self.publish('http://kylewm.com/articles.atom')
elif post.post_type=='note':
self.publish('http://kylewm.com/notes.atom')
|
Send the all.atom feed and the articles/notes feeds to PuSH
|
Send the all.atom feed and the articles/notes feeds to PuSH
|
Python
|
bsd-2-clause
|
thedod/redwind,Lancey6/redwind,thedod/redwind,Lancey6/redwind,Lancey6/redwind
|
import requests
class PushClient:
def __init__(self, app):
self.app = app
- def handle_new_or_edit(self, post):
+ def publish(self, url):
- data = { 'hub.mode' : 'publish',
+ data = { 'hub.mode' : 'publish', 'hub.url' : url }
- 'hub.url' : 'http://kylewm.com/all.atom' }
response = requests.post('https://pubsubhubbub.appspot.com/', data)
if response.status_code == 204:
self.app.logger.info('successfully sent PuSH notification')
+ else:
+ self.app.logger.warn('unexpected response from PuSH hub %s', response)
+
+ def handle_new_or_edit(self, post):
+ self.publish('http://kylewm.com/all.atom')
+ if post.post_type=='article':
+ self.publish('http://kylewm.com/articles.atom')
+ elif post.post_type=='note':
+ self.publish('http://kylewm.com/notes.atom')
+
|
Send the all.atom feed and the articles/notes feeds to PuSH
|
## Code Before:
import requests
class PushClient:
def __init__(self, app):
self.app = app
def handle_new_or_edit(self, post):
data = { 'hub.mode' : 'publish',
'hub.url' : 'http://kylewm.com/all.atom' }
response = requests.post('https://pubsubhubbub.appspot.com/', data)
if response.status_code == 204:
self.app.logger.info('successfully sent PuSH notification')
## Instruction:
Send the all.atom feed and the articles/notes feeds to PuSH
## Code After:
import requests
class PushClient:
def __init__(self, app):
self.app = app
def publish(self, url):
data = { 'hub.mode' : 'publish', 'hub.url' : url }
response = requests.post('https://pubsubhubbub.appspot.com/', data)
if response.status_code == 204:
self.app.logger.info('successfully sent PuSH notification')
else:
self.app.logger.warn('unexpected response from PuSH hub %s', response)
def handle_new_or_edit(self, post):
self.publish('http://kylewm.com/all.atom')
if post.post_type=='article':
self.publish('http://kylewm.com/articles.atom')
elif post.post_type=='note':
self.publish('http://kylewm.com/notes.atom')
|
# ... existing code ...
def publish(self, url):
data = { 'hub.mode' : 'publish', 'hub.url' : url }
response = requests.post('https://pubsubhubbub.appspot.com/', data)
# ... modified code ...
self.app.logger.info('successfully sent PuSH notification')
else:
self.app.logger.warn('unexpected response from PuSH hub %s', response)
def handle_new_or_edit(self, post):
self.publish('http://kylewm.com/all.atom')
if post.post_type=='article':
self.publish('http://kylewm.com/articles.atom')
elif post.post_type=='note':
self.publish('http://kylewm.com/notes.atom')
# ... rest of the code ...
|
6f7890c8b29670f613b6a551ebac2b383f3a7a64
|
tests/test_recipes.py
|
tests/test_recipes.py
|
import unittest
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
from brew.recipes import Recipe
from fixtures import grain_additions
from fixtures import hop_additions
from fixtures import recipe
class TestRecipe(unittest.TestCase):
def setUp(self):
# Define Grains
self.grain_additions = grain_additions
# Define Hops
self.hop_additions = hop_additions
# Define Recipes
self.recipe = recipe
def test_str(self):
out = str(self.recipe)
self.assertEquals(out, 'pale ale')
def test_set_units(self):
self.assertEquals(self.recipe.units, IMPERIAL_UNITS)
self.recipe.set_units(SI_UNITS)
self.assertEquals(self.recipe.units, SI_UNITS)
def test_set_raises(self):
with self.assertRaises(Exception):
self.recipe.set_units('bad')
def test_validate(self):
data = self.recipe.to_dict()
Recipe.validate(data)
|
import unittest
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
from brew.recipes import Recipe
from fixtures import grain_additions
from fixtures import hop_additions
from fixtures import recipe
from fixtures import yeast
class TestRecipe(unittest.TestCase):
def setUp(self):
# Define Grains
self.grain_additions = grain_additions
# Define Hops
self.hop_additions = hop_additions
# Define Yeast
self.yeast = yeast
# Define Recipes
self.recipe = recipe
def test_str(self):
out = str(self.recipe)
self.assertEquals(out, 'pale ale')
def test_set_units(self):
self.assertEquals(self.recipe.units, IMPERIAL_UNITS)
self.recipe.set_units(SI_UNITS)
self.assertEquals(self.recipe.units, SI_UNITS)
def test_set_raises(self):
with self.assertRaises(Exception):
self.recipe.set_units('bad')
def test_grains_units_mismatch_raises(self):
grain_additions = [g.change_units() for g in self.grain_additions]
with self.assertRaises(Exception):
Recipe(name='pale ale',
grain_additions=grain_additions,
hop_additions=self.hop_additions,
yeast=self.yeast)
def test_hops_units_mismatch_raises(self):
hop_additions = [h.change_units() for h in self.hop_additions]
with self.assertRaises(Exception):
Recipe(name='pale ale',
grain_additions=self.grain_additions,
hop_additions=hop_additions,
yeast=self.yeast)
def test_validate(self):
data = self.recipe.to_dict()
Recipe.validate(data)
|
Test units mismatch in recipe
|
Test units mismatch in recipe
|
Python
|
mit
|
chrisgilmerproj/brewday,chrisgilmerproj/brewday
|
import unittest
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
from brew.recipes import Recipe
from fixtures import grain_additions
from fixtures import hop_additions
from fixtures import recipe
+ from fixtures import yeast
class TestRecipe(unittest.TestCase):
def setUp(self):
# Define Grains
self.grain_additions = grain_additions
# Define Hops
self.hop_additions = hop_additions
+
+ # Define Yeast
+ self.yeast = yeast
# Define Recipes
self.recipe = recipe
def test_str(self):
out = str(self.recipe)
self.assertEquals(out, 'pale ale')
def test_set_units(self):
self.assertEquals(self.recipe.units, IMPERIAL_UNITS)
self.recipe.set_units(SI_UNITS)
self.assertEquals(self.recipe.units, SI_UNITS)
def test_set_raises(self):
with self.assertRaises(Exception):
self.recipe.set_units('bad')
+ def test_grains_units_mismatch_raises(self):
+ grain_additions = [g.change_units() for g in self.grain_additions]
+ with self.assertRaises(Exception):
+ Recipe(name='pale ale',
+ grain_additions=grain_additions,
+ hop_additions=self.hop_additions,
+ yeast=self.yeast)
+
+ def test_hops_units_mismatch_raises(self):
+ hop_additions = [h.change_units() for h in self.hop_additions]
+ with self.assertRaises(Exception):
+ Recipe(name='pale ale',
+ grain_additions=self.grain_additions,
+ hop_additions=hop_additions,
+ yeast=self.yeast)
+
def test_validate(self):
data = self.recipe.to_dict()
Recipe.validate(data)
|
Test units mismatch in recipe
|
## Code Before:
import unittest
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
from brew.recipes import Recipe
from fixtures import grain_additions
from fixtures import hop_additions
from fixtures import recipe
class TestRecipe(unittest.TestCase):
def setUp(self):
# Define Grains
self.grain_additions = grain_additions
# Define Hops
self.hop_additions = hop_additions
# Define Recipes
self.recipe = recipe
def test_str(self):
out = str(self.recipe)
self.assertEquals(out, 'pale ale')
def test_set_units(self):
self.assertEquals(self.recipe.units, IMPERIAL_UNITS)
self.recipe.set_units(SI_UNITS)
self.assertEquals(self.recipe.units, SI_UNITS)
def test_set_raises(self):
with self.assertRaises(Exception):
self.recipe.set_units('bad')
def test_validate(self):
data = self.recipe.to_dict()
Recipe.validate(data)
## Instruction:
Test units mismatch in recipe
## Code After:
import unittest
from brew.constants import IMPERIAL_UNITS
from brew.constants import SI_UNITS
from brew.recipes import Recipe
from fixtures import grain_additions
from fixtures import hop_additions
from fixtures import recipe
from fixtures import yeast
class TestRecipe(unittest.TestCase):
def setUp(self):
# Define Grains
self.grain_additions = grain_additions
# Define Hops
self.hop_additions = hop_additions
# Define Yeast
self.yeast = yeast
# Define Recipes
self.recipe = recipe
def test_str(self):
out = str(self.recipe)
self.assertEquals(out, 'pale ale')
def test_set_units(self):
self.assertEquals(self.recipe.units, IMPERIAL_UNITS)
self.recipe.set_units(SI_UNITS)
self.assertEquals(self.recipe.units, SI_UNITS)
def test_set_raises(self):
with self.assertRaises(Exception):
self.recipe.set_units('bad')
def test_grains_units_mismatch_raises(self):
grain_additions = [g.change_units() for g in self.grain_additions]
with self.assertRaises(Exception):
Recipe(name='pale ale',
grain_additions=grain_additions,
hop_additions=self.hop_additions,
yeast=self.yeast)
def test_hops_units_mismatch_raises(self):
hop_additions = [h.change_units() for h in self.hop_additions]
with self.assertRaises(Exception):
Recipe(name='pale ale',
grain_additions=self.grain_additions,
hop_additions=hop_additions,
yeast=self.yeast)
def test_validate(self):
data = self.recipe.to_dict()
Recipe.validate(data)
|
...
from fixtures import recipe
from fixtures import yeast
...
self.hop_additions = hop_additions
# Define Yeast
self.yeast = yeast
...
def test_grains_units_mismatch_raises(self):
grain_additions = [g.change_units() for g in self.grain_additions]
with self.assertRaises(Exception):
Recipe(name='pale ale',
grain_additions=grain_additions,
hop_additions=self.hop_additions,
yeast=self.yeast)
def test_hops_units_mismatch_raises(self):
hop_additions = [h.change_units() for h in self.hop_additions]
with self.assertRaises(Exception):
Recipe(name='pale ale',
grain_additions=self.grain_additions,
hop_additions=hop_additions,
yeast=self.yeast)
def test_validate(self):
...
|
163cfea2a0c5e7d96dd870aa540c95a2ffa139f9
|
appstats/filters.py
|
appstats/filters.py
|
import json
def json_filter(value):
return json.dumps(value)
def count_filter(value):
if value is None:
return ""
count = float(value)
base = 1000
prefixes = [
('K'),
('M'),
('G'),
('T'),
('P'),
('E'),
('Z'),
('Y')
]
if count < base:
return '%.1f' % count
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if count < unit:
return '%.1f %s' % ((base * count / unit), prefix)
return '%.1f %s' % ((base * count / unit), prefix)
def time_filter(value):
if value is None:
return ""
time = float(value)
# Transform secs into ms
time = value * 1000
if time < 1000:
return '%.1f ms' % time
else:
time /= 1000
if time < 60:
return '%.1f s' % time
else:
time /= 60
if time < 60:
return '%.1f m' % time
else:
time /= 60
if time < 24:
return '%.1f h' % time
else:
time /= 24
return'%.1f d' % time
def default_filter(value):
if value is None:
return ""
return value
|
import json
def json_filter(value):
return json.dumps(value)
def count_filter(value):
if value is None:
return ""
count = float(value)
base = 1000
prefixes = [
('K'),
('M'),
('G'),
('T'),
('P'),
('E'),
('Z'),
('Y')
]
if count < base:
return '%.1f' % count
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if count < unit:
return '%.1f %s' % ((base * count / unit), prefix)
return '%.1f %s' % ((base * count / unit), prefix)
def time_filter(value):
if value is None:
return ""
# Transform secs into ms
time = float(value) * 1000
if time < 1000:
return '%.1f ms' % time
else:
time /= 1000
if time < 60:
return '%.1f s' % time
else:
time /= 60
if time < 60:
return '%.1f m' % time
else:
time /= 60
if time < 24:
return '%.1f h' % time
else:
time /= 24
return'%.1f d' % time
def default_filter(value):
if value is None:
return ""
return value
|
Join two lines in one
|
Join two lines in one
|
Python
|
mit
|
uvNikita/appstats,uvNikita/appstats,uvNikita/appstats
|
import json
def json_filter(value):
return json.dumps(value)
def count_filter(value):
if value is None:
return ""
count = float(value)
base = 1000
prefixes = [
('K'),
('M'),
('G'),
('T'),
('P'),
('E'),
('Z'),
('Y')
]
if count < base:
return '%.1f' % count
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if count < unit:
return '%.1f %s' % ((base * count / unit), prefix)
return '%.1f %s' % ((base * count / unit), prefix)
def time_filter(value):
if value is None:
return ""
- time = float(value)
# Transform secs into ms
- time = value * 1000
+ time = float(value) * 1000
if time < 1000:
return '%.1f ms' % time
else:
time /= 1000
if time < 60:
return '%.1f s' % time
else:
time /= 60
if time < 60:
return '%.1f m' % time
else:
time /= 60
if time < 24:
return '%.1f h' % time
else:
time /= 24
return'%.1f d' % time
def default_filter(value):
if value is None:
return ""
return value
|
Join two lines in one
|
## Code Before:
import json
def json_filter(value):
return json.dumps(value)
def count_filter(value):
if value is None:
return ""
count = float(value)
base = 1000
prefixes = [
('K'),
('M'),
('G'),
('T'),
('P'),
('E'),
('Z'),
('Y')
]
if count < base:
return '%.1f' % count
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if count < unit:
return '%.1f %s' % ((base * count / unit), prefix)
return '%.1f %s' % ((base * count / unit), prefix)
def time_filter(value):
if value is None:
return ""
time = float(value)
# Transform secs into ms
time = value * 1000
if time < 1000:
return '%.1f ms' % time
else:
time /= 1000
if time < 60:
return '%.1f s' % time
else:
time /= 60
if time < 60:
return '%.1f m' % time
else:
time /= 60
if time < 24:
return '%.1f h' % time
else:
time /= 24
return'%.1f d' % time
def default_filter(value):
if value is None:
return ""
return value
## Instruction:
Join two lines in one
## Code After:
import json
def json_filter(value):
return json.dumps(value)
def count_filter(value):
if value is None:
return ""
count = float(value)
base = 1000
prefixes = [
('K'),
('M'),
('G'),
('T'),
('P'),
('E'),
('Z'),
('Y')
]
if count < base:
return '%.1f' % count
else:
for i, prefix in enumerate(prefixes):
unit = base ** (i + 2)
if count < unit:
return '%.1f %s' % ((base * count / unit), prefix)
return '%.1f %s' % ((base * count / unit), prefix)
def time_filter(value):
if value is None:
return ""
# Transform secs into ms
time = float(value) * 1000
if time < 1000:
return '%.1f ms' % time
else:
time /= 1000
if time < 60:
return '%.1f s' % time
else:
time /= 60
if time < 60:
return '%.1f m' % time
else:
time /= 60
if time < 24:
return '%.1f h' % time
else:
time /= 24
return'%.1f d' % time
def default_filter(value):
if value is None:
return ""
return value
|
...
return ""
# Transform secs into ms
time = float(value) * 1000
if time < 1000:
...
|
d495d9500377bad5c7ccfd15037fb4d03fd7bff3
|
videolog/user.py
|
videolog/user.py
|
from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user):
content = self._make_request('GET', '/usuario/%s/videos.json' % user)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response
|
from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user, privacy=None):
path = '/usuario/%s/videos.json' % user
if privacy is not None:
path = "%s?privacidade=%s" % (path, privacy)
content = self._make_request('GET', path)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response
|
Add privacy parameter to User.find_videos
|
Add privacy parameter to User.find_videos
|
Python
|
mit
|
rcmachado/pyvideolog
|
from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
- def find_videos(self, user):
+ def find_videos(self, user, privacy=None):
- content = self._make_request('GET', '/usuario/%s/videos.json' % user)
+ path = '/usuario/%s/videos.json' % user
+ if privacy is not None:
+ path = "%s?privacidade=%s" % (path, privacy)
+
+ content = self._make_request('GET', path)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response
|
Add privacy parameter to User.find_videos
|
## Code Before:
from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user):
content = self._make_request('GET', '/usuario/%s/videos.json' % user)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response
## Instruction:
Add privacy parameter to User.find_videos
## Code After:
from datetime import datetime
import time
import json
from videolog.core import Videolog
class User(Videolog):
def find_videos(self, user, privacy=None):
path = '/usuario/%s/videos.json' % user
if privacy is not None:
path = "%s?privacidade=%s" % (path, privacy)
content = self._make_request('GET', path)
usuario = json.loads(content)
response = []
for video in usuario['usuario']['videos']:
video['criacao'] = datetime.strptime(video['criacao'], "%Y-%m-%dT%H:%M:%S")
video["duracao"] = time.strptime("00:00:05", "%H:%M:%S")
if video['mobile'].lower() == "s":
video['mobile'] = True
else:
video['mobile'] = False
response.append(video)
return response
|
...
class User(Videolog):
def find_videos(self, user, privacy=None):
path = '/usuario/%s/videos.json' % user
if privacy is not None:
path = "%s?privacidade=%s" % (path, privacy)
content = self._make_request('GET', path)
usuario = json.loads(content)
...
|
6be70d01bdf58389db2a6adc4035f82669d02a61
|
cms/plugins/googlemap/cms_plugins.py
|
cms/plugins/googlemap/cms_plugins.py
|
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.googlemap.models import GoogleMap
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
from cms.plugins.googlemap import settings
from django.forms.widgets import Media
class GoogleMapPlugin(CMSPluginBase):
model = GoogleMap
name = _("Google Map")
render_template = "cms/plugins/googlemap.html"
def render(self, context, instance, placeholder):
context.update({
'object':instance,
'placeholder':placeholder,
})
return context
def get_plugin_media(self, request, context, plugin):
if 'GOOGLE_MAPS_API_KEY' in context:
key = context['GOOGLE_MAPS_API_KEY']
else:
key = GOOGLE_MAPS_API_KEY
return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, request.LANGUAGE_CODE),))
plugin_pool.register_plugin(GoogleMapPlugin)
|
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.googlemap.models import GoogleMap
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
from django.forms.widgets import Media
class GoogleMapPlugin(CMSPluginBase):
model = GoogleMap
name = _("Google Map")
render_template = "cms/plugins/googlemap.html"
def render(self, context, instance, placeholder):
context.update({
'object':instance,
'placeholder':placeholder,
})
return context
def get_plugin_media(self, request, context, plugin):
if 'GOOGLE_MAPS_API_KEY' in context:
key = context['GOOGLE_MAPS_API_KEY']
else:
key = GOOGLE_MAPS_API_KEY
lang = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE[0:2])
return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, lang),))
plugin_pool.register_plugin(GoogleMapPlugin)
|
Allow use of GoogleMaps plugin without Multilingual support
|
Allow use of GoogleMaps plugin without Multilingual support
|
Python
|
bsd-3-clause
|
cyberintruder/django-cms,chmberl/django-cms,owers19856/django-cms,jproffitt/django-cms,vstoykov/django-cms,MagicSolutions/django-cms,isotoma/django-cms,jproffitt/django-cms,chkir/django-cms,stefanw/django-cms,jeffreylu9/django-cms,divio/django-cms,Vegasvikk/django-cms,jrief/django-cms,pbs/django-cms,farhaadila/django-cms,chrisglass/django-cms,kk9599/django-cms,nimbis/django-cms,rsalmaso/django-cms,vad/django-cms,rscnt/django-cms,memnonila/django-cms,intip/django-cms,MagicSolutions/django-cms,stefanfoulis/django-cms,jrclaramunt/django-cms,SinnerSchraderMobileMirrors/django-cms,selecsosi/django-cms,donce/django-cms,liuyisiyisi/django-cms,jeffreylu9/django-cms,pbs/django-cms,liuyisiyisi/django-cms,jrclaramunt/django-cms,divio/django-cms,stefanfoulis/django-cms,astagi/django-cms,datakortet/django-cms,intip/django-cms,DylannCordel/django-cms,frnhr/django-cms,adaptivelogic/django-cms,stefanw/django-cms,qnub/django-cms,timgraham/django-cms,stefanw/django-cms,memnonila/django-cms,mkoistinen/django-cms,jeffreylu9/django-cms,vad/django-cms,AlexProfi/django-cms,intgr/django-cms,ojii/django-cms,sephii/django-cms,philippze/django-cms,rscnt/django-cms,kk9599/django-cms,pbs/django-cms,jsma/django-cms,astagi/django-cms,rscnt/django-cms,czpython/django-cms,jeffreylu9/django-cms,foobacca/django-cms,foobacca/django-cms,selecsosi/django-cms,donce/django-cms,SinnerSchraderMobileMirrors/django-cms,SachaMPS/django-cms,chkir/django-cms,11craft/django-cms,youprofit/django-cms,petecummings/django-cms,wyg3958/django-cms,frnhr/django-cms,foobacca/django-cms,pixbuffer/django-cms,datakortet/django-cms,vxsx/django-cms,datakortet/django-cms,driesdesmet/django-cms,bittner/django-cms,astagi/django-cms,netzkolchose/django-cms,owers19856/django-cms,netzkolchose/django-cms,wuzhihui1123/django-cms,wyg3958/django-cms,cyberintruder/django-cms,SofiaReis/django-cms,benzkji/django-cms,nimbis/django-cms,rryan/django-cms,takeshineshiro/django-cms,robmagee/django-cms,FinalAngel/django-cms,nostalgiaz/django-cms,andyzsf/django-cms,frnhr/django-cms,adaptivelogic/django-cms,dhorelik/django-cms,iddqd1/django-cms,jsma/django-cms,frnhr/django-cms,11craft/django-cms,saintbird/django-cms,adaptivelogic/django-cms,memnonila/django-cms,jrief/django-cms,pbs/django-cms,takeshineshiro/django-cms,MagicSolutions/django-cms,Vegasvikk/django-cms,evildmp/django-cms,AlexProfi/django-cms,jsma/django-cms,divio/django-cms,rsalmaso/django-cms,isotoma/django-cms,petecummings/django-cms,vxsx/django-cms,Livefyre/django-cms,11craft/django-cms,liuyisiyisi/django-cms,jalaziz/django-cms-grappelli-old,keimlink/django-cms,czpython/django-cms,keimlink/django-cms,stefanfoulis/django-cms,petecummings/django-cms,takeshineshiro/django-cms,ScholzVolkmer/django-cms,timgraham/django-cms,chkir/django-cms,foobacca/django-cms,stefanw/django-cms,jalaziz/django-cms-grappelli-old,rryan/django-cms,ScholzVolkmer/django-cms,qnub/django-cms,benzkji/django-cms,ScholzVolkmer/django-cms,kk9599/django-cms,nimbis/django-cms,webu/django-cms,nostalgiaz/django-cms,nostalgiaz/django-cms,vad/django-cms,mkoistinen/django-cms,selecsosi/django-cms,jsma/django-cms,keimlink/django-cms,timgraham/django-cms,yakky/django-cms,isotoma/django-cms,vxsx/django-cms,jrclaramunt/django-cms,intgr/django-cms,pancentric/django-cms,sznekol/django-cms,pixbuffer/django-cms,leture/django-cms,mkoistinen/django-cms,irudayarajisawa/django-cms,czpython/django-cms,intip/django-cms,Jaccorot/django-cms,sephii/django-cms,irudayarajisawa/django-cms,jproffitt/django-cms,wuzhihui1123/django-cms,vstoykov/django-cms,rsalmaso/django-cms,farhaadila/django-cms,vad/django-cms,SofiaReis/django-cms,360youlun/django-cms,DylannCordel/django-cms,intgr/django-cms,jrief/django-cms,leture/django-cms,SofiaReis/django-cms,yakky/django-cms,Vegasvikk/django-cms,owers19856/django-cms,mkoistinen/django-cms,saintbird/django-cms,yakky/django-cms,jrief/django-cms,robmagee/django-cms,pixbuffer/django-cms,philippze/django-cms,saintbird/django-cms,ojii/django-cms,360youlun/django-cms,webu/django-cms,sznekol/django-cms,dhorelik/django-cms,wuzhihui1123/django-cms,evildmp/django-cms,yakky/django-cms,Livefyre/django-cms,netzkolchose/django-cms,josjevv/django-cms,bittner/django-cms,rryan/django-cms,SmithsonianEnterprises/django-cms,evildmp/django-cms,farhaadila/django-cms,nimbis/django-cms,sznekol/django-cms,ojii/django-cms,sephii/django-cms,Livefyre/django-cms,rryan/django-cms,FinalAngel/django-cms,jalaziz/django-cms-grappelli-old,FinalAngel/django-cms,bittner/django-cms,SachaMPS/django-cms,webu/django-cms,pancentric/django-cms,driesdesmet/django-cms,benzkji/django-cms,divio/django-cms,isotoma/django-cms,VillageAlliance/django-cms,iddqd1/django-cms,intip/django-cms,evildmp/django-cms,chrisglass/django-cms,benzkji/django-cms,360youlun/django-cms,sephii/django-cms,pancentric/django-cms,datakortet/django-cms,dhorelik/django-cms,cyberintruder/django-cms,andyzsf/django-cms,iddqd1/django-cms,andyzsf/django-cms,SachaMPS/django-cms,czpython/django-cms,nostalgiaz/django-cms,robmagee/django-cms,vstoykov/django-cms,chmberl/django-cms,philippze/django-cms,wyg3958/django-cms,intgr/django-cms,andyzsf/django-cms,leture/django-cms,chmberl/django-cms,vxsx/django-cms,Livefyre/django-cms,FinalAngel/django-cms,DylannCordel/django-cms,josjevv/django-cms,11craft/django-cms,jproffitt/django-cms,selecsosi/django-cms,irudayarajisawa/django-cms,youprofit/django-cms,VillageAlliance/django-cms,rsalmaso/django-cms,netzkolchose/django-cms,SinnerSchraderMobileMirrors/django-cms,bittner/django-cms,VillageAlliance/django-cms,Jaccorot/django-cms,driesdesmet/django-cms,SmithsonianEnterprises/django-cms,donce/django-cms,youprofit/django-cms,AlexProfi/django-cms,wuzhihui1123/django-cms,qnub/django-cms,stefanfoulis/django-cms,Jaccorot/django-cms,josjevv/django-cms,SmithsonianEnterprises/django-cms
|
+ from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.googlemap.models import GoogleMap
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
- from cms.plugins.googlemap import settings
from django.forms.widgets import Media
class GoogleMapPlugin(CMSPluginBase):
model = GoogleMap
name = _("Google Map")
render_template = "cms/plugins/googlemap.html"
def render(self, context, instance, placeholder):
context.update({
'object':instance,
'placeholder':placeholder,
})
return context
def get_plugin_media(self, request, context, plugin):
if 'GOOGLE_MAPS_API_KEY' in context:
key = context['GOOGLE_MAPS_API_KEY']
else:
key = GOOGLE_MAPS_API_KEY
+ lang = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE[0:2])
- return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, request.LANGUAGE_CODE),))
+ return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, lang),))
-
+
plugin_pool.register_plugin(GoogleMapPlugin)
|
Allow use of GoogleMaps plugin without Multilingual support
|
## Code Before:
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.googlemap.models import GoogleMap
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
from cms.plugins.googlemap import settings
from django.forms.widgets import Media
class GoogleMapPlugin(CMSPluginBase):
model = GoogleMap
name = _("Google Map")
render_template = "cms/plugins/googlemap.html"
def render(self, context, instance, placeholder):
context.update({
'object':instance,
'placeholder':placeholder,
})
return context
def get_plugin_media(self, request, context, plugin):
if 'GOOGLE_MAPS_API_KEY' in context:
key = context['GOOGLE_MAPS_API_KEY']
else:
key = GOOGLE_MAPS_API_KEY
return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, request.LANGUAGE_CODE),))
plugin_pool.register_plugin(GoogleMapPlugin)
## Instruction:
Allow use of GoogleMaps plugin without Multilingual support
## Code After:
from django.conf import settings
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from django.utils.translation import ugettext_lazy as _
from cms.plugins.googlemap.models import GoogleMap
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
from django.forms.widgets import Media
class GoogleMapPlugin(CMSPluginBase):
model = GoogleMap
name = _("Google Map")
render_template = "cms/plugins/googlemap.html"
def render(self, context, instance, placeholder):
context.update({
'object':instance,
'placeholder':placeholder,
})
return context
def get_plugin_media(self, request, context, plugin):
if 'GOOGLE_MAPS_API_KEY' in context:
key = context['GOOGLE_MAPS_API_KEY']
else:
key = GOOGLE_MAPS_API_KEY
lang = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE[0:2])
return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, lang),))
plugin_pool.register_plugin(GoogleMapPlugin)
|
// ... existing code ...
from django.conf import settings
from cms.plugin_pool import plugin_pool
// ... modified code ...
from cms.plugins.googlemap.settings import GOOGLE_MAPS_API_KEY
from django.forms.widgets import Media
...
key = GOOGLE_MAPS_API_KEY
lang = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE[0:2])
return Media(js = ('http://maps.google.com/maps?file=api&v=2&key=%s&hl=%s' % (key, lang),))
plugin_pool.register_plugin(GoogleMapPlugin)
// ... rest of the code ...
|
2f6e53a12975dc4e15ba8b85e4df409868ec4df9
|
tests/test_utils.py
|
tests/test_utils.py
|
import cStringIO
import sys
import unittest2
from ceilometerclient.common import utils
class UtilsTest(unittest2.TestCase):
def test_prettytable(self):
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
# test that the prettytable output is wellformatted (left-aligned)
columns = ['ID', 'Name']
val = ['Name1', 'another', 'veeeery long']
images = [Struct(**{'id': i ** 16, 'name': val[i]})
for i in range(len(val))]
saved_stdout = sys.stdout
try:
sys.stdout = output_dict = cStringIO.StringIO()
utils.print_dict({'K': 'k', 'Key': 'Value'})
finally:
sys.stdout = saved_stdout
self.assertEqual(output_dict.getvalue(), '''\
+----------+-------+
| Property | Value |
+----------+-------+
| K | k |
| Key | Value |
+----------+-------+
''')
|
import cStringIO
import sys
import unittest2
from ceilometerclient.common import utils
class UtilsTest(unittest2.TestCase):
def test_prettytable(self):
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
# test that the prettytable output is wellformatted (left-aligned)
saved_stdout = sys.stdout
try:
sys.stdout = output_dict = cStringIO.StringIO()
utils.print_dict({'K': 'k', 'Key': 'Value'})
finally:
sys.stdout = saved_stdout
self.assertEqual(output_dict.getvalue(), '''\
+----------+-------+
| Property | Value |
+----------+-------+
| K | k |
| Key | Value |
+----------+-------+
''')
|
Remove unused test code in test_util.py
|
Remove unused test code in test_util.py
This doesn't seem to do anything
Change-Id: Ieba6b5f7229680146f9b3f2ae2f3f2d2b1354376
|
Python
|
apache-2.0
|
citrix-openstack-build/python-ceilometerclient,citrix-openstack-build/python-ceilometerclient
|
import cStringIO
import sys
import unittest2
from ceilometerclient.common import utils
class UtilsTest(unittest2.TestCase):
def test_prettytable(self):
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
# test that the prettytable output is wellformatted (left-aligned)
- columns = ['ID', 'Name']
- val = ['Name1', 'another', 'veeeery long']
- images = [Struct(**{'id': i ** 16, 'name': val[i]})
- for i in range(len(val))]
-
saved_stdout = sys.stdout
try:
sys.stdout = output_dict = cStringIO.StringIO()
utils.print_dict({'K': 'k', 'Key': 'Value'})
finally:
sys.stdout = saved_stdout
self.assertEqual(output_dict.getvalue(), '''\
+----------+-------+
| Property | Value |
+----------+-------+
| K | k |
| Key | Value |
+----------+-------+
''')
|
Remove unused test code in test_util.py
|
## Code Before:
import cStringIO
import sys
import unittest2
from ceilometerclient.common import utils
class UtilsTest(unittest2.TestCase):
def test_prettytable(self):
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
# test that the prettytable output is wellformatted (left-aligned)
columns = ['ID', 'Name']
val = ['Name1', 'another', 'veeeery long']
images = [Struct(**{'id': i ** 16, 'name': val[i]})
for i in range(len(val))]
saved_stdout = sys.stdout
try:
sys.stdout = output_dict = cStringIO.StringIO()
utils.print_dict({'K': 'k', 'Key': 'Value'})
finally:
sys.stdout = saved_stdout
self.assertEqual(output_dict.getvalue(), '''\
+----------+-------+
| Property | Value |
+----------+-------+
| K | k |
| Key | Value |
+----------+-------+
''')
## Instruction:
Remove unused test code in test_util.py
## Code After:
import cStringIO
import sys
import unittest2
from ceilometerclient.common import utils
class UtilsTest(unittest2.TestCase):
def test_prettytable(self):
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
# test that the prettytable output is wellformatted (left-aligned)
saved_stdout = sys.stdout
try:
sys.stdout = output_dict = cStringIO.StringIO()
utils.print_dict({'K': 'k', 'Key': 'Value'})
finally:
sys.stdout = saved_stdout
self.assertEqual(output_dict.getvalue(), '''\
+----------+-------+
| Property | Value |
+----------+-------+
| K | k |
| Key | Value |
+----------+-------+
''')
|
...
# test that the prettytable output is wellformatted (left-aligned)
saved_stdout = sys.stdout
...
|
67ab2070206fc1313e1f83948b6c29565c189861
|
test/features/test_create_pages.py
|
test/features/test_create_pages.py
|
import time
import unittest
from hamcrest import *
from splinter import Browser
from support.stub_server import HttpStub
class test_create_pages(unittest.TestCase):
def setUp(self):
HttpStub.start()
time.sleep(2)
def tearDown(self):
HttpStub.stop()
def test_about_page(self):
with Browser() as browser:
browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html")
assert_that(browser.is_text_present('High-volume services'),
is_(True))
|
import time
import unittest
from hamcrest import *
from splinter import Browser
from support.stub_server import HttpStub
class test_create_pages(unittest.TestCase):
def setUp(self):
HttpStub.start()
time.sleep(2)
def tearDown(self):
HttpStub.stop()
def test_about_page(self):
with Browser('phantomjs', wait_time=3) as browser:
browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html")
assert_that(browser.is_text_present('High-volume services'),
is_(True))
|
Use phantomjs instead of a real browser
|
Use phantomjs instead of a real browser
|
Python
|
mit
|
alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer
|
import time
import unittest
from hamcrest import *
from splinter import Browser
from support.stub_server import HttpStub
class test_create_pages(unittest.TestCase):
def setUp(self):
HttpStub.start()
time.sleep(2)
def tearDown(self):
HttpStub.stop()
def test_about_page(self):
- with Browser() as browser:
+ with Browser('phantomjs', wait_time=3) as browser:
browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html")
assert_that(browser.is_text_present('High-volume services'),
is_(True))
|
Use phantomjs instead of a real browser
|
## Code Before:
import time
import unittest
from hamcrest import *
from splinter import Browser
from support.stub_server import HttpStub
class test_create_pages(unittest.TestCase):
def setUp(self):
HttpStub.start()
time.sleep(2)
def tearDown(self):
HttpStub.stop()
def test_about_page(self):
with Browser() as browser:
browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html")
assert_that(browser.is_text_present('High-volume services'),
is_(True))
## Instruction:
Use phantomjs instead of a real browser
## Code After:
import time
import unittest
from hamcrest import *
from splinter import Browser
from support.stub_server import HttpStub
class test_create_pages(unittest.TestCase):
def setUp(self):
HttpStub.start()
time.sleep(2)
def tearDown(self):
HttpStub.stop()
def test_about_page(self):
with Browser('phantomjs', wait_time=3) as browser:
browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html")
assert_that(browser.is_text_present('High-volume services'),
is_(True))
|
# ... existing code ...
def test_about_page(self):
with Browser('phantomjs', wait_time=3) as browser:
browser.visit("http://0.0.0.0:8000/high-volume-services/by-transactions-per-year/descending.html")
# ... rest of the code ...
|
43ca79dbd2067ba9733bf43f81b43aa048bbd900
|
seaweb_project/jobs/serializers.py
|
seaweb_project/jobs/serializers.py
|
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
|
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
|
Implement validation for structure and topology files.
|
Implement validation for structure and topology
files.
|
Python
|
mit
|
grollins/sea-web-django
|
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
+ def validate_structure(self, attrs, source):
+ """
+ Check that structure file is a gro file.
+ """
+ uploaded_file = attrs[source]
+ if uploaded_file.name.endswith('.gro'):
+ return attrs
+ else:
+ raise serializers.ValidationError('Structure file must be a .gro file.')
+
+ def validate_topology(self, attrs, source):
+ """
+ Check that topology file is a top file.
+ """
+ uploaded_file = attrs[source]
+ if uploaded_file.name.endswith('.top'):
+ return attrs
+ else:
+ raise serializers.ValidationError('Topology file must be a .top file.')
+
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
|
Implement validation for structure and topology files.
|
## Code Before:
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
## Instruction:
Implement validation for structure and topology files.
## Code After:
from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Job, Result
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
class JobSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.Field(source='owner.username')
result = ResultSerializer(read_only=True)
class Meta:
model = Job
fields = ('id', 'url', 'title', 'status', 'owner', 'structure', 'topology',
'iterations', 'result')
read_only_fields = ('status',)
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
class UserSerializer(serializers.HyperlinkedModelSerializer):
jobs = serializers.HyperlinkedRelatedField(many=True, view_name='job-detail')
class Meta:
model = User
fields = ('url', 'username', 'jobs')
|
...
def validate_structure(self, attrs, source):
"""
Check that structure file is a gro file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.gro'):
return attrs
else:
raise serializers.ValidationError('Structure file must be a .gro file.')
def validate_topology(self, attrs, source):
"""
Check that topology file is a top file.
"""
uploaded_file = attrs[source]
if uploaded_file.name.endswith('.top'):
return attrs
else:
raise serializers.ValidationError('Topology file must be a .top file.')
...
|
7a8112249de859a5ef73fe07eb6029aeb1266f35
|
tob-api/tob_api/urls.py
|
tob-api/tob_api/urls.py
|
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="api/v2/")),
url(
r"^api-auth/",
include("rest_framework.urls", namespace="rest_framework"),
),
# url(r"^api/v1/", include("api.urls")),
url(r"^api/v2/", include("api_v2.urls")),
url(r"^health$", views.health),
]
|
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="api/v2/")),
url(
r"^api-auth/",
include("rest_framework.urls", namespace="rest_framework"),
),
url(r"^api/v2/", include("api_v2.urls")),
url(r"^health$", views.health),
]
|
Remove commented-out reference to v1
|
Remove commented-out reference to v1
Signed-off-by: Nicholas Rempel <[email protected]>
|
Python
|
apache-2.0
|
swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook
|
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="api/v2/")),
url(
r"^api-auth/",
include("rest_framework.urls", namespace="rest_framework"),
),
- # url(r"^api/v1/", include("api.urls")),
url(r"^api/v2/", include("api_v2.urls")),
url(r"^health$", views.health),
]
|
Remove commented-out reference to v1
|
## Code Before:
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="api/v2/")),
url(
r"^api-auth/",
include("rest_framework.urls", namespace="rest_framework"),
),
# url(r"^api/v1/", include("api.urls")),
url(r"^api/v2/", include("api_v2.urls")),
url(r"^health$", views.health),
]
## Instruction:
Remove commented-out reference to v1
## Code After:
from django.conf.urls import include, url
from django.views.generic import RedirectView
from . import views
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = [
url(r"^$", RedirectView.as_view(url="api/v2/")),
url(
r"^api-auth/",
include("rest_framework.urls", namespace="rest_framework"),
),
url(r"^api/v2/", include("api_v2.urls")),
url(r"^health$", views.health),
]
|
...
),
url(r"^api/v2/", include("api_v2.urls")),
...
|
94142e31d4189fbcf152eeb6b9ad89d684f1a6d0
|
autoload/splicelib/util/io.py
|
autoload/splicelib/util/io.py
|
import sys
def error(m):
sys.stderr.write(str(m) + '\n')
|
import sys
import vim
def error(m):
sys.stderr.write(str(m) + '\n')
def echomsg(m):
vim.command('echomsg "%s"' % m)
|
Add a utility for echoing in the IO utils.
|
Add a utility for echoing in the IO utils.
|
Python
|
mit
|
sjl/splice.vim,sjl/splice.vim
|
import sys
+ import vim
def error(m):
sys.stderr.write(str(m) + '\n')
+ def echomsg(m):
+ vim.command('echomsg "%s"' % m)
+
|
Add a utility for echoing in the IO utils.
|
## Code Before:
import sys
def error(m):
sys.stderr.write(str(m) + '\n')
## Instruction:
Add a utility for echoing in the IO utils.
## Code After:
import sys
import vim
def error(m):
sys.stderr.write(str(m) + '\n')
def echomsg(m):
vim.command('echomsg "%s"' % m)
|
# ... existing code ...
import sys
import vim
# ... modified code ...
sys.stderr.write(str(m) + '\n')
def echomsg(m):
vim.command('echomsg "%s"' % m)
# ... rest of the code ...
|
9db16e16db9131806d76a1f6875dfba33a7d452b
|
smile_model_graph/__openerp__.py
|
smile_model_graph/__openerp__.py
|
{
"name": "Objects Graph",
"version": "0.1",
"depends": ["base"],
"author": "Smile",
"license": 'AGPL-3',
"description": """
Generate Objects Graph
Suggestions & Feedback to: [email protected]
""",
"website": "http://www.smile.fr",
"category": "Hidden",
"sequence": 32,
"data": [
"wizard/ir_model_graph_wizard_view.xml",
],
"demo": [],
'test': [],
"auto_install": True,
"installable": True,
"application": False,
}
|
{
"name": "Models Graph",
"version": "0.1",
"depends": ["base"],
"author": "Smile",
"license": 'AGPL-3',
"description": """
Generate Models Graph
Suggestions & Feedback to: [email protected]
""",
"website": "http://www.smile.fr",
"category": "Hidden",
"sequence": 32,
"data": [
"wizard/ir_model_graph_wizard_view.xml",
],
"demo": [],
'test': [],
"auto_install": True,
"installable": True,
"application": False,
}
|
Rename Objects to Models in module description
|
[IMP] Rename Objects to Models in module description
|
Python
|
agpl-3.0
|
tiexinliu/odoo_addons,chadyred/odoo_addons,chadyred/odoo_addons,ovnicraft/odoo_addons,bmya/odoo_addons,odoocn/odoo_addons,odoocn/odoo_addons,tiexinliu/odoo_addons,chadyred/odoo_addons,odoocn/odoo_addons,ovnicraft/odoo_addons,bmya/odoo_addons,ovnicraft/odoo_addons,bmya/odoo_addons,tiexinliu/odoo_addons
|
{
- "name": "Objects Graph",
+ "name": "Models Graph",
"version": "0.1",
"depends": ["base"],
"author": "Smile",
"license": 'AGPL-3',
"description": """
- Generate Objects Graph
+ Generate Models Graph
Suggestions & Feedback to: [email protected]
""",
"website": "http://www.smile.fr",
"category": "Hidden",
"sequence": 32,
"data": [
"wizard/ir_model_graph_wizard_view.xml",
],
"demo": [],
'test': [],
"auto_install": True,
"installable": True,
"application": False,
}
|
Rename Objects to Models in module description
|
## Code Before:
{
"name": "Objects Graph",
"version": "0.1",
"depends": ["base"],
"author": "Smile",
"license": 'AGPL-3',
"description": """
Generate Objects Graph
Suggestions & Feedback to: [email protected]
""",
"website": "http://www.smile.fr",
"category": "Hidden",
"sequence": 32,
"data": [
"wizard/ir_model_graph_wizard_view.xml",
],
"demo": [],
'test': [],
"auto_install": True,
"installable": True,
"application": False,
}
## Instruction:
Rename Objects to Models in module description
## Code After:
{
"name": "Models Graph",
"version": "0.1",
"depends": ["base"],
"author": "Smile",
"license": 'AGPL-3',
"description": """
Generate Models Graph
Suggestions & Feedback to: [email protected]
""",
"website": "http://www.smile.fr",
"category": "Hidden",
"sequence": 32,
"data": [
"wizard/ir_model_graph_wizard_view.xml",
],
"demo": [],
'test': [],
"auto_install": True,
"installable": True,
"application": False,
}
|
# ... existing code ...
{
"name": "Models Graph",
"version": "0.1",
# ... modified code ...
"description": """
Generate Models Graph
# ... rest of the code ...
|
c2859bd8da741862ee01a276a1350fb4a5931dbc
|
data_access.py
|
data_access.py
|
import sys
import mysql.connector
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...")
for n in xrange(0, 10000):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%1417773'")
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
|
from random import randint
import sys
import mysql.connector
NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...")
for n in xrange(0, NUM_EMPLOYEES):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%%%d'" % randint(0, NUM_EMPLOYEES))
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
|
Change data access script to issue SELECTs that actually return a value
|
Change data access script to issue SELECTs that actually return a value
This makes the part about tracing the SQL statements and tracing the
number of rows returned a little more interesting.
|
Python
|
mit
|
goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop,goldshtn/linux-tracing-workshop
|
+ from random import randint
import sys
import mysql.connector
+
+ NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...")
- for n in xrange(0, 10000):
+ for n in xrange(0, NUM_EMPLOYEES):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
- cursor.execute("select * from employees where name like '%1417773'")
+ cursor.execute("select * from employees where name like '%%%d'" % randint(0, NUM_EMPLOYEES))
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
|
Change data access script to issue SELECTs that actually return a value
|
## Code Before:
import sys
import mysql.connector
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...")
for n in xrange(0, 10000):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%1417773'")
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
## Instruction:
Change data access script to issue SELECTs that actually return a value
## Code After:
from random import randint
import sys
import mysql.connector
NUM_EMPLOYEES = 10000
def insert():
cursor = connection.cursor()
try:
cursor.execute("drop table employees")
except:
pass
cursor.execute("create table employees (id integer primary key, name text)")
cursor.close()
print("Inserting employees...")
for n in xrange(0, NUM_EMPLOYEES):
cursor = connection.cursor()
cursor.execute("insert into employees (id, name) values (%d, 'Employee_%d')" %
(n, n))
connection.commit()
cursor.close()
def select():
print("Selecting employees...")
while True:
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%%%d'" % randint(0, NUM_EMPLOYEES))
for row in cursor:
pass
cursor.close()
connection = mysql.connector.connect(host='localhost', database='test')
if "insert" in sys.argv:
while True:
insert()
elif "insert_once" in sys.argv:
insert()
elif "select" in sys.argv:
select()
else:
print("USAGE: data_access.py <insert|insert_once|select>")
connection.close()
|
...
from random import randint
import sys
...
import mysql.connector
NUM_EMPLOYEES = 10000
...
print("Inserting employees...")
for n in xrange(0, NUM_EMPLOYEES):
cursor = connection.cursor()
...
cursor = connection.cursor()
cursor.execute("select * from employees where name like '%%%d'" % randint(0, NUM_EMPLOYEES))
for row in cursor:
...
|
a51d280ca7c7f487e6743e4f377f70641a8b4edd
|
turbustat/statistics/statistics_list.py
|
turbustat/statistics/statistics_list.py
|
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
"VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
|
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
"VCS_Large_Scale", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
threeD_statistics_list = \
["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale",
"VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
|
Update the stats lists and add a 3D only version
|
Update the stats lists and add a 3D only version
|
Python
|
mit
|
Astroua/TurbuStat,e-koch/TurbuStat
|
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
- "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD",
+ "VCS_Large_Scale", "PDF_Hellinger", "PDF_KS",
+ "PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
- "PDF_Hellinger", "PDF_KS", # "PDF_AD",
+ "PDF_Hellinger", "PDF_KS",
+ "PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
+ threeD_statistics_list = \
+ ["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale",
+ "VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS",
+ "PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
+
|
Update the stats lists and add a 3D only version
|
## Code Before:
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
"VCS_Large_Scale", "PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
## Instruction:
Update the stats lists and add a 3D only version
## Code After:
'''
Returns a list of all available distance metrics
'''
statistics_list = ["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "VCS", "VCA", "Tsallis", "PCA", "SCF", "Cramer",
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
"VCS_Large_Scale", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
twoD_statistics_list = \
["Wavelet", "MVC", "PSpec", "Bispectrum", "DeltaVariance",
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
threeD_statistics_list = \
["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale",
"VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
|
...
"Skewness", "Kurtosis", "VCS_Small_Scale", "VCS_Break",
"VCS_Large_Scale", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
...
"Genus", "Tsallis", "Skewness", "Kurtosis",
"PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", # "PDF_AD",
"Dendrogram_Hist", "Dendrogram_Num"]
threeD_statistics_list = \
["VCS", "VCA", "PCA", "SCF", "Cramer", "VCS_Small_Scale",
"VCS_Large_Scale", "VCS_Break", "PDF_Hellinger", "PDF_KS",
"PDF_Lognormal", "Dendrogram_Hist", "Dendrogram_Num"]
...
|
debdc71a1c22412c46d8bf74315a5467c1e228ee
|
magnum/tests/unit/common/test_exception.py
|
magnum/tests/unit/common/test_exception.py
|
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", ex.message)
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", ex.message)
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
|
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", str(ex))
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", str(ex))
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
|
Stop using deprecated 'message' attribute in Exception
|
Stop using deprecated 'message' attribute in Exception
The 'message' attribute has been deprecated and removed
from Python3.
For more details, please check:
https://www.python.org/dev/peps/pep-0352/
Change-Id: Id952e4f59a911df7ccc1d64e7a8a2d5e9ee353dd
|
Python
|
apache-2.0
|
ArchiFleKs/magnum,ArchiFleKs/magnum,openstack/magnum,openstack/magnum
|
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
- self.assertEqual("templated NAME", ex.message)
+ self.assertEqual("templated NAME", str(ex))
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
- self.assertEqual("custom templated NAME", ex.message)
+ self.assertEqual("custom templated NAME", str(ex))
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
|
Stop using deprecated 'message' attribute in Exception
|
## Code Before:
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", ex.message)
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", ex.message)
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
## Instruction:
Stop using deprecated 'message' attribute in Exception
## Code After:
import inspect
from magnum.common import exception
from magnum.i18n import _
from magnum.tests import base
class TestMagnumException(exception.MagnumException):
message = _("templated %(name)s")
class TestException(base.BaseTestCase):
def raise_(self, ex):
raise ex
def test_message_is_templated(self):
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", str(ex))
def test_custom_message_is_templated(self):
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", str(ex))
def test_all_exceptions(self):
for name, obj in inspect.getmembers(exception):
if inspect.isclass(obj) and issubclass(obj, Exception):
self.assertRaises(obj, self.raise_, obj())
|
# ... existing code ...
ex = TestMagnumException(name="NAME")
self.assertEqual("templated NAME", str(ex))
# ... modified code ...
ex = TestMagnumException(_("custom templated %(name)s"), name="NAME")
self.assertEqual("custom templated NAME", str(ex))
# ... rest of the code ...
|
53be5c9c86d544567f8171baba58128b5ad0502a
|
tests/test_io.py
|
tests/test_io.py
|
import nonstdlib
def test_capture_output():
import sys
with nonstdlib.capture_output() as output:
print('std', end='', file=sys.stdout)
print('st', end='', file=sys.stderr)
print('out', file=sys.stdout)
print('derr', file=sys.stderr)
assert 'stdout' in output
assert 'stderr' in output
assert output.stdout == 'stdout\n'
assert output.stderr == 'stderr\n'
def test_muffle():
with nonstdlib.muffle():
print("""\
This test doesn't really test anything, it just makes sure the
muffle function returns without raising any exceptions. You shouldn't ever see
this message.""")
|
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import nonstdlib
def test_capture_output():
import sys
with nonstdlib.capture_output() as output:
print('std', end='', file=sys.stdout)
print('st', end='', file=sys.stderr)
print('out', file=sys.stdout)
print('derr', file=sys.stderr)
assert 'stdout' in output
assert 'stderr' in output
assert output.stdout == 'stdout\n'
assert output.stderr == 'stderr\n'
def test_muffle():
with nonstdlib.muffle():
print("""\
This test doesn't really test anything, it just makes sure the
muffle function returns without raising any exceptions. You shouldn't ever see
this message.""")
|
Make the tests compatible with python2.
|
Make the tests compatible with python2.
|
Python
|
mit
|
kalekundert/nonstdlib,KenKundert/nonstdlib,KenKundert/nonstdlib,kalekundert/nonstdlib
|
+
+ from __future__ import division
+ from __future__ import print_function
+ from __future__ import unicode_literals
+
import nonstdlib
def test_capture_output():
import sys
with nonstdlib.capture_output() as output:
print('std', end='', file=sys.stdout)
print('st', end='', file=sys.stderr)
print('out', file=sys.stdout)
print('derr', file=sys.stderr)
assert 'stdout' in output
assert 'stderr' in output
assert output.stdout == 'stdout\n'
assert output.stderr == 'stderr\n'
def test_muffle():
with nonstdlib.muffle():
print("""\
This test doesn't really test anything, it just makes sure the
muffle function returns without raising any exceptions. You shouldn't ever see
this message.""")
|
Make the tests compatible with python2.
|
## Code Before:
import nonstdlib
def test_capture_output():
import sys
with nonstdlib.capture_output() as output:
print('std', end='', file=sys.stdout)
print('st', end='', file=sys.stderr)
print('out', file=sys.stdout)
print('derr', file=sys.stderr)
assert 'stdout' in output
assert 'stderr' in output
assert output.stdout == 'stdout\n'
assert output.stderr == 'stderr\n'
def test_muffle():
with nonstdlib.muffle():
print("""\
This test doesn't really test anything, it just makes sure the
muffle function returns without raising any exceptions. You shouldn't ever see
this message.""")
## Instruction:
Make the tests compatible with python2.
## Code After:
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import nonstdlib
def test_capture_output():
import sys
with nonstdlib.capture_output() as output:
print('std', end='', file=sys.stdout)
print('st', end='', file=sys.stderr)
print('out', file=sys.stdout)
print('derr', file=sys.stderr)
assert 'stdout' in output
assert 'stderr' in output
assert output.stdout == 'stdout\n'
assert output.stderr == 'stderr\n'
def test_muffle():
with nonstdlib.muffle():
print("""\
This test doesn't really test anything, it just makes sure the
muffle function returns without raising any exceptions. You shouldn't ever see
this message.""")
|
# ... existing code ...
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import nonstdlib
# ... rest of the code ...
|
d966b0973da71f5c883697ddd12c2728b2a04cce
|
ci/cleanup-binary-tags.py
|
ci/cleanup-binary-tags.py
|
import os
import subprocess
import re
import semver
def tag_to_version(tag):
version = re.sub(r'binary-', '', tag)
version = re.sub(r'-[x86|i686].*', '', version)
return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
import os
import subprocess
import re
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
Improve git tag to version conversion
|
Improve git tag to version conversion
There is also aarch64 arch.
|
Python
|
mit
|
autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim,autozimu/LanguageClient-neovim
|
import os
import subprocess
import re
import semver
def tag_to_version(tag):
+ return tag.split('-')[1].lstrip('v')
- version = re.sub(r'binary-', '', tag)
- version = re.sub(r'-[x86|i686].*', '', version)
- return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
Improve git tag to version conversion
|
## Code Before:
import os
import subprocess
import re
import semver
def tag_to_version(tag):
version = re.sub(r'binary-', '', tag)
version = re.sub(r'-[x86|i686].*', '', version)
return version
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
## Instruction:
Improve git tag to version conversion
## Code After:
import os
import subprocess
import re
import semver
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
subprocess.check_call('git pull --tags', shell=True)
tags = subprocess.check_output(
'git tag --list | grep binary', shell=True).decode('UTF-8').splitlines()
versions = sorted(list(set([tag_to_version(tag) for tag in tags])),
key=semver.parse_version_info)
versions_to_delete = versions[:-3]
cmd_delete_local = 'git tag --delete'
cmd_delete_remote = 'git push --delete '
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
if GITHUB_TOKEN:
cmd_delete_remote += (
'https://{}@github.com/autozimu/LanguageClient-neovim.git'
.format(GITHUB_TOKEN))
else:
cmd_delete_remote += 'origin'
for tag in tags:
if tag_to_version(tag) in versions_to_delete:
cmd_delete_local += ' ' + tag
cmd_delete_remote += ' ' + tag
if not cmd_delete_local.endswith('delete'):
subprocess.check_call(cmd_delete_local, shell=True)
if not (cmd_delete_remote.endswith('origin') or
cmd_delete_remote.endswith('.git')):
subprocess.check_call(cmd_delete_remote, shell=True)
|
...
def tag_to_version(tag):
return tag.split('-')[1].lstrip('v')
...
|
9dd4da3d62312c5184150a967f7e4a3935c7b94e
|
moksha/tests/test_clientsockets.py
|
moksha/tests/test_clientsockets.py
|
import webtest
import moksha.tests.utils as testutils
from moksha.api.widgets.live import get_moksha_socket
from moksha.middleware import make_moksha_middleware
from tw2.core import make_middleware as make_tw2_middleware
class TestClientSocketDumb:
def _setUp(self):
def kernel(config):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
socket = get_moksha_socket(config)
return map(str, [socket.display()])
app = make_moksha_middleware(app, config)
app = make_tw2_middleware(app, config)
app = webtest.TestApp(app)
self.app = app
for _setup, name in testutils.make_setup_functions(kernel):
yield _setup, name
def _tearDown(self):
pass
@testutils.crosstest
def test_middleware_wrap(self):
targets = ['moksha_websocket', 'TCPSocket']
response = self.app.get('/')
assert(any([target in response for target in targets]))
|
import webtest
import moksha.tests.utils as testutils
from moksha.api.widgets.live import get_moksha_socket
from moksha.middleware import make_moksha_middleware
from tw2.core import make_middleware as make_tw2_middleware
class TestClientSocketDumb:
def _setUp(self):
def kernel(config):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
socket = get_moksha_socket(config)
return map(str, [socket.display()])
app = make_moksha_middleware(app, config)
app = make_tw2_middleware(app, config)
app = webtest.TestApp(app)
self.app = app
for _setup, name in testutils.make_setup_functions(kernel):
yield _setup, name
def _tearDown(self):
pass
@testutils.crosstest
def test_has_socket_str(self):
targets = ['moksha_websocket', 'TCPSocket']
response = self.app.get('/')
assert(any([target in response for target in targets]))
|
Rename test. Fix copy/pasta forgetfulness.
|
Rename test. Fix copy/pasta forgetfulness.
|
Python
|
apache-2.0
|
pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha,pombredanne/moksha
|
import webtest
import moksha.tests.utils as testutils
from moksha.api.widgets.live import get_moksha_socket
from moksha.middleware import make_moksha_middleware
from tw2.core import make_middleware as make_tw2_middleware
class TestClientSocketDumb:
def _setUp(self):
def kernel(config):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
socket = get_moksha_socket(config)
return map(str, [socket.display()])
app = make_moksha_middleware(app, config)
app = make_tw2_middleware(app, config)
app = webtest.TestApp(app)
self.app = app
for _setup, name in testutils.make_setup_functions(kernel):
yield _setup, name
def _tearDown(self):
pass
@testutils.crosstest
- def test_middleware_wrap(self):
+ def test_has_socket_str(self):
targets = ['moksha_websocket', 'TCPSocket']
response = self.app.get('/')
assert(any([target in response for target in targets]))
|
Rename test. Fix copy/pasta forgetfulness.
|
## Code Before:
import webtest
import moksha.tests.utils as testutils
from moksha.api.widgets.live import get_moksha_socket
from moksha.middleware import make_moksha_middleware
from tw2.core import make_middleware as make_tw2_middleware
class TestClientSocketDumb:
def _setUp(self):
def kernel(config):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
socket = get_moksha_socket(config)
return map(str, [socket.display()])
app = make_moksha_middleware(app, config)
app = make_tw2_middleware(app, config)
app = webtest.TestApp(app)
self.app = app
for _setup, name in testutils.make_setup_functions(kernel):
yield _setup, name
def _tearDown(self):
pass
@testutils.crosstest
def test_middleware_wrap(self):
targets = ['moksha_websocket', 'TCPSocket']
response = self.app.get('/')
assert(any([target in response for target in targets]))
## Instruction:
Rename test. Fix copy/pasta forgetfulness.
## Code After:
import webtest
import moksha.tests.utils as testutils
from moksha.api.widgets.live import get_moksha_socket
from moksha.middleware import make_moksha_middleware
from tw2.core import make_middleware as make_tw2_middleware
class TestClientSocketDumb:
def _setUp(self):
def kernel(config):
def app(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
socket = get_moksha_socket(config)
return map(str, [socket.display()])
app = make_moksha_middleware(app, config)
app = make_tw2_middleware(app, config)
app = webtest.TestApp(app)
self.app = app
for _setup, name in testutils.make_setup_functions(kernel):
yield _setup, name
def _tearDown(self):
pass
@testutils.crosstest
def test_has_socket_str(self):
targets = ['moksha_websocket', 'TCPSocket']
response = self.app.get('/')
assert(any([target in response for target in targets]))
|
# ... existing code ...
@testutils.crosstest
def test_has_socket_str(self):
targets = ['moksha_websocket', 'TCPSocket']
# ... rest of the code ...
|
257134bdaea7c250d5956c4095adf0b917b65aa6
|
database/dict_converters/event_details_converter.py
|
database/dict_converters/event_details_converter.py
|
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections,
'district_points': event_details.district_points,
'rankings': event_details.renderable_rankings,
'stats': event_details.matchstats,
}
return event_details_dict
|
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections if event_details else None,
'district_points': event_details.district_points if event_details else None,
'rankings': event_details.renderable_rankings if event_details else None,
'stats': event_details.matchstats if event_details else None,
}
return event_details_dict
|
Fix null case for event details
|
Fix null case for event details
|
Python
|
mit
|
verycumbersome/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance
|
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
- 'alliances': event_details.alliance_selections,
+ 'alliances': event_details.alliance_selections if event_details else None,
- 'district_points': event_details.district_points,
+ 'district_points': event_details.district_points if event_details else None,
- 'rankings': event_details.renderable_rankings,
+ 'rankings': event_details.renderable_rankings if event_details else None,
- 'stats': event_details.matchstats,
+ 'stats': event_details.matchstats if event_details else None,
}
return event_details_dict
|
Fix null case for event details
|
## Code Before:
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections,
'district_points': event_details.district_points,
'rankings': event_details.renderable_rankings,
'stats': event_details.matchstats,
}
return event_details_dict
## Instruction:
Fix null case for event details
## Code After:
from database.dict_converters.converter_base import ConverterBase
class EventDetailsConverter(ConverterBase):
SUBVERSIONS = { # Increment every time a change to the dict is made
3: 0,
}
@classmethod
def convert(cls, event_details, dict_version):
CONVERTERS = {
3: cls.eventDetailsConverter_v3,
}
return CONVERTERS[dict_version](event_details)
@classmethod
def eventDetailsConverter_v3(cls, event_details):
event_details_dict = {
'alliances': event_details.alliance_selections if event_details else None,
'district_points': event_details.district_points if event_details else None,
'rankings': event_details.renderable_rankings if event_details else None,
'stats': event_details.matchstats if event_details else None,
}
return event_details_dict
|
// ... existing code ...
event_details_dict = {
'alliances': event_details.alliance_selections if event_details else None,
'district_points': event_details.district_points if event_details else None,
'rankings': event_details.renderable_rankings if event_details else None,
'stats': event_details.matchstats if event_details else None,
}
// ... rest of the code ...
|
b1bfb600240a006eed0cfce19d3fc87b3c72669f
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
name = 'jargparse',
packages = ['jargparse'], # this must be the same as the name above
version = '0.0.3',
description = 'A tiny super-dumb python module just because I like to see the usage info on stdout on an error',
author = 'Justin Clark-Casey',
author_email = '[email protected]',
url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo
keywords = ['logging'], # arbitrary keywords
)
|
from distutils.core import setup
setup(
name = 'jargparse',
packages = ['jargparse'], # this must be the same as the name above
version = '0.0.4',
description = 'A tiny super-dumb module just because I like to see the usage info on stdout on an error. jargparse.ArgParser just wraps argparse.ArgParser',
author = 'Justin Clark-Casey',
author_email = '[email protected]',
url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo
keywords = ['logging'], # arbitrary keywords
)
|
Add a bit more to description
|
Add a bit more to description
|
Python
|
apache-2.0
|
justinccdev/jargparse
|
from distutils.core import setup
setup(
name = 'jargparse',
packages = ['jargparse'], # this must be the same as the name above
- version = '0.0.3',
+ version = '0.0.4',
- description = 'A tiny super-dumb python module just because I like to see the usage info on stdout on an error',
+ description = 'A tiny super-dumb module just because I like to see the usage info on stdout on an error. jargparse.ArgParser just wraps argparse.ArgParser',
author = 'Justin Clark-Casey',
author_email = '[email protected]',
url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo
keywords = ['logging'], # arbitrary keywords
)
|
Add a bit more to description
|
## Code Before:
from distutils.core import setup
setup(
name = 'jargparse',
packages = ['jargparse'], # this must be the same as the name above
version = '0.0.3',
description = 'A tiny super-dumb python module just because I like to see the usage info on stdout on an error',
author = 'Justin Clark-Casey',
author_email = '[email protected]',
url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo
keywords = ['logging'], # arbitrary keywords
)
## Instruction:
Add a bit more to description
## Code After:
from distutils.core import setup
setup(
name = 'jargparse',
packages = ['jargparse'], # this must be the same as the name above
version = '0.0.4',
description = 'A tiny super-dumb module just because I like to see the usage info on stdout on an error. jargparse.ArgParser just wraps argparse.ArgParser',
author = 'Justin Clark-Casey',
author_email = '[email protected]',
url = 'https://github.com/justinccdev/jargparse', # use the URL to the github repo
keywords = ['logging'], # arbitrary keywords
)
|
// ... existing code ...
packages = ['jargparse'], # this must be the same as the name above
version = '0.0.4',
description = 'A tiny super-dumb module just because I like to see the usage info on stdout on an error. jargparse.ArgParser just wraps argparse.ArgParser',
author = 'Justin Clark-Casey',
// ... rest of the code ...
|
bf0043ac102cc9eddf03c8db493ae1a985c6a30a
|
src/nyc_trees/apps/home/urls.py
|
src/nyc_trees/apps/home/urls.py
|
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progress/$', r.progress_page, name='progress_page'),
url(r'^jobs/(?P<job_id>\d+)/$', r.retrieve_job_status,
name='retrieve_job_status'),
url(r'^training/$', r.training_list_page, name="training_list_page"),
url(r'^training/groups_to_follow/$', r.groups_to_follow),
# "training" instead of "training/" because the flatpages admin interface
# insists that the "URL" (really a URL segment) start with a leading slash
url(r'^training', include('django.contrib.flatpages.urls')),
)
|
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progress/$', r.progress_page, name='progress_page'),
url(r'^jobs/(?P<job_id>\d+)/$', r.retrieve_job_status,
name='retrieve_job_status'),
url(r'^training/$', r.training_list_page, name="training_list_page"),
url(r'^training/groups_to_follow/$', r.groups_to_follow),
# "training" instead of "training/" because the flatpages admin interface
# insists that the "URL" (really a URL segment) start with a leading slash
url(r'^training(?P<url>.*/)$', include('django.contrib.flatpages.urls')),
)
|
Fix trailing slash 404 for flat pages and co
|
Fix trailing slash 404 for flat pages and co
By modifying the URL, flatpage requests without a trailing slash will
always fail, triggering the redirect provided by `APPEND_SLASH`.
This is important because urls that share a common endpoint path were
404ing on a flatpage not found when not constructed with a slash.
|
Python
|
agpl-3.0
|
azavea/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,azavea/nyc-trees,RickMohr/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,RickMohr/nyc-trees
|
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progress/$', r.progress_page, name='progress_page'),
url(r'^jobs/(?P<job_id>\d+)/$', r.retrieve_job_status,
name='retrieve_job_status'),
url(r'^training/$', r.training_list_page, name="training_list_page"),
url(r'^training/groups_to_follow/$', r.groups_to_follow),
# "training" instead of "training/" because the flatpages admin interface
# insists that the "URL" (really a URL segment) start with a leading slash
- url(r'^training', include('django.contrib.flatpages.urls')),
+ url(r'^training(?P<url>.*/)$', include('django.contrib.flatpages.urls')),
)
|
Fix trailing slash 404 for flat pages and co
|
## Code Before:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progress/$', r.progress_page, name='progress_page'),
url(r'^jobs/(?P<job_id>\d+)/$', r.retrieve_job_status,
name='retrieve_job_status'),
url(r'^training/$', r.training_list_page, name="training_list_page"),
url(r'^training/groups_to_follow/$', r.groups_to_follow),
# "training" instead of "training/" because the flatpages admin interface
# insists that the "URL" (really a URL segment) start with a leading slash
url(r'^training', include('django.contrib.flatpages.urls')),
)
## Instruction:
Fix trailing slash 404 for flat pages and co
## Code After:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django.conf.urls import patterns, url, include
from apps.home import routes as r
urlpatterns = patterns(
'',
url(r'^$', r.home_page, name='home_page'),
url(r'^progress/$', r.progress_page, name='progress_page'),
url(r'^jobs/(?P<job_id>\d+)/$', r.retrieve_job_status,
name='retrieve_job_status'),
url(r'^training/$', r.training_list_page, name="training_list_page"),
url(r'^training/groups_to_follow/$', r.groups_to_follow),
# "training" instead of "training/" because the flatpages admin interface
# insists that the "URL" (really a URL segment) start with a leading slash
url(r'^training(?P<url>.*/)$', include('django.contrib.flatpages.urls')),
)
|
// ... existing code ...
# insists that the "URL" (really a URL segment) start with a leading slash
url(r'^training(?P<url>.*/)$', include('django.contrib.flatpages.urls')),
)
// ... rest of the code ...
|
f693f09bfedc4981557741a8ac445c160faab65d
|
assisstant/main.py
|
assisstant/main.py
|
import sys
from PyQt5.QtWidgets import QApplication
from keyboard.ui.widgets import KeyboardWindow
if __name__ == '__main__':
app = QApplication([])
window = KeyboardWindow()
window.showMaximized()
sys.exit(app.exec())
|
import sys
import signal
from PyQt5.QtWidgets import QApplication
from keyboard.ui.widgets import KeyboardWindow
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QApplication([])
window = KeyboardWindow()
window.showMaximized()
sys.exit(app.exec())
|
Add signal handler to quit the application
|
Add signal handler to quit the application
|
Python
|
apache-2.0
|
brainbots/assistant
|
import sys
+ import signal
from PyQt5.QtWidgets import QApplication
from keyboard.ui.widgets import KeyboardWindow
if __name__ == '__main__':
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QApplication([])
window = KeyboardWindow()
window.showMaximized()
sys.exit(app.exec())
|
Add signal handler to quit the application
|
## Code Before:
import sys
from PyQt5.QtWidgets import QApplication
from keyboard.ui.widgets import KeyboardWindow
if __name__ == '__main__':
app = QApplication([])
window = KeyboardWindow()
window.showMaximized()
sys.exit(app.exec())
## Instruction:
Add signal handler to quit the application
## Code After:
import sys
import signal
from PyQt5.QtWidgets import QApplication
from keyboard.ui.widgets import KeyboardWindow
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QApplication([])
window = KeyboardWindow()
window.showMaximized()
sys.exit(app.exec())
|
# ... existing code ...
import sys
import signal
from PyQt5.QtWidgets import QApplication
# ... modified code ...
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QApplication([])
# ... rest of the code ...
|
5c61d7f125078cb6b3bd0c5700ae9219baab0078
|
webapp/tests/test_dashboard.py
|
webapp/tests/test_dashboard.py
|
from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('graphite.dashboard.views.dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
|
from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
|
Update reverse call to use named URL
|
Update reverse call to use named URL
|
Python
|
apache-2.0
|
redice/graphite-web,dbn/graphite-web,Skyscanner/graphite-web,penpen/graphite-web,lyft/graphite-web,esnet/graphite-web,bpaquet/graphite-web,atnak/graphite-web,section-io/graphite-web,kkdk5535/graphite-web,cosm0s/graphite-web,cgvarela/graphite-web,gwaldo/graphite-web,redice/graphite-web,edwardmlyte/graphite-web,atnak/graphite-web,criteo-forks/graphite-web,bmhatfield/graphite-web,obfuscurity/graphite-web,AICIDNN/graphite-web,edwardmlyte/graphite-web,gwaldo/graphite-web,penpen/graphite-web,cbowman0/graphite-web,Skyscanner/graphite-web,JeanFred/graphite-web,cgvarela/graphite-web,bruce-lyft/graphite-web,criteo-forks/graphite-web,phreakocious/graphite-web,lyft/graphite-web,mcoolive/graphite-web,piotr1212/graphite-web,esnet/graphite-web,zBMNForks/graphite-web,axibase/graphite-web,blacked/graphite-web,AICIDNN/graphite-web,kkdk5535/graphite-web,atnak/graphite-web,ZelunZhang/graphite-web,graphite-server/graphite-web,cgvarela/graphite-web,graphite-server/graphite-web,zBMNForks/graphite-web,synedge/graphite-web,pu239ppy/graphite-web,axibase/graphite-web,gwaldo/graphite-web,jssjr/graphite-web,esnet/graphite-web,Skyscanner/graphite-web,bmhatfield/graphite-web,DanCech/graphite-web,lfckop/graphite-web,JeanFred/graphite-web,edwardmlyte/graphite-web,brutasse/graphite-web,esnet/graphite-web,Invoca/graphite-web,johnseekins/graphite-web,esnet/graphite-web,criteo-forks/graphite-web,mcoolive/graphite-web,pu239ppy/graphite-web,bmhatfield/graphite-web,edwardmlyte/graphite-web,ZelunZhang/graphite-web,DanCech/graphite-web,section-io/graphite-web,penpen/graphite-web,cbowman0/graphite-web,Invoca/graphite-web,markolson/graphite-web,markolson/graphite-web,Aloomaio/graphite-web,graphite-project/graphite-web,mcoolive/graphite-web,edwardmlyte/graphite-web,atnak/graphite-web,graphite-project/graphite-web,Squarespace/graphite-web,cbowman0/graphite-web,kkdk5535/graphite-web,lyft/graphite-web,criteo-forks/graphite-web,JeanFred/graphite-web,redice/graphite-web,graphite-server/graphite-web,dbn/graphite-web,pu239ppy/graphite-web,piotr1212/graphite-web,brutasse/graphite-web,phreakocious/graphite-web,mcoolive/graphite-web,lfckop/graphite-web,penpen/graphite-web,DanCech/graphite-web,johnseekins/graphite-web,blacked/graphite-web,bpaquet/graphite-web,cbowman0/graphite-web,cgvarela/graphite-web,markolson/graphite-web,bpaquet/graphite-web,graphite-project/graphite-web,bpaquet/graphite-web,bruce-lyft/graphite-web,Invoca/graphite-web,Squarespace/graphite-web,lyft/graphite-web,synedge/graphite-web,bbc/graphite-web,piotr1212/graphite-web,pu239ppy/graphite-web,johnseekins/graphite-web,JeanFred/graphite-web,DanCech/graphite-web,obfuscurity/graphite-web,lyft/graphite-web,cosm0s/graphite-web,Invoca/graphite-web,deniszh/graphite-web,krux/graphite-web,bbc/graphite-web,goir/graphite-web,Squarespace/graphite-web,DanCech/graphite-web,Aloomaio/graphite-web,bpaquet/graphite-web,johnseekins/graphite-web,disqus/graphite-web,penpen/graphite-web,section-io/graphite-web,cgvarela/graphite-web,lfckop/graphite-web,Invoca/graphite-web,jssjr/graphite-web,AICIDNN/graphite-web,bruce-lyft/graphite-web,cosm0s/graphite-web,ZelunZhang/graphite-web,graphite-project/graphite-web,zBMNForks/graphite-web,cgvarela/graphite-web,JeanFred/graphite-web,piotr1212/graphite-web,goir/graphite-web,cbowman0/graphite-web,drax68/graphite-web,criteo-forks/graphite-web,synedge/graphite-web,synedge/graphite-web,nkhuyu/graphite-web,JeanFred/graphite-web,phreakocious/graphite-web,Aloomaio/graphite-web,bbc/graphite-web,phreakocious/graphite-web,cosm0s/graphite-web,phreakocious/graphite-web,brutasse/graphite-web,graphite-server/graphite-web,Squarespace/graphite-web,gwaldo/graphite-web,cosm0s/graphite-web,deniszh/graphite-web,pu239ppy/graphite-web,blacked/graphite-web,Invoca/graphite-web,krux/graphite-web,AICIDNN/graphite-web,redice/graphite-web,piotr1212/graphite-web,cbowman0/graphite-web,section-io/graphite-web,obfuscurity/graphite-web,redice/graphite-web,section-io/graphite-web,deniszh/graphite-web,krux/graphite-web,nkhuyu/graphite-web,gwaldo/graphite-web,nkhuyu/graphite-web,graphite-server/graphite-web,deniszh/graphite-web,goir/graphite-web,Aloomaio/graphite-web,drax68/graphite-web,markolson/graphite-web,krux/graphite-web,obfuscurity/graphite-web,dbn/graphite-web,bruce-lyft/graphite-web,markolson/graphite-web,bmhatfield/graphite-web,brutasse/graphite-web,atnak/graphite-web,Skyscanner/graphite-web,krux/graphite-web,blacked/graphite-web,kkdk5535/graphite-web,jssjr/graphite-web,goir/graphite-web,lfckop/graphite-web,bmhatfield/graphite-web,cosm0s/graphite-web,Squarespace/graphite-web,disqus/graphite-web,ZelunZhang/graphite-web,Aloomaio/graphite-web,axibase/graphite-web,disqus/graphite-web,bbc/graphite-web,ZelunZhang/graphite-web,redice/graphite-web,goir/graphite-web,bruce-lyft/graphite-web,ZelunZhang/graphite-web,AICIDNN/graphite-web,axibase/graphite-web,mcoolive/graphite-web,disqus/graphite-web,johnseekins/graphite-web,drax68/graphite-web,drax68/graphite-web,lyft/graphite-web,graphite-project/graphite-web,lfckop/graphite-web,bmhatfield/graphite-web,blacked/graphite-web,axibase/graphite-web,axibase/graphite-web,krux/graphite-web,disqus/graphite-web,drax68/graphite-web,bbc/graphite-web,criteo-forks/graphite-web,pu239ppy/graphite-web,obfuscurity/graphite-web,nkhuyu/graphite-web,drax68/graphite-web,jssjr/graphite-web,obfuscurity/graphite-web,kkdk5535/graphite-web,jssjr/graphite-web,bruce-lyft/graphite-web,Aloomaio/graphite-web,kkdk5535/graphite-web,zBMNForks/graphite-web,DanCech/graphite-web,dbn/graphite-web,Squarespace/graphite-web,AICIDNN/graphite-web,zBMNForks/graphite-web,section-io/graphite-web,mcoolive/graphite-web,edwardmlyte/graphite-web,synedge/graphite-web,graphite-project/graphite-web,atnak/graphite-web,nkhuyu/graphite-web,brutasse/graphite-web,jssjr/graphite-web,disqus/graphite-web,johnseekins/graphite-web,synedge/graphite-web,Skyscanner/graphite-web,Skyscanner/graphite-web,lfckop/graphite-web,zBMNForks/graphite-web,deniszh/graphite-web,nkhuyu/graphite-web,penpen/graphite-web,dbn/graphite-web,blacked/graphite-web,brutasse/graphite-web,deniszh/graphite-web,graphite-server/graphite-web,bpaquet/graphite-web,gwaldo/graphite-web,goir/graphite-web,phreakocious/graphite-web,piotr1212/graphite-web,dbn/graphite-web
|
from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
- url = reverse('graphite.dashboard.views.dashboard')
+ url = reverse('dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
|
Update reverse call to use named URL
|
## Code Before:
from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('graphite.dashboard.views.dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
## Instruction:
Update reverse call to use named URL
## Code After:
from django.core.urlresolvers import reverse
from django.test import TestCase
class DashboardTest(TestCase):
def test_dashboard(self):
url = reverse('dashboard')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
|
# ... existing code ...
def test_dashboard(self):
url = reverse('dashboard')
response = self.client.get(url)
# ... rest of the code ...
|
78c96e56b46f800c972bcdb5c5aa525d73d84a80
|
src/setuptools_scm/__main__.py
|
src/setuptools_scm/__main__.py
|
import sys
from setuptools_scm import _get_version
from setuptools_scm import get_version
from setuptools_scm.config import Configuration
from setuptools_scm.integration import find_files
def main() -> None:
files = list(sorted(find_files("."), key=len))
try:
pyproject = next(fname for fname in files if fname.endswith("pyproject.toml"))
print(_get_version(Configuration.from_file(pyproject)))
except (LookupError, StopIteration):
print("Guessed Version", get_version())
if "ls" in sys.argv:
for fname in files:
print(fname)
if __name__ == "__main__":
main()
|
import argparse
import os
import warnings
from setuptools_scm import _get_version
from setuptools_scm.config import Configuration
from setuptools_scm.discover import walk_potential_roots
from setuptools_scm.integration import find_files
def main() -> None:
opts = _get_cli_opts()
root = opts.root or "."
try:
pyproject = opts.config or _find_pyproject(root)
root = opts.root or os.path.relpath(os.path.dirname(pyproject))
config = Configuration.from_file(pyproject)
config.root = root
except (LookupError, FileNotFoundError) as ex:
# no pyproject.toml OR no [tool.setuptools_scm]
warnings.warn(f"{ex}. Using default configuration.")
config = Configuration(root)
print(_get_version(config))
if opts.command == "ls":
for fname in find_files(config.root):
print(fname)
def _get_cli_opts():
prog = "python -m setuptools_scm"
desc = "Print project version according to SCM metadata"
parser = argparse.ArgumentParser(prog, description=desc)
# By default, help for `--help` starts with lower case, so we keep the pattern:
parser.add_argument(
"-r",
"--root",
default=None,
help='directory managed by the SCM, default: inferred from config file, or "."',
)
parser.add_argument(
"-c",
"--config",
default=None,
metavar="PATH",
help="path to 'pyproject.toml' with setuptools_scm config, "
"default: looked up in the current or parent directories",
)
sub = parser.add_subparsers(title="extra commands", dest="command", metavar="")
# We avoid `metavar` to prevent printing repetitive information
desc = "List files managed by the SCM"
sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc)
return parser.parse_args()
def _find_pyproject(parent):
for directory in walk_potential_roots(os.path.abspath(parent)):
pyproject = os.path.join(directory, "pyproject.toml")
if os.path.exists(pyproject):
return pyproject
raise FileNotFoundError("'pyproject.toml' was not found")
if __name__ == "__main__":
main()
|
Add options to better control CLI command
|
Add options to better control CLI command
Instead of trying to guess the `pyprojec.toml` file by looking at the
files controlled by the SCM, use explicit options to control it.
|
Python
|
mit
|
pypa/setuptools_scm,pypa/setuptools_scm,RonnyPfannschmidt/setuptools_scm,RonnyPfannschmidt/setuptools_scm
|
+ import argparse
- import sys
+ import os
+ import warnings
from setuptools_scm import _get_version
- from setuptools_scm import get_version
from setuptools_scm.config import Configuration
+ from setuptools_scm.discover import walk_potential_roots
from setuptools_scm.integration import find_files
def main() -> None:
- files = list(sorted(find_files("."), key=len))
+ opts = _get_cli_opts()
+ root = opts.root or "."
+
try:
- pyproject = next(fname for fname in files if fname.endswith("pyproject.toml"))
+ pyproject = opts.config or _find_pyproject(root)
+ root = opts.root or os.path.relpath(os.path.dirname(pyproject))
- print(_get_version(Configuration.from_file(pyproject)))
+ config = Configuration.from_file(pyproject)
- except (LookupError, StopIteration):
- print("Guessed Version", get_version())
+ config.root = root
+ except (LookupError, FileNotFoundError) as ex:
+ # no pyproject.toml OR no [tool.setuptools_scm]
+ warnings.warn(f"{ex}. Using default configuration.")
+ config = Configuration(root)
- if "ls" in sys.argv:
+ print(_get_version(config))
+
+ if opts.command == "ls":
- for fname in files:
+ for fname in find_files(config.root):
print(fname)
+
+
+ def _get_cli_opts():
+ prog = "python -m setuptools_scm"
+ desc = "Print project version according to SCM metadata"
+ parser = argparse.ArgumentParser(prog, description=desc)
+ # By default, help for `--help` starts with lower case, so we keep the pattern:
+ parser.add_argument(
+ "-r",
+ "--root",
+ default=None,
+ help='directory managed by the SCM, default: inferred from config file, or "."',
+ )
+ parser.add_argument(
+ "-c",
+ "--config",
+ default=None,
+ metavar="PATH",
+ help="path to 'pyproject.toml' with setuptools_scm config, "
+ "default: looked up in the current or parent directories",
+ )
+ sub = parser.add_subparsers(title="extra commands", dest="command", metavar="")
+ # We avoid `metavar` to prevent printing repetitive information
+ desc = "List files managed by the SCM"
+ sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc)
+ return parser.parse_args()
+
+
+ def _find_pyproject(parent):
+ for directory in walk_potential_roots(os.path.abspath(parent)):
+ pyproject = os.path.join(directory, "pyproject.toml")
+ if os.path.exists(pyproject):
+ return pyproject
+
+ raise FileNotFoundError("'pyproject.toml' was not found")
if __name__ == "__main__":
main()
|
Add options to better control CLI command
|
## Code Before:
import sys
from setuptools_scm import _get_version
from setuptools_scm import get_version
from setuptools_scm.config import Configuration
from setuptools_scm.integration import find_files
def main() -> None:
files = list(sorted(find_files("."), key=len))
try:
pyproject = next(fname for fname in files if fname.endswith("pyproject.toml"))
print(_get_version(Configuration.from_file(pyproject)))
except (LookupError, StopIteration):
print("Guessed Version", get_version())
if "ls" in sys.argv:
for fname in files:
print(fname)
if __name__ == "__main__":
main()
## Instruction:
Add options to better control CLI command
## Code After:
import argparse
import os
import warnings
from setuptools_scm import _get_version
from setuptools_scm.config import Configuration
from setuptools_scm.discover import walk_potential_roots
from setuptools_scm.integration import find_files
def main() -> None:
opts = _get_cli_opts()
root = opts.root or "."
try:
pyproject = opts.config or _find_pyproject(root)
root = opts.root or os.path.relpath(os.path.dirname(pyproject))
config = Configuration.from_file(pyproject)
config.root = root
except (LookupError, FileNotFoundError) as ex:
# no pyproject.toml OR no [tool.setuptools_scm]
warnings.warn(f"{ex}. Using default configuration.")
config = Configuration(root)
print(_get_version(config))
if opts.command == "ls":
for fname in find_files(config.root):
print(fname)
def _get_cli_opts():
prog = "python -m setuptools_scm"
desc = "Print project version according to SCM metadata"
parser = argparse.ArgumentParser(prog, description=desc)
# By default, help for `--help` starts with lower case, so we keep the pattern:
parser.add_argument(
"-r",
"--root",
default=None,
help='directory managed by the SCM, default: inferred from config file, or "."',
)
parser.add_argument(
"-c",
"--config",
default=None,
metavar="PATH",
help="path to 'pyproject.toml' with setuptools_scm config, "
"default: looked up in the current or parent directories",
)
sub = parser.add_subparsers(title="extra commands", dest="command", metavar="")
# We avoid `metavar` to prevent printing repetitive information
desc = "List files managed by the SCM"
sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc)
return parser.parse_args()
def _find_pyproject(parent):
for directory in walk_potential_roots(os.path.abspath(parent)):
pyproject = os.path.join(directory, "pyproject.toml")
if os.path.exists(pyproject):
return pyproject
raise FileNotFoundError("'pyproject.toml' was not found")
if __name__ == "__main__":
main()
|
# ... existing code ...
import argparse
import os
import warnings
# ... modified code ...
from setuptools_scm import _get_version
from setuptools_scm.config import Configuration
from setuptools_scm.discover import walk_potential_roots
from setuptools_scm.integration import find_files
...
def main() -> None:
opts = _get_cli_opts()
root = opts.root or "."
try:
pyproject = opts.config or _find_pyproject(root)
root = opts.root or os.path.relpath(os.path.dirname(pyproject))
config = Configuration.from_file(pyproject)
config.root = root
except (LookupError, FileNotFoundError) as ex:
# no pyproject.toml OR no [tool.setuptools_scm]
warnings.warn(f"{ex}. Using default configuration.")
config = Configuration(root)
print(_get_version(config))
if opts.command == "ls":
for fname in find_files(config.root):
print(fname)
def _get_cli_opts():
prog = "python -m setuptools_scm"
desc = "Print project version according to SCM metadata"
parser = argparse.ArgumentParser(prog, description=desc)
# By default, help for `--help` starts with lower case, so we keep the pattern:
parser.add_argument(
"-r",
"--root",
default=None,
help='directory managed by the SCM, default: inferred from config file, or "."',
)
parser.add_argument(
"-c",
"--config",
default=None,
metavar="PATH",
help="path to 'pyproject.toml' with setuptools_scm config, "
"default: looked up in the current or parent directories",
)
sub = parser.add_subparsers(title="extra commands", dest="command", metavar="")
# We avoid `metavar` to prevent printing repetitive information
desc = "List files managed by the SCM"
sub.add_parser("ls", help=desc[0].lower() + desc[1:], description=desc)
return parser.parse_args()
def _find_pyproject(parent):
for directory in walk_potential_roots(os.path.abspath(parent)):
pyproject = os.path.join(directory, "pyproject.toml")
if os.path.exists(pyproject):
return pyproject
raise FileNotFoundError("'pyproject.toml' was not found")
# ... rest of the code ...
|
b65c95ca400f91648a53553f51979f5ceb7a0d94
|
test/test-unrealcv.py
|
test/test-unrealcv.py
|
import unittest, time, sys, argparse, threading
sys.path.append('./test/ipc')
from common_conf import *
from test_dev_server import TestDevServer
from test_client import TestUE4CVClient
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI
args = parser.parse_args()
suites = []
load = unittest.TestLoader().loadTestsFromTestCase
s = load(TestDevServer); suites.append(s)
s = load(TestUE4CVClient); suites.append(s)
suite_obj = unittest.TestSuite(suites)
ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSuccessful()
sys.exit(ret)
|
'''
Run python test.py to test unrealcv
'''
import unittest, time, sys, argparse, threading
from common_conf import *
def run_full_test():
pass
def run_travis_test():
sys.path.append('./test/ipc')
from test_dev_server import TestDevServer
from test_client import TestUE4CVClient
load = unittest.TestLoader().loadTestsFromTestCase
suites = []
s = load(TestDevServer); suites.append(s)
s = load(TestUE4CVClient); suites.append(s)
suite_obj = unittest.TestSuite(suites)
ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSuccessful()
return ret
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI
args = parser.parse_args()
if args.travis:
ret = run_travis_test()
else:
ret = run_full_test()
sys.exit(ret)
|
Clean up the portal of test script.
|
Clean up the portal of test script.
|
Python
|
mit
|
unrealcv/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv
|
+ '''
+ Run python test.py to test unrealcv
+ '''
import unittest, time, sys, argparse, threading
- sys.path.append('./test/ipc')
from common_conf import *
+
+ def run_full_test():
+ pass
+
+ def run_travis_test():
+ sys.path.append('./test/ipc')
- from test_dev_server import TestDevServer
+ from test_dev_server import TestDevServer
- from test_client import TestUE4CVClient
+ from test_client import TestUE4CVClient
+ load = unittest.TestLoader().loadTestsFromTestCase
+
+ suites = []
+ s = load(TestDevServer); suites.append(s)
+ s = load(TestUE4CVClient); suites.append(s)
+ suite_obj = unittest.TestSuite(suites)
+
+ ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSuccessful()
+
+ return ret
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI
args = parser.parse_args()
- suites = []
+ if args.travis:
+ ret = run_travis_test()
+ else:
+ ret = run_full_test()
- load = unittest.TestLoader().loadTestsFromTestCase
- s = load(TestDevServer); suites.append(s)
- s = load(TestUE4CVClient); suites.append(s)
-
- suite_obj = unittest.TestSuite(suites)
- ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSuccessful()
sys.exit(ret)
|
Clean up the portal of test script.
|
## Code Before:
import unittest, time, sys, argparse, threading
sys.path.append('./test/ipc')
from common_conf import *
from test_dev_server import TestDevServer
from test_client import TestUE4CVClient
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI
args = parser.parse_args()
suites = []
load = unittest.TestLoader().loadTestsFromTestCase
s = load(TestDevServer); suites.append(s)
s = load(TestUE4CVClient); suites.append(s)
suite_obj = unittest.TestSuite(suites)
ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSuccessful()
sys.exit(ret)
## Instruction:
Clean up the portal of test script.
## Code After:
'''
Run python test.py to test unrealcv
'''
import unittest, time, sys, argparse, threading
from common_conf import *
def run_full_test():
pass
def run_travis_test():
sys.path.append('./test/ipc')
from test_dev_server import TestDevServer
from test_client import TestUE4CVClient
load = unittest.TestLoader().loadTestsFromTestCase
suites = []
s = load(TestDevServer); suites.append(s)
s = load(TestUE4CVClient); suites.append(s)
suite_obj = unittest.TestSuite(suites)
ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSuccessful()
return ret
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI
args = parser.parse_args()
if args.travis:
ret = run_travis_test()
else:
ret = run_full_test()
sys.exit(ret)
|
...
'''
Run python test.py to test unrealcv
'''
import unittest, time, sys, argparse, threading
from common_conf import *
def run_full_test():
pass
def run_travis_test():
sys.path.append('./test/ipc')
from test_dev_server import TestDevServer
from test_client import TestUE4CVClient
load = unittest.TestLoader().loadTestsFromTestCase
suites = []
s = load(TestDevServer); suites.append(s)
s = load(TestUE4CVClient); suites.append(s)
suite_obj = unittest.TestSuite(suites)
ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSuccessful()
return ret
...
args = parser.parse_args()
if args.travis:
ret = run_travis_test()
else:
ret = run_full_test()
sys.exit(ret)
...
|
483e04671095eedabc8972982dd2109a5329c603
|
tests/test_templatetags.py
|
tests/test_templatetags.py
|
import unittest
from columns.templatetags.columns import rows, columns
class TestColumns(unittest.TestCase):
def test_columns(self):
data = range(7)
result = rows(data, 2)
expected = [[0, 1, 2, 3], [4, 5, 6]]
self.assertEqual(result, expected)
|
import unittest
from columns.templatetags.columns import columns
class TestColumns(unittest.TestCase):
def test_columns(self):
data = range(7)
result = columns(data, 2)
expected = [[0, 1, 2, 3], [4, 5, 6]]
self.assertEqual(result, expected)
|
Fix tests to match updated defs.
|
Fix tests to match updated defs.
|
Python
|
bsd-3-clause
|
audreyr/django-columns,audreyr/django-columns,audreyr/django-columns
|
import unittest
- from columns.templatetags.columns import rows, columns
+ from columns.templatetags.columns import columns
class TestColumns(unittest.TestCase):
def test_columns(self):
data = range(7)
- result = rows(data, 2)
+ result = columns(data, 2)
expected = [[0, 1, 2, 3], [4, 5, 6]]
self.assertEqual(result, expected)
|
Fix tests to match updated defs.
|
## Code Before:
import unittest
from columns.templatetags.columns import rows, columns
class TestColumns(unittest.TestCase):
def test_columns(self):
data = range(7)
result = rows(data, 2)
expected = [[0, 1, 2, 3], [4, 5, 6]]
self.assertEqual(result, expected)
## Instruction:
Fix tests to match updated defs.
## Code After:
import unittest
from columns.templatetags.columns import columns
class TestColumns(unittest.TestCase):
def test_columns(self):
data = range(7)
result = columns(data, 2)
expected = [[0, 1, 2, 3], [4, 5, 6]]
self.assertEqual(result, expected)
|
# ... existing code ...
from columns.templatetags.columns import columns
# ... modified code ...
data = range(7)
result = columns(data, 2)
expected = [[0, 1, 2, 3], [4, 5, 6]]
# ... rest of the code ...
|
8c8307ff5313b1f6c69d976853f763daf2aece0c
|
test.py
|
test.py
|
""" Functions to call the api and test it """
import sys
import fenix
api = fenix.FenixAPISingleton()
print('Testing Fenix API SDK Python')
auth_url = api.get_authentication_url()
print(auth_url)
api.set_code(sys.argv[1])
print('Access token: ' + api.get_access_token())
print('Refresh token: ' + api.get_refresh_token())
api._refresh_access_token()
print('New access token: ' + api.get_access_token())
print(api.get_space('2465311230082'))
|
""" Functions to call the api and test it """
import sys
import fenix
api = fenix.FenixAPISingleton()
print('Testing Fenix API SDK Python')
auth_url = api.get_authentication_url()
print(api.get_space('2465311230082'))
print(auth_url)
api.set_code(sys.argv[1])
print('Access token: ' + api.get_access_token())
print('Refresh token: ' + api.get_refresh_token())
api._refresh_access_token()
print('New access token: ' + api.get_access_token())
|
Test now calls a public endpoint first
|
Test now calls a public endpoint first
|
Python
|
mit
|
samfcmc/fenixedu-python-sdk
|
""" Functions to call the api and test it """
import sys
import fenix
api = fenix.FenixAPISingleton()
print('Testing Fenix API SDK Python')
auth_url = api.get_authentication_url()
+ print(api.get_space('2465311230082'))
print(auth_url)
api.set_code(sys.argv[1])
print('Access token: ' + api.get_access_token())
print('Refresh token: ' + api.get_refresh_token())
api._refresh_access_token()
print('New access token: ' + api.get_access_token())
- print(api.get_space('2465311230082'))
|
Test now calls a public endpoint first
|
## Code Before:
""" Functions to call the api and test it """
import sys
import fenix
api = fenix.FenixAPISingleton()
print('Testing Fenix API SDK Python')
auth_url = api.get_authentication_url()
print(auth_url)
api.set_code(sys.argv[1])
print('Access token: ' + api.get_access_token())
print('Refresh token: ' + api.get_refresh_token())
api._refresh_access_token()
print('New access token: ' + api.get_access_token())
print(api.get_space('2465311230082'))
## Instruction:
Test now calls a public endpoint first
## Code After:
""" Functions to call the api and test it """
import sys
import fenix
api = fenix.FenixAPISingleton()
print('Testing Fenix API SDK Python')
auth_url = api.get_authentication_url()
print(api.get_space('2465311230082'))
print(auth_url)
api.set_code(sys.argv[1])
print('Access token: ' + api.get_access_token())
print('Refresh token: ' + api.get_refresh_token())
api._refresh_access_token()
print('New access token: ' + api.get_access_token())
|
...
auth_url = api.get_authentication_url()
print(api.get_space('2465311230082'))
print(auth_url)
...
...
|
34af1fdb4f6c9c8b994cb710b97fe0ed9e1311a7
|
setup.py
|
setup.py
|
import os
import glob
from numpy.distutils.core import setup, Extension
version = (os.popen('git config --get remote.origin.url').read() + ',' +
os.popen('git describe --always --tags --dirty').read())
scripts = []
setup(name='matscipy',
version=version,
description='Generic Python Materials Science tools',
maintainer='James Kermode & Lars Pastewka',
maintainer_email='[email protected]',
license='LGPLv2.1+',
package_dir={'matscipy': 'matscipy'},
packages=['matscipy'],
scripts=scripts,
ext_modules=[
Extension(
'_matscipy',
[ 'c/matscipymodule.c' ],
)
]
)
|
import os
import glob
from numpy.distutils.core import setup, Extension
version = (os.popen('git config --get remote.origin.url').read() + ',' +
os.popen('git describe --always --tags --dirty').read())
scripts = []
setup(name='matscipy',
version=version,
description='Generic Python Materials Science tools',
maintainer='James Kermode & Lars Pastewka',
maintainer_email='[email protected]',
license='LGPLv2.1+',
package_dir={'matscipy': 'matscipy'},
packages=['matscipy', 'matscipy.fracture_mechanics'],
scripts=scripts,
ext_modules=[
Extension(
'_matscipy',
[ 'c/matscipymodule.c' ],
)
]
)
|
Add matscipy.fracture_mechanics to packages list to install subpackage
|
Add matscipy.fracture_mechanics to packages list to install subpackage
|
Python
|
lgpl-2.1
|
libAtoms/matscipy,libAtoms/matscipy,libAtoms/matscipy,libAtoms/matscipy
|
import os
import glob
from numpy.distutils.core import setup, Extension
version = (os.popen('git config --get remote.origin.url').read() + ',' +
os.popen('git describe --always --tags --dirty').read())
scripts = []
setup(name='matscipy',
version=version,
description='Generic Python Materials Science tools',
maintainer='James Kermode & Lars Pastewka',
maintainer_email='[email protected]',
license='LGPLv2.1+',
package_dir={'matscipy': 'matscipy'},
- packages=['matscipy'],
+ packages=['matscipy', 'matscipy.fracture_mechanics'],
scripts=scripts,
ext_modules=[
Extension(
'_matscipy',
[ 'c/matscipymodule.c' ],
)
]
)
|
Add matscipy.fracture_mechanics to packages list to install subpackage
|
## Code Before:
import os
import glob
from numpy.distutils.core import setup, Extension
version = (os.popen('git config --get remote.origin.url').read() + ',' +
os.popen('git describe --always --tags --dirty').read())
scripts = []
setup(name='matscipy',
version=version,
description='Generic Python Materials Science tools',
maintainer='James Kermode & Lars Pastewka',
maintainer_email='[email protected]',
license='LGPLv2.1+',
package_dir={'matscipy': 'matscipy'},
packages=['matscipy'],
scripts=scripts,
ext_modules=[
Extension(
'_matscipy',
[ 'c/matscipymodule.c' ],
)
]
)
## Instruction:
Add matscipy.fracture_mechanics to packages list to install subpackage
## Code After:
import os
import glob
from numpy.distutils.core import setup, Extension
version = (os.popen('git config --get remote.origin.url').read() + ',' +
os.popen('git describe --always --tags --dirty').read())
scripts = []
setup(name='matscipy',
version=version,
description='Generic Python Materials Science tools',
maintainer='James Kermode & Lars Pastewka',
maintainer_email='[email protected]',
license='LGPLv2.1+',
package_dir={'matscipy': 'matscipy'},
packages=['matscipy', 'matscipy.fracture_mechanics'],
scripts=scripts,
ext_modules=[
Extension(
'_matscipy',
[ 'c/matscipymodule.c' ],
)
]
)
|
// ... existing code ...
package_dir={'matscipy': 'matscipy'},
packages=['matscipy', 'matscipy.fracture_mechanics'],
scripts=scripts,
// ... rest of the code ...
|
a7028ca3d3dea5a9f8891dfd2947b671bbe02b7e
|
pentai/gui/my_button.py
|
pentai/gui/my_button.py
|
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
|
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
|
Make "silent" an attribute from __init__
|
Make "silent" an attribute from __init__
|
Python
|
mit
|
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
|
from kivy.uix.button import Button
import audio as a_m
+ from pentai.base.defines import *
class MyButton(Button):
+ def __init__(self, *args, **kwargs):
+ super(MyButton, self).__init__(*args, **kwargs)
+ self.silent = False
+
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
- if not hasattr(self, "silent"):
+ if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
- if not hasattr(self, "silent"):
+ if not self.silent:
a_m.instance.click()
|
Make "silent" an attribute from __init__
|
## Code Before:
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
## Instruction:
Make "silent" an attribute from __init__
## Code After:
from kivy.uix.button import Button
import audio as a_m
from pentai.base.defines import *
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
super(MyButton, self).on_touch_up(touch, *args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self, ignored=None):
self.state = "normal"
if not self.silent:
a_m.instance.click()
|
# ... existing code ...
import audio as a_m
from pentai.base.defines import *
# ... modified code ...
class MyButton(Button):
def __init__(self, *args, **kwargs):
super(MyButton, self).__init__(*args, **kwargs)
self.silent = False
def on_touch_up(self, touch, *args, **kwargs):
...
if self.collide_point(*touch.pos):
if not self.silent:
a_m.instance.click()
...
self.state = "normal"
if not self.silent:
a_m.instance.click()
# ... rest of the code ...
|
4c1237d2969d735cfcf9f3c10cf27cb801996e32
|
tests/test_integration.py
|
tests/test_integration.py
|
"""Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
|
"""Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
|
Use Sauce Labs for selenium testing when available
|
Use Sauce Labs for selenium testing when available
|
Python
|
bsd-3-clause
|
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
|
"""Unit test module for Selenium testing"""
+ import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
+ if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
+
+ capabilities = {
+ "tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
+ "build": os.environ["TRAVIS_BUILD_NUMBER"],
+ "tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
+ }
+ url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
+ username=os.environ["SAUCE_USERNAME"],
+ access_key=os.environ["SAUCE_ACCESS_KEY"],
+ )
+
+ self.driver = webdriver.Remote(
+ desired_capabilities=capabilities,
+ command_executor=url
+ )
+
+ else:
- self.driver = webdriver.Firefox()
+ self.driver = webdriver.Firefox()
+
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
|
Use Sauce Labs for selenium testing when available
|
## Code Before:
"""Unit test module for Selenium testing"""
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
## Instruction:
Use Sauce Labs for selenium testing when available
## Code After:
"""Unit test module for Selenium testing"""
import os
from selenium import webdriver
from flask.ext.testing import LiveServerTestCase
from tests import TestCase
from pages import LoginPage
class TestUI(TestCase, LiveServerTestCase):
"""Test class for UI integration/workflow testing"""
def setUp(self):
"""Reset all tables before testing."""
super(TestUI, self).setUp()
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
self.driver.root_uri = self.get_server_url()
def tearDown(self):
"""Clean db session, drop all tables."""
self.driver.quit()
super(TestUI, self).tearDown()
def test_login_page(self):
"""Ensure login page loads successfully"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertNotIn("Uh-oh", page.w.find_element_by_tag_name("body").text)
def test_login_form_facebook_exists(self):
"""Ensure Facebook button present on login form"""
page = LoginPage(self.driver)
page.get("/user/sign-in")
self.assertIsNotNone(page.facebook_button)
|
# ... existing code ...
"""Unit test module for Selenium testing"""
import os
from selenium import webdriver
# ... modified code ...
if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:
capabilities = {
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_BUILD_NUMBER"],
"tags": [os.environ["TRAVIS_PYTHON_VERSION"], "CI"],
}
url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
username=os.environ["SAUCE_USERNAME"],
access_key=os.environ["SAUCE_ACCESS_KEY"],
)
self.driver = webdriver.Remote(
desired_capabilities=capabilities,
command_executor=url
)
else:
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(60)
# ... rest of the code ...
|
60cbe21d95cc6e079979022a505dcc2099bd30c1
|
cla_public/libs/call_centre_availability.py
|
cla_public/libs/call_centre_availability.py
|
import datetime
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
|
import datetime
from cla_public.libs.utils import get_locale
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix_welsh(day):
ordinals = {
"1": "af",
"2": "il",
"3": "ydd",
"4": "ydd",
"5": "ed",
"6": "ed",
"7": "fed",
"8": "fed",
"9": "fed",
"10": "fed",
"11": "eg",
"12": "fed",
"13": "eg",
"14": "eg",
"15": "fed",
"16": "eg",
"17": "eg",
"18": "fed",
"19": "eg",
"20": "fed",
}
return ordinals.get(str(day), "ain")
def suffix_english(day):
if 11 <= day <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(day % 10, _("th"))
def suffix(day):
if get_locale()[:2] == "cy":
return suffix_welsh(day)
return suffix_english(day)
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
|
Add welsh days ordinal suffix
|
Add welsh days ordinal suffix
|
Python
|
mit
|
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
|
import datetime
+ from cla_public.libs.utils import get_locale
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
- def suffix(d):
+ def suffix_welsh(day):
+ ordinals = {
+ "1": "af",
+ "2": "il",
+ "3": "ydd",
+ "4": "ydd",
+ "5": "ed",
+ "6": "ed",
+ "7": "fed",
+ "8": "fed",
+ "9": "fed",
+ "10": "fed",
+ "11": "eg",
+ "12": "fed",
+ "13": "eg",
+ "14": "eg",
+ "15": "fed",
+ "16": "eg",
+ "17": "eg",
+ "18": "fed",
+ "19": "eg",
+ "20": "fed",
+ }
+ return ordinals.get(str(day), "ain")
+
+
+ def suffix_english(day):
- if 11 <= d <= 13:
+ if 11 <= day <= 13:
return _("th")
- return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
+ return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(day % 10, _("th"))
+
+
+ def suffix(day):
+ if get_locale()[:2] == "cy":
+ return suffix_welsh(day)
+
+ return suffix_english(day)
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
|
Add welsh days ordinal suffix
|
## Code Before:
import datetime
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix(d):
if 11 <= d <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(d % 10, _("th"))
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
## Instruction:
Add welsh days ordinal suffix
## Code After:
import datetime
from cla_public.libs.utils import get_locale
from flask.ext.babel import lazy_gettext as _
def time_choice(time):
display_format = "%I:%M %p"
end = time + datetime.timedelta(minutes=30)
display_string = time.strftime(display_format).lstrip("0") + " - " + end.strftime(display_format).lstrip("0")
return time.strftime("%H%M"), display_string
def suffix_welsh(day):
ordinals = {
"1": "af",
"2": "il",
"3": "ydd",
"4": "ydd",
"5": "ed",
"6": "ed",
"7": "fed",
"8": "fed",
"9": "fed",
"10": "fed",
"11": "eg",
"12": "fed",
"13": "eg",
"14": "eg",
"15": "fed",
"16": "eg",
"17": "eg",
"18": "fed",
"19": "eg",
"20": "fed",
}
return ordinals.get(str(day), "ain")
def suffix_english(day):
if 11 <= day <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(day % 10, _("th"))
def suffix(day):
if get_locale()[:2] == "cy":
return suffix_welsh(day)
return suffix_english(day)
def day_choice(day):
return day.strftime("%Y%m%d"), "%s %s%s" % (_(day.strftime("%A")), day.strftime("%d").lstrip("0"), suffix(day.day))
|
// ... existing code ...
import datetime
from cla_public.libs.utils import get_locale
from flask.ext.babel import lazy_gettext as _
// ... modified code ...
def suffix_welsh(day):
ordinals = {
"1": "af",
"2": "il",
"3": "ydd",
"4": "ydd",
"5": "ed",
"6": "ed",
"7": "fed",
"8": "fed",
"9": "fed",
"10": "fed",
"11": "eg",
"12": "fed",
"13": "eg",
"14": "eg",
"15": "fed",
"16": "eg",
"17": "eg",
"18": "fed",
"19": "eg",
"20": "fed",
}
return ordinals.get(str(day), "ain")
def suffix_english(day):
if 11 <= day <= 13:
return _("th")
return {1: _("st"), 2: _("nd"), 3: _("rd")}.get(day % 10, _("th"))
def suffix(day):
if get_locale()[:2] == "cy":
return suffix_welsh(day)
return suffix_english(day)
// ... rest of the code ...
|
93623d3bc8336073b65f586e2d1573831c492084
|
iatidataquality/__init__.py
|
iatidataquality/__init__.py
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey
|
Add survey controller to routes
|
Add survey controller to routes
|
Python
|
agpl-3.0
|
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
|
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
+ import survey
|
Add survey controller to routes
|
## Code Before:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
## Instruction:
Add survey controller to routes
## Code After:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__.split('.')[0])
app.config.from_pyfile('../config.py')
db = SQLAlchemy(app)
import api
import routes
import publishers
import publisher_conditions
import tests
import organisations
import organisations_feedback
import registry
import packages
import indicators
import aggregationtypes
import survey
|
...
import aggregationtypes
import survey
...
|
6947a38fd99447809870d82a425abd4db9d884fe
|
test/htmltoreadable.py
|
test/htmltoreadable.py
|
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.css('.post_show')
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(path):
os.mkdir(path)
outpath = os.path.join(path, 'out.log')
with codecs.open(outpath, 'w', encoding='utf-8') as fh:
fh.write(text)
if __name__ == '__main__':
test()
|
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.doc.tree.cssselect('.post_show')[0]
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(path):
os.mkdir(path)
outpath = os.path.join(path, 'out.log')
with codecs.open(outpath, 'w', encoding='utf-8') as fh:
fh.write(text)
if __name__ == '__main__':
test()
|
Delete using deprecated fnc in test
|
Delete using deprecated fnc in test
|
Python
|
mit
|
shigarus/NewsParser
|
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
- root_node = g.css('.post_show')
+ root_node = g.doc.tree.cssselect('.post_show')[0]
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(path):
os.mkdir(path)
outpath = os.path.join(path, 'out.log')
with codecs.open(outpath, 'w', encoding='utf-8') as fh:
fh.write(text)
if __name__ == '__main__':
test()
|
Delete using deprecated fnc in test
|
## Code Before:
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.css('.post_show')
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(path):
os.mkdir(path)
outpath = os.path.join(path, 'out.log')
with codecs.open(outpath, 'w', encoding='utf-8') as fh:
fh.write(text)
if __name__ == '__main__':
test()
## Instruction:
Delete using deprecated fnc in test
## Code After:
import codecs
import os
import grab
from src import htmltoreadable as hr
def test():
g = grab.Grab()
g.go('http://habrahabr.ru/post/266293/')
root_node = g.doc.tree.cssselect('.post_show')[0]
text = hr.html_to_readable(root_node)
path = 'out'
if not os.path.exists(path):
os.mkdir(path)
outpath = os.path.join(path, 'out.log')
with codecs.open(outpath, 'w', encoding='utf-8') as fh:
fh.write(text)
if __name__ == '__main__':
test()
|
...
g.go('http://habrahabr.ru/post/266293/')
root_node = g.doc.tree.cssselect('.post_show')[0]
text = hr.html_to_readable(root_node)
...
|
dd4f4beb23c1a51c913cf2a2533c72df9fdca5fe
|
en-2017-06-25-consuming-and-publishing-celery-tasks-in-cpp-via-amqp/python/hello.py
|
en-2017-06-25-consuming-and-publishing-celery-tasks-in-cpp-via-amqp/python/hello.py
|
import sys
from tasks import hello
if __name__ == '__main__':
if len(sys.argv) != 3:
print('usage: {} NAME AGE'.format(sys.argv[0]))
sys.exit(1)
# By calling hello.delay(), we request hello() to be executed in a worker
# rather than executing it directly in the current process, which is what a
# direct call to hello() would do.
# http://docs.celeryproject.org/en/latest/userguide/calling.html
hello.delay(sys.argv[1], int(sys.argv[2]))
|
import sys
from tasks import hello
if __name__ == '__main__':
if len(sys.argv) != 3:
print('usage: {} NAME AGE'.format(sys.argv[0]))
sys.exit(1)
# By calling hello.delay(), we request hello() to be executed in a worker
# rather than executed directly in the current process, which is what a
# call to hello() would do.
# http://docs.celeryproject.org/en/latest/userguide/calling.html
hello.delay(sys.argv[1], int(sys.argv[2]))
|
Fix the phrasing in a comment.
|
en-2017-06-25: Fix the phrasing in a comment.
|
Python
|
bsd-3-clause
|
s3rvac/blog,s3rvac/blog,s3rvac/blog,s3rvac/blog
|
import sys
from tasks import hello
if __name__ == '__main__':
if len(sys.argv) != 3:
print('usage: {} NAME AGE'.format(sys.argv[0]))
sys.exit(1)
# By calling hello.delay(), we request hello() to be executed in a worker
- # rather than executing it directly in the current process, which is what a
+ # rather than executed directly in the current process, which is what a
- # direct call to hello() would do.
+ # call to hello() would do.
# http://docs.celeryproject.org/en/latest/userguide/calling.html
hello.delay(sys.argv[1], int(sys.argv[2]))
|
Fix the phrasing in a comment.
|
## Code Before:
import sys
from tasks import hello
if __name__ == '__main__':
if len(sys.argv) != 3:
print('usage: {} NAME AGE'.format(sys.argv[0]))
sys.exit(1)
# By calling hello.delay(), we request hello() to be executed in a worker
# rather than executing it directly in the current process, which is what a
# direct call to hello() would do.
# http://docs.celeryproject.org/en/latest/userguide/calling.html
hello.delay(sys.argv[1], int(sys.argv[2]))
## Instruction:
Fix the phrasing in a comment.
## Code After:
import sys
from tasks import hello
if __name__ == '__main__':
if len(sys.argv) != 3:
print('usage: {} NAME AGE'.format(sys.argv[0]))
sys.exit(1)
# By calling hello.delay(), we request hello() to be executed in a worker
# rather than executed directly in the current process, which is what a
# call to hello() would do.
# http://docs.celeryproject.org/en/latest/userguide/calling.html
hello.delay(sys.argv[1], int(sys.argv[2]))
|
...
# By calling hello.delay(), we request hello() to be executed in a worker
# rather than executed directly in the current process, which is what a
# call to hello() would do.
# http://docs.celeryproject.org/en/latest/userguide/calling.html
...
|
b946768acb8c9e34dbb72cb6d3bc33a7e67f4548
|
setup.py
|
setup.py
|
from distutils.core import setup
setup(
requires=['beautifulsoup4', 'requests'],
name='python-ninegag',
version='0.1',
py_modules=['pyninegag'],
url='https://github.com/sashgorokhov/python-ninegag',
license='MIT',
author='sashgorokhov',
author_email='[email protected]',
description='Python library to get stuff from 9gag.com'
)
|
from distutils.core import setup
with open('README.md') as file:
long_description = file.read()
setup(
requires=['beautifulsoup4', 'requests'],
name='python-ninegag',
version='0.1',
py_modules=['pyninegag'],
url='https://github.com/sashgorokhov/python-ninegag',
download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip',
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='[email protected]',
description='Python library to get stuff from 9gag.com'
)
|
Add download url and long description
|
Add download url and long description
|
Python
|
mit
|
sashgorokhov/python-ninegag
|
from distutils.core import setup
+
+ with open('README.md') as file:
+ long_description = file.read()
setup(
requires=['beautifulsoup4', 'requests'],
name='python-ninegag',
version='0.1',
py_modules=['pyninegag'],
url='https://github.com/sashgorokhov/python-ninegag',
+ download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip',
+ long_description=long_description,
- license='MIT',
+ license='MIT License',
author='sashgorokhov',
author_email='[email protected]',
description='Python library to get stuff from 9gag.com'
)
|
Add download url and long description
|
## Code Before:
from distutils.core import setup
setup(
requires=['beautifulsoup4', 'requests'],
name='python-ninegag',
version='0.1',
py_modules=['pyninegag'],
url='https://github.com/sashgorokhov/python-ninegag',
license='MIT',
author='sashgorokhov',
author_email='[email protected]',
description='Python library to get stuff from 9gag.com'
)
## Instruction:
Add download url and long description
## Code After:
from distutils.core import setup
with open('README.md') as file:
long_description = file.read()
setup(
requires=['beautifulsoup4', 'requests'],
name='python-ninegag',
version='0.1',
py_modules=['pyninegag'],
url='https://github.com/sashgorokhov/python-ninegag',
download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip',
long_description=long_description,
license='MIT License',
author='sashgorokhov',
author_email='[email protected]',
description='Python library to get stuff from 9gag.com'
)
|
# ... existing code ...
from distutils.core import setup
with open('README.md') as file:
long_description = file.read()
# ... modified code ...
url='https://github.com/sashgorokhov/python-ninegag',
download_url='https://github.com/sashgorokhov/python-ninegag/archive/master.zip',
long_description=long_description,
license='MIT License',
author='sashgorokhov',
# ... rest of the code ...
|
d9b804f72e54ffc9cb0f1cef8ce74aef1079ef76
|
tosec/management/commands/tosecscan.py
|
tosec/management/commands/tosecscan.py
|
import os
import hashlib
from tosec.models import Rom
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = '<folder>'
help = 'Scan a folder for TOSEC roms'
def handle(self, *args, **kwargs):
directory = args[0]
dest = os.path.join(directory, 'TOSEC')
if not os.path.exists(dest):
os.makedirs(dest)
self.stdout.write("Scanning %s" % directory)
for filename in os.listdir(directory):
abspath = os.path.join(directory, filename)
if not os.path.isfile(abspath):
continue
md5sum = hashlib.md5(open(abspath).read()).hexdigest()
rom = Rom.objects.filter(md5=md5sum)
if not rom:
continue
else:
rom = rom[0]
self.stdout.write("Found %s" % rom.name)
new_path = os.path.join(dest, rom.name)
os.rename(abspath, new_path)
|
import os
import hashlib
from tosec.models import Rom, Game
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = '<folder>'
help = 'Scan a folder for TOSEC roms'
def handle(self, *args, **kwargs):
directory = args[0]
dest = os.path.join(directory, 'TOSEC')
if not os.path.exists(dest):
os.makedirs(dest)
self.stdout.write("Scanning %s" % directory)
filenames = os.listdir(directory)
total_files = len(filenames)
tosec_sets = {} # Store TOSEC sets with number of found roms
for index, filename in enumerate(filenames, start=1):
abspath = os.path.join(directory, filename)
if not os.path.isfile(abspath):
continue
md5sum = hashlib.md5(open(abspath).read()).hexdigest()
try:
rom = Rom.objects.get(md5=md5sum)
except Rom.DoesNotExist:
continue
set_name = rom.game.category.name
if set_name in tosec_sets:
tosec_sets[set_name] += 1
else:
tosec_sets[set_name] = 1
self.stdout.write("[{} of {}] Found {}".format(index,
total_files,
rom.name))
new_path = os.path.join(dest, rom.name)
os.rename(abspath, new_path)
for set_name in tosec_sets:
set_size = Game.objects.filter(category__name=set_name).count()
self.stdout.write("{}: imported {} of {} games".format(
set_name, tosec_sets[set_name], set_size
))
|
Print report on imported TOSEC sets
|
Print report on imported TOSEC sets
|
Python
|
agpl-3.0
|
Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,lutris/website,Turupawn/website
|
import os
import hashlib
- from tosec.models import Rom
+ from tosec.models import Rom, Game
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = '<folder>'
help = 'Scan a folder for TOSEC roms'
def handle(self, *args, **kwargs):
directory = args[0]
dest = os.path.join(directory, 'TOSEC')
if not os.path.exists(dest):
os.makedirs(dest)
self.stdout.write("Scanning %s" % directory)
- for filename in os.listdir(directory):
+ filenames = os.listdir(directory)
+ total_files = len(filenames)
+ tosec_sets = {} # Store TOSEC sets with number of found roms
+ for index, filename in enumerate(filenames, start=1):
abspath = os.path.join(directory, filename)
if not os.path.isfile(abspath):
continue
md5sum = hashlib.md5(open(abspath).read()).hexdigest()
+ try:
- rom = Rom.objects.filter(md5=md5sum)
+ rom = Rom.objects.get(md5=md5sum)
- if not rom:
+ except Rom.DoesNotExist:
continue
+ set_name = rom.game.category.name
+ if set_name in tosec_sets:
+ tosec_sets[set_name] += 1
else:
- rom = rom[0]
-
- self.stdout.write("Found %s" % rom.name)
+ tosec_sets[set_name] = 1
+ self.stdout.write("[{} of {}] Found {}".format(index,
+ total_files,
+ rom.name))
new_path = os.path.join(dest, rom.name)
os.rename(abspath, new_path)
+ for set_name in tosec_sets:
+ set_size = Game.objects.filter(category__name=set_name).count()
+ self.stdout.write("{}: imported {} of {} games".format(
+ set_name, tosec_sets[set_name], set_size
+ ))
+
|
Print report on imported TOSEC sets
|
## Code Before:
import os
import hashlib
from tosec.models import Rom
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = '<folder>'
help = 'Scan a folder for TOSEC roms'
def handle(self, *args, **kwargs):
directory = args[0]
dest = os.path.join(directory, 'TOSEC')
if not os.path.exists(dest):
os.makedirs(dest)
self.stdout.write("Scanning %s" % directory)
for filename in os.listdir(directory):
abspath = os.path.join(directory, filename)
if not os.path.isfile(abspath):
continue
md5sum = hashlib.md5(open(abspath).read()).hexdigest()
rom = Rom.objects.filter(md5=md5sum)
if not rom:
continue
else:
rom = rom[0]
self.stdout.write("Found %s" % rom.name)
new_path = os.path.join(dest, rom.name)
os.rename(abspath, new_path)
## Instruction:
Print report on imported TOSEC sets
## Code After:
import os
import hashlib
from tosec.models import Rom, Game
from django.core.management.base import BaseCommand
class Command(BaseCommand):
args = '<folder>'
help = 'Scan a folder for TOSEC roms'
def handle(self, *args, **kwargs):
directory = args[0]
dest = os.path.join(directory, 'TOSEC')
if not os.path.exists(dest):
os.makedirs(dest)
self.stdout.write("Scanning %s" % directory)
filenames = os.listdir(directory)
total_files = len(filenames)
tosec_sets = {} # Store TOSEC sets with number of found roms
for index, filename in enumerate(filenames, start=1):
abspath = os.path.join(directory, filename)
if not os.path.isfile(abspath):
continue
md5sum = hashlib.md5(open(abspath).read()).hexdigest()
try:
rom = Rom.objects.get(md5=md5sum)
except Rom.DoesNotExist:
continue
set_name = rom.game.category.name
if set_name in tosec_sets:
tosec_sets[set_name] += 1
else:
tosec_sets[set_name] = 1
self.stdout.write("[{} of {}] Found {}".format(index,
total_files,
rom.name))
new_path = os.path.join(dest, rom.name)
os.rename(abspath, new_path)
for set_name in tosec_sets:
set_size = Game.objects.filter(category__name=set_name).count()
self.stdout.write("{}: imported {} of {} games".format(
set_name, tosec_sets[set_name], set_size
))
|
# ... existing code ...
import hashlib
from tosec.models import Rom, Game
from django.core.management.base import BaseCommand
# ... modified code ...
self.stdout.write("Scanning %s" % directory)
filenames = os.listdir(directory)
total_files = len(filenames)
tosec_sets = {} # Store TOSEC sets with number of found roms
for index, filename in enumerate(filenames, start=1):
abspath = os.path.join(directory, filename)
...
md5sum = hashlib.md5(open(abspath).read()).hexdigest()
try:
rom = Rom.objects.get(md5=md5sum)
except Rom.DoesNotExist:
continue
set_name = rom.game.category.name
if set_name in tosec_sets:
tosec_sets[set_name] += 1
else:
tosec_sets[set_name] = 1
self.stdout.write("[{} of {}] Found {}".format(index,
total_files,
rom.name))
new_path = os.path.join(dest, rom.name)
...
os.rename(abspath, new_path)
for set_name in tosec_sets:
set_size = Game.objects.filter(category__name=set_name).count()
self.stdout.write("{}: imported {} of {} games".format(
set_name, tosec_sets[set_name], set_size
))
# ... rest of the code ...
|
a895661f7ce1a814f308dbe8b5836a4cdb472c8c
|
cla_public/apps/base/filters.py
|
cla_public/apps/base/filters.py
|
import re
from cla_public.apps.base import base
@base.app_template_filter()
def matches(value, pattern):
return bool(re.search(pattern, value))
|
from cla_public.apps.base import base
@base.app_template_filter()
def test(value):
return value
|
Revert "BE: Update custom template filter"
|
Revert "BE: Update custom template filter"
This reverts commit ea0c0beb1d2aa0d5970b629ac06e6f9b9708bfdd.
|
Python
|
mit
|
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
|
- import re
from cla_public.apps.base import base
@base.app_template_filter()
- def matches(value, pattern):
- return bool(re.search(pattern, value))
+ def test(value):
+ return value
|
Revert "BE: Update custom template filter"
|
## Code Before:
import re
from cla_public.apps.base import base
@base.app_template_filter()
def matches(value, pattern):
return bool(re.search(pattern, value))
## Instruction:
Revert "BE: Update custom template filter"
## Code After:
from cla_public.apps.base import base
@base.app_template_filter()
def test(value):
return value
|
# ... existing code ...
from cla_public.apps.base import base
# ... modified code ...
@base.app_template_filter()
def test(value):
return value
# ... rest of the code ...
|
3492ae03c9cfc8322ba60522779c7c0eeb642dd3
|
server/models/event_subscription.py
|
server/models/event_subscription.py
|
"""This module contains the SQLAlchemy EventSubscription class definition."""
from server.models.db import db
class EventSubscription(db.Model):
"""SQLAlchemy EventSubscription class definition."""
__tablename__ = 'event_subscriptions'
user_id = db.Column(
'user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)
event_id = db.Column(
'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True)
event = db.relationship('Event', backref=db.backref('event_subscriptions'))
user = db.relationship('User', backref=db.backref('event_subscriptions'))
def __init__(self, event_id=None, user_id=None):
"""Constructor for EventSubscription class."""
self.event_id = event_id
self.user_id = user_id
|
"""This module contains the SQLAlchemy EventSubscription class definition."""
from server.models.db import db
class EventSubscription(db.Model):
"""SQLAlchemy EventSubscription class definition."""
__tablename__ = 'event_subscriptions'
user_id = db.Column(
'user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)
event_id = db.Column(
'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True)
def __init__(self, event_id=None, user_id=None):
"""Constructor for EventSubscription class."""
self.event_id = event_id
self.user_id = user_id
|
Fix issue with deleting event subscriptions
|
Fix issue with deleting event subscriptions
|
Python
|
mit
|
bnotified/api,bnotified/api
|
"""This module contains the SQLAlchemy EventSubscription class definition."""
from server.models.db import db
class EventSubscription(db.Model):
"""SQLAlchemy EventSubscription class definition."""
__tablename__ = 'event_subscriptions'
user_id = db.Column(
'user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)
event_id = db.Column(
'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True)
- event = db.relationship('Event', backref=db.backref('event_subscriptions'))
-
- user = db.relationship('User', backref=db.backref('event_subscriptions'))
-
def __init__(self, event_id=None, user_id=None):
"""Constructor for EventSubscription class."""
self.event_id = event_id
self.user_id = user_id
|
Fix issue with deleting event subscriptions
|
## Code Before:
"""This module contains the SQLAlchemy EventSubscription class definition."""
from server.models.db import db
class EventSubscription(db.Model):
"""SQLAlchemy EventSubscription class definition."""
__tablename__ = 'event_subscriptions'
user_id = db.Column(
'user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)
event_id = db.Column(
'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True)
event = db.relationship('Event', backref=db.backref('event_subscriptions'))
user = db.relationship('User', backref=db.backref('event_subscriptions'))
def __init__(self, event_id=None, user_id=None):
"""Constructor for EventSubscription class."""
self.event_id = event_id
self.user_id = user_id
## Instruction:
Fix issue with deleting event subscriptions
## Code After:
"""This module contains the SQLAlchemy EventSubscription class definition."""
from server.models.db import db
class EventSubscription(db.Model):
"""SQLAlchemy EventSubscription class definition."""
__tablename__ = 'event_subscriptions'
user_id = db.Column(
'user_id', db.Integer, db.ForeignKey('users.id'), primary_key=True)
event_id = db.Column(
'event_id', db.Integer, db.ForeignKey('events.id'), primary_key=True)
def __init__(self, event_id=None, user_id=None):
"""Constructor for EventSubscription class."""
self.event_id = event_id
self.user_id = user_id
|
// ... existing code ...
def __init__(self, event_id=None, user_id=None):
// ... rest of the code ...
|
5f799aa16b2bfd35fc68073e73b85cf9ad75ba47
|
tests/__init__.py
|
tests/__init__.py
|
"""Test Package set up."""
import oauth2client.util
__author__ = '[email protected] (Ali Afshar)'
def setup_package():
"""Run on testing package."""
oauth2client.util.positional_parameters_enforcement = 'EXCEPTION'
|
"""Test package set-up."""
from oauth2client import util
__author__ = '[email protected] (Ali Afshar)'
def setup_package():
"""Run on testing package."""
util.positional_parameters_enforcement = util.POSITIONAL_EXCEPTION
|
Use symbolic constant rather than literal value
|
Use symbolic constant rather than literal value
|
Python
|
apache-2.0
|
google/oauth2client,clancychilds/oauth2client,clancychilds/oauth2client,jonparrott/oauth2client,google/oauth2client,googleapis/oauth2client,googleapis/oauth2client,jonparrott/oauth2client
|
- """Test Package set up."""
+ """Test package set-up."""
+ from oauth2client import util
- import oauth2client.util
-
__author__ = '[email protected] (Ali Afshar)'
def setup_package():
"""Run on testing package."""
- oauth2client.util.positional_parameters_enforcement = 'EXCEPTION'
+ util.positional_parameters_enforcement = util.POSITIONAL_EXCEPTION
|
Use symbolic constant rather than literal value
|
## Code Before:
"""Test Package set up."""
import oauth2client.util
__author__ = '[email protected] (Ali Afshar)'
def setup_package():
"""Run on testing package."""
oauth2client.util.positional_parameters_enforcement = 'EXCEPTION'
## Instruction:
Use symbolic constant rather than literal value
## Code After:
"""Test package set-up."""
from oauth2client import util
__author__ = '[email protected] (Ali Afshar)'
def setup_package():
"""Run on testing package."""
util.positional_parameters_enforcement = util.POSITIONAL_EXCEPTION
|
// ... existing code ...
"""Test package set-up."""
from oauth2client import util
// ... modified code ...
"""Run on testing package."""
util.positional_parameters_enforcement = util.POSITIONAL_EXCEPTION
// ... rest of the code ...
|
b1feed0ced6d1328cc39bc9bba36331ec6da7803
|
pre_commit_hooks/detect_private_key.py
|
pre_commit_hooks/detect_private_key.py
|
from __future__ import print_function
import argparse
import sys
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
b'BEGIN OPENSSH PRIVATE KEY',
b'BEGIN PRIVATE KEY',
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
]
def detect_private_key(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
if private_key_files:
for private_key_file in private_key_files:
print('Private key found: {}'.format(private_key_file))
return 1
else:
return 0
if __name__ == '__main__':
sys.exit(detect_private_key())
|
from __future__ import print_function
import argparse
import sys
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
b'BEGIN OPENSSH PRIVATE KEY',
b'BEGIN PRIVATE KEY',
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
b'BEGIN PGP PRIVATE KEY BLOCK',
]
def detect_private_key(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
if private_key_files:
for private_key_file in private_key_files:
print('Private key found: {}'.format(private_key_file))
return 1
else:
return 0
if __name__ == '__main__':
sys.exit(detect_private_key())
|
Add ban for pgp/gpg private key blocks
|
Add ban for pgp/gpg private key blocks
|
Python
|
mit
|
pre-commit/pre-commit-hooks,Harwood/pre-commit-hooks
|
from __future__ import print_function
import argparse
import sys
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
b'BEGIN OPENSSH PRIVATE KEY',
b'BEGIN PRIVATE KEY',
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
+ b'BEGIN PGP PRIVATE KEY BLOCK',
]
def detect_private_key(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
if private_key_files:
for private_key_file in private_key_files:
print('Private key found: {}'.format(private_key_file))
return 1
else:
return 0
if __name__ == '__main__':
sys.exit(detect_private_key())
|
Add ban for pgp/gpg private key blocks
|
## Code Before:
from __future__ import print_function
import argparse
import sys
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
b'BEGIN OPENSSH PRIVATE KEY',
b'BEGIN PRIVATE KEY',
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
]
def detect_private_key(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
if private_key_files:
for private_key_file in private_key_files:
print('Private key found: {}'.format(private_key_file))
return 1
else:
return 0
if __name__ == '__main__':
sys.exit(detect_private_key())
## Instruction:
Add ban for pgp/gpg private key blocks
## Code After:
from __future__ import print_function
import argparse
import sys
BLACKLIST = [
b'BEGIN RSA PRIVATE KEY',
b'BEGIN DSA PRIVATE KEY',
b'BEGIN EC PRIVATE KEY',
b'BEGIN OPENSSH PRIVATE KEY',
b'BEGIN PRIVATE KEY',
b'PuTTY-User-Key-File-2',
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
b'BEGIN PGP PRIVATE KEY BLOCK',
]
def detect_private_key(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
private_key_files = []
for filename in args.filenames:
with open(filename, 'rb') as f:
content = f.read()
if any(line in content for line in BLACKLIST):
private_key_files.append(filename)
if private_key_files:
for private_key_file in private_key_files:
print('Private key found: {}'.format(private_key_file))
return 1
else:
return 0
if __name__ == '__main__':
sys.exit(detect_private_key())
|
// ... existing code ...
b'BEGIN SSH2 ENCRYPTED PRIVATE KEY',
b'BEGIN PGP PRIVATE KEY BLOCK',
]
// ... rest of the code ...
|
8259a733e1f039cea55cfc5aad7d69e0fb37c43c
|
tests.py
|
tests.py
|
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.assertEqual('USD', twenty_usd.currency)
self.assertEqual(21.8, twenty_usd.amount)
def test_convert_euro_to_brl(self):
twenty_brl = self.twenty_euro.to_brl()
self.assertIsInstance(twenty_brl, Money)
self.assertEqual('BRL', twenty_brl.currency)
self.assertEqual(85, twenty_brl.amount)
if __name__ == '__main__':
unittest.main()
|
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.assertEqual('USD', twenty_usd.currency)
self.assertEqual(21.8, twenty_usd.amount)
def test_convert_euro_to_brl(self):
twenty_brl = self.twenty_euro.to_brl()
self.assertIsInstance(twenty_brl, Money)
self.assertEqual('BRL', twenty_brl.currency)
self.assertEqual(85, twenty_brl.amount)
def test_invalid_method_pattern_call(self):
with self.assertRaises(AttributeError):
twenty_brl = self.twenty_euro.batman()
if __name__ == '__main__':
unittest.main()
|
Add test that validates method call
|
Add test that validates method call
|
Python
|
mit
|
mdsrosa/money-conversion-py
|
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.assertEqual('USD', twenty_usd.currency)
self.assertEqual(21.8, twenty_usd.amount)
def test_convert_euro_to_brl(self):
twenty_brl = self.twenty_euro.to_brl()
self.assertIsInstance(twenty_brl, Money)
self.assertEqual('BRL', twenty_brl.currency)
self.assertEqual(85, twenty_brl.amount)
+ def test_invalid_method_pattern_call(self):
+ with self.assertRaises(AttributeError):
+ twenty_brl = self.twenty_euro.batman()
+
+
if __name__ == '__main__':
unittest.main()
|
Add test that validates method call
|
## Code Before:
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.assertEqual('USD', twenty_usd.currency)
self.assertEqual(21.8, twenty_usd.amount)
def test_convert_euro_to_brl(self):
twenty_brl = self.twenty_euro.to_brl()
self.assertIsInstance(twenty_brl, Money)
self.assertEqual('BRL', twenty_brl.currency)
self.assertEqual(85, twenty_brl.amount)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add test that validates method call
## Code After:
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.assertEqual('USD', twenty_usd.currency)
self.assertEqual(21.8, twenty_usd.amount)
def test_convert_euro_to_brl(self):
twenty_brl = self.twenty_euro.to_brl()
self.assertIsInstance(twenty_brl, Money)
self.assertEqual('BRL', twenty_brl.currency)
self.assertEqual(85, twenty_brl.amount)
def test_invalid_method_pattern_call(self):
with self.assertRaises(AttributeError):
twenty_brl = self.twenty_euro.batman()
if __name__ == '__main__':
unittest.main()
|
// ... existing code ...
def test_invalid_method_pattern_call(self):
with self.assertRaises(AttributeError):
twenty_brl = self.twenty_euro.batman()
if __name__ == '__main__':
// ... rest of the code ...
|
59030daa60a4d2006cae6192219071e2a8017364
|
test/conftest.py
|
test/conftest.py
|
from os.path import join, dirname, abspath
default_base_dir = join(dirname(abspath(__file__)), 'completion')
import run
def pytest_addoption(parser):
parser.addoption(
"--base-dir", default=default_base_dir,
help="Directory in which integration test case files locate.")
parser.addoption(
"--thirdparty",
help="Include integration tests that requires third party modules.")
def pytest_generate_tests(metafunc):
"""
:type metafunc: _pytest.python.Metafunc
"""
if 'case' in metafunc.fixturenames:
base_dir = metafunc.config.option.base_dir
test_files = {}
thirdparty = metafunc.config.option.thirdparty
metafunc.parametrize(
'case',
run.collect_dir_tests(base_dir, test_files, thirdparty))
|
from os.path import join, dirname, abspath
default_base_dir = join(dirname(abspath(__file__)), 'completion')
import run
def pytest_addoption(parser):
parser.addoption(
"--base-dir", default=default_base_dir,
help="Directory in which integration test case files locate.")
parser.addoption(
"--test-files", "-T", default=[], action='append',
help=(
"Specify test files using FILE_NAME[:LINE[,LINE[,...]]]. "
"For example: -T generators.py:10,13,19. "
"Note that you can use -m to specify the test case by id."))
parser.addoption(
"--thirdparty",
help="Include integration tests that requires third party modules.")
def parse_test_files_option(opt):
"""
Parse option passed to --test-files into a key-value pair.
>>> parse_test_files_option('generators.py:10,13,19')
('generators.py', [10, 13, 19])
"""
opt = str(opt)
if ':' in opt:
(f_name, rest) = opt.split(':', 1)
return (f_name, list(map(int, rest.split(','))))
else:
return (opt, [])
def pytest_generate_tests(metafunc):
"""
:type metafunc: _pytest.python.Metafunc
"""
if 'case' in metafunc.fixturenames:
base_dir = metafunc.config.option.base_dir
test_files = dict(map(parse_test_files_option,
metafunc.config.option.test_files))
thirdparty = metafunc.config.option.thirdparty
metafunc.parametrize(
'case',
run.collect_dir_tests(base_dir, test_files, thirdparty))
|
Add --test-files option to py.test
|
Add --test-files option to py.test
At this point, py.test should be equivalent to test/run.py
|
Python
|
mit
|
tjwei/jedi,jonashaag/jedi,mfussenegger/jedi,jonashaag/jedi,dwillmer/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,dwillmer/jedi,flurischt/jedi,WoLpH/jedi,flurischt/jedi
|
from os.path import join, dirname, abspath
default_base_dir = join(dirname(abspath(__file__)), 'completion')
import run
def pytest_addoption(parser):
parser.addoption(
"--base-dir", default=default_base_dir,
help="Directory in which integration test case files locate.")
parser.addoption(
+ "--test-files", "-T", default=[], action='append',
+ help=(
+ "Specify test files using FILE_NAME[:LINE[,LINE[,...]]]. "
+ "For example: -T generators.py:10,13,19. "
+ "Note that you can use -m to specify the test case by id."))
+ parser.addoption(
"--thirdparty",
help="Include integration tests that requires third party modules.")
+
+
+ def parse_test_files_option(opt):
+ """
+ Parse option passed to --test-files into a key-value pair.
+
+ >>> parse_test_files_option('generators.py:10,13,19')
+ ('generators.py', [10, 13, 19])
+ """
+ opt = str(opt)
+ if ':' in opt:
+ (f_name, rest) = opt.split(':', 1)
+ return (f_name, list(map(int, rest.split(','))))
+ else:
+ return (opt, [])
def pytest_generate_tests(metafunc):
"""
:type metafunc: _pytest.python.Metafunc
"""
if 'case' in metafunc.fixturenames:
base_dir = metafunc.config.option.base_dir
- test_files = {}
+ test_files = dict(map(parse_test_files_option,
+ metafunc.config.option.test_files))
thirdparty = metafunc.config.option.thirdparty
metafunc.parametrize(
'case',
run.collect_dir_tests(base_dir, test_files, thirdparty))
|
Add --test-files option to py.test
|
## Code Before:
from os.path import join, dirname, abspath
default_base_dir = join(dirname(abspath(__file__)), 'completion')
import run
def pytest_addoption(parser):
parser.addoption(
"--base-dir", default=default_base_dir,
help="Directory in which integration test case files locate.")
parser.addoption(
"--thirdparty",
help="Include integration tests that requires third party modules.")
def pytest_generate_tests(metafunc):
"""
:type metafunc: _pytest.python.Metafunc
"""
if 'case' in metafunc.fixturenames:
base_dir = metafunc.config.option.base_dir
test_files = {}
thirdparty = metafunc.config.option.thirdparty
metafunc.parametrize(
'case',
run.collect_dir_tests(base_dir, test_files, thirdparty))
## Instruction:
Add --test-files option to py.test
## Code After:
from os.path import join, dirname, abspath
default_base_dir = join(dirname(abspath(__file__)), 'completion')
import run
def pytest_addoption(parser):
parser.addoption(
"--base-dir", default=default_base_dir,
help="Directory in which integration test case files locate.")
parser.addoption(
"--test-files", "-T", default=[], action='append',
help=(
"Specify test files using FILE_NAME[:LINE[,LINE[,...]]]. "
"For example: -T generators.py:10,13,19. "
"Note that you can use -m to specify the test case by id."))
parser.addoption(
"--thirdparty",
help="Include integration tests that requires third party modules.")
def parse_test_files_option(opt):
"""
Parse option passed to --test-files into a key-value pair.
>>> parse_test_files_option('generators.py:10,13,19')
('generators.py', [10, 13, 19])
"""
opt = str(opt)
if ':' in opt:
(f_name, rest) = opt.split(':', 1)
return (f_name, list(map(int, rest.split(','))))
else:
return (opt, [])
def pytest_generate_tests(metafunc):
"""
:type metafunc: _pytest.python.Metafunc
"""
if 'case' in metafunc.fixturenames:
base_dir = metafunc.config.option.base_dir
test_files = dict(map(parse_test_files_option,
metafunc.config.option.test_files))
thirdparty = metafunc.config.option.thirdparty
metafunc.parametrize(
'case',
run.collect_dir_tests(base_dir, test_files, thirdparty))
|
...
parser.addoption(
"--test-files", "-T", default=[], action='append',
help=(
"Specify test files using FILE_NAME[:LINE[,LINE[,...]]]. "
"For example: -T generators.py:10,13,19. "
"Note that you can use -m to specify the test case by id."))
parser.addoption(
"--thirdparty",
...
help="Include integration tests that requires third party modules.")
def parse_test_files_option(opt):
"""
Parse option passed to --test-files into a key-value pair.
>>> parse_test_files_option('generators.py:10,13,19')
('generators.py', [10, 13, 19])
"""
opt = str(opt)
if ':' in opt:
(f_name, rest) = opt.split(':', 1)
return (f_name, list(map(int, rest.split(','))))
else:
return (opt, [])
...
base_dir = metafunc.config.option.base_dir
test_files = dict(map(parse_test_files_option,
metafunc.config.option.test_files))
thirdparty = metafunc.config.option.thirdparty
...
|
42cc93590bef8e97c76e79110d2b64906c34690d
|
config_template.py
|
config_template.py
|
chatbot_ubuntu = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_swisscom = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_ubuntu_seq2seq = {
'socket_address': '',
'socket_port': ''
}
ate = {
'path': '',
'python_env': ''
}
neuroate = {
'path': '',
'python_env': ''
}
ner = {
'path': '',
'python_env': ''
}
kpextract = {
'path': '',
'fetcher_path': '',
'python_env': '',
'api_emb_url':''
}
neural_programmer = {
'socket_address': '',
'socket_port': '',
'mongo': False,
'mongo_address': '',
'mongo_port': '',
'mongo_db': '',
'mongo_feedback_coll': '',
'mongo_use_coll': ''
}
gsw_translator = {
'pbsmt_only_url': '',
'pbsmt_phono_url': '',
'pbsmt_ortho_url': '',
'pbsmt_cbnmt_url': ''
}
machine_translation_stdlangs = {
'base_url': ''
}
churn = {
'path' : '',
'python_env': '',
'e_host':'',
'e_port':
}
|
chatbot_ubuntu = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_swisscom = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_ubuntu_seq2seq = {
'socket_address': '',
'socket_port': ''
}
chatbot_goaloriented = {
'socket_address': '127.0.0.1',
'socket_port': 8889
}
ate = {
'path': '',
'python_env': ''
}
neuroate = {
'path': '',
'python_env': ''
}
ner = {
'path': '',
'python_env': ''
}
kpextract = {
'path': '',
'fetcher_path': '',
'python_env': '',
'api_emb_url':''
}
neural_programmer = {
'socket_address': '',
'socket_port': '',
'mongo': False,
'mongo_address': '',
'mongo_port': '',
'mongo_db': '',
'mongo_feedback_coll': '',
'mongo_use_coll': ''
}
gsw_translator = {
'pbsmt_only_url': '',
'pbsmt_phono_url': '',
'pbsmt_ortho_url': '',
'pbsmt_cbnmt_url': ''
}
machine_translation_stdlangs = {
'base_url': ''
}
churn = {
'path' : '',
'python_env': '',
'e_host':'',
'e_port': ''
}
|
Add ports and fix bug
|
Add ports and fix bug
|
Python
|
mit
|
nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos
|
chatbot_ubuntu = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_swisscom = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_ubuntu_seq2seq = {
'socket_address': '',
'socket_port': ''
}
+
+ chatbot_goaloriented = {
+ 'socket_address': '127.0.0.1',
+ 'socket_port': 8889
+ }
+
ate = {
'path': '',
'python_env': ''
}
neuroate = {
'path': '',
'python_env': ''
}
ner = {
'path': '',
'python_env': ''
}
kpextract = {
'path': '',
'fetcher_path': '',
'python_env': '',
'api_emb_url':''
}
neural_programmer = {
'socket_address': '',
'socket_port': '',
'mongo': False,
'mongo_address': '',
'mongo_port': '',
'mongo_db': '',
'mongo_feedback_coll': '',
'mongo_use_coll': ''
}
gsw_translator = {
'pbsmt_only_url': '',
'pbsmt_phono_url': '',
'pbsmt_ortho_url': '',
'pbsmt_cbnmt_url': ''
}
machine_translation_stdlangs = {
'base_url': ''
}
churn = {
'path' : '',
'python_env': '',
'e_host':'',
- 'e_port':
+ 'e_port': ''
}
|
Add ports and fix bug
|
## Code Before:
chatbot_ubuntu = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_swisscom = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_ubuntu_seq2seq = {
'socket_address': '',
'socket_port': ''
}
ate = {
'path': '',
'python_env': ''
}
neuroate = {
'path': '',
'python_env': ''
}
ner = {
'path': '',
'python_env': ''
}
kpextract = {
'path': '',
'fetcher_path': '',
'python_env': '',
'api_emb_url':''
}
neural_programmer = {
'socket_address': '',
'socket_port': '',
'mongo': False,
'mongo_address': '',
'mongo_port': '',
'mongo_db': '',
'mongo_feedback_coll': '',
'mongo_use_coll': ''
}
gsw_translator = {
'pbsmt_only_url': '',
'pbsmt_phono_url': '',
'pbsmt_ortho_url': '',
'pbsmt_cbnmt_url': ''
}
machine_translation_stdlangs = {
'base_url': ''
}
churn = {
'path' : '',
'python_env': '',
'e_host':'',
'e_port':
}
## Instruction:
Add ports and fix bug
## Code After:
chatbot_ubuntu = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_swisscom = {
'path': '',
'model_id': '',
'python_env': ''
}
chatbot_ubuntu_seq2seq = {
'socket_address': '',
'socket_port': ''
}
chatbot_goaloriented = {
'socket_address': '127.0.0.1',
'socket_port': 8889
}
ate = {
'path': '',
'python_env': ''
}
neuroate = {
'path': '',
'python_env': ''
}
ner = {
'path': '',
'python_env': ''
}
kpextract = {
'path': '',
'fetcher_path': '',
'python_env': '',
'api_emb_url':''
}
neural_programmer = {
'socket_address': '',
'socket_port': '',
'mongo': False,
'mongo_address': '',
'mongo_port': '',
'mongo_db': '',
'mongo_feedback_coll': '',
'mongo_use_coll': ''
}
gsw_translator = {
'pbsmt_only_url': '',
'pbsmt_phono_url': '',
'pbsmt_ortho_url': '',
'pbsmt_cbnmt_url': ''
}
machine_translation_stdlangs = {
'base_url': ''
}
churn = {
'path' : '',
'python_env': '',
'e_host':'',
'e_port': ''
}
|
...
}
chatbot_goaloriented = {
'socket_address': '127.0.0.1',
'socket_port': 8889
}
ate = {
...
'e_host':'',
'e_port': ''
}
...
|
f1436f7f5140ea51fd5fc1f231e28f57c69f0cb1
|
tutorials/urls.py
|
tutorials/urls.py
|
from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
]
|
from django.conf.urls import include, url
from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
# this not working correctly - some error in gatherTutorials
url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'),
url(r'^markdownx/', include(markdownx)),
]
|
Add markdownx url, Add add-tutrorial url
|
Add markdownx url, Add add-tutrorial url
|
Python
|
agpl-3.0
|
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
|
from django.conf.urls import include, url
+ from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
+ # this not working correctly - some error in gatherTutorials
+ url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'),
+ url(r'^markdownx/', include(markdownx)),
]
|
Add markdownx url, Add add-tutrorial url
|
## Code Before:
from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
]
## Instruction:
Add markdownx url, Add add-tutrorial url
## Code After:
from django.conf.urls import include, url
from markdownx import urls as markdownx
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
# this not working correctly - some error in gatherTutorials
url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'),
url(r'^markdownx/', include(markdownx)),
]
|
...
from django.conf.urls import include, url
from markdownx import urls as markdownx
...
url(r'^(?P<tutorial_id>[\w\-]+)/$', views.TutorialDetail.as_view()),
# this not working correctly - some error in gatherTutorials
url(r'/add/', views.NewTutorial.as_view(), name='add_tutorial'),
url(r'^markdownx/', include(markdownx)),
]
...
|
58846603f8a5310bb0e6e1eaa9f9f599c315b041
|
django_webtest/response.py
|
django_webtest/response.py
|
from django.test import Client
from django.http import SimpleCookie
from webtest import TestResponse
from django_webtest.compat import urlparse
class DjangoWebtestResponse(TestResponse):
"""
WebOb's Response quacking more like django's HttpResponse.
This is here to make more django's TestCase asserts work,
not to provide a generally useful proxy.
"""
streaming = False
@property
def status_code(self):
return self.status_int
@property
def _charset(self):
return self.charset
@property
def content(self):
return self.body
@property
def client(self):
client = Client()
client.cookies = SimpleCookie()
for k,v in self.test_app.cookies.items():
client.cookies[k] = v
return client
def __getitem__(self, item):
item = item.lower()
if item == 'location':
# django's test response returns location as http://testserver/,
# WebTest returns it as http://localhost:80/
e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(self.location)
if e_netloc == 'localhost:80':
e_netloc = 'testserver'
return urlparse.urlunsplit([e_scheme, e_netloc, e_path, e_query, e_fragment])
for header, value in self.headerlist:
if header.lower() == item:
return value
raise KeyError(item)
|
from django.test import Client
from django.http import SimpleCookie
from webtest import TestResponse
from django_webtest.compat import urlparse
class DjangoWebtestResponse(TestResponse):
"""
WebOb's Response quacking more like django's HttpResponse.
This is here to make more django's TestCase asserts work,
not to provide a generally useful proxy.
"""
streaming = False
@property
def status_code(self):
return self.status_int
@property
def _charset(self):
return self.charset
@property
def content(self):
return self.body
@property
def url(self):
return self['location']
@property
def client(self):
client = Client()
client.cookies = SimpleCookie()
for k,v in self.test_app.cookies.items():
client.cookies[k] = v
return client
def __getitem__(self, item):
item = item.lower()
if item == 'location':
# django's test response returns location as http://testserver/,
# WebTest returns it as http://localhost:80/
e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(self.location)
if e_netloc == 'localhost:80':
e_netloc = 'testserver'
return urlparse.urlunsplit([e_scheme, e_netloc, e_path, e_query, e_fragment])
for header, value in self.headerlist:
if header.lower() == item:
return value
raise KeyError(item)
|
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
|
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
|
Python
|
mit
|
kmike/django-webtest,helenst/django-webtest,vaad2/django-webtest,django-webtest/django-webtest,abbottc/django-webtest,kharandziuk/django-webtest,abbottc/django-webtest,MikeAmy/django-webtest,andrewyoung1991/django-webtest,helenst/django-webtest,yrik/django-webtest,andrewyoung1991/django-webtest,andriisoldatenko/django-webtest,larssos/django-webtest,django-webtest/django-webtest,kmike/django-webtest,wbbradley/django-webtest,andriisoldatenko/django-webtest
|
from django.test import Client
from django.http import SimpleCookie
from webtest import TestResponse
from django_webtest.compat import urlparse
class DjangoWebtestResponse(TestResponse):
"""
WebOb's Response quacking more like django's HttpResponse.
This is here to make more django's TestCase asserts work,
not to provide a generally useful proxy.
"""
streaming = False
@property
def status_code(self):
return self.status_int
@property
def _charset(self):
return self.charset
@property
def content(self):
return self.body
@property
+ def url(self):
+ return self['location']
+
+ @property
def client(self):
client = Client()
client.cookies = SimpleCookie()
for k,v in self.test_app.cookies.items():
client.cookies[k] = v
return client
def __getitem__(self, item):
item = item.lower()
if item == 'location':
# django's test response returns location as http://testserver/,
# WebTest returns it as http://localhost:80/
e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(self.location)
if e_netloc == 'localhost:80':
e_netloc = 'testserver'
return urlparse.urlunsplit([e_scheme, e_netloc, e_path, e_query, e_fragment])
for header, value in self.headerlist:
if header.lower() == item:
return value
raise KeyError(item)
|
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
|
## Code Before:
from django.test import Client
from django.http import SimpleCookie
from webtest import TestResponse
from django_webtest.compat import urlparse
class DjangoWebtestResponse(TestResponse):
"""
WebOb's Response quacking more like django's HttpResponse.
This is here to make more django's TestCase asserts work,
not to provide a generally useful proxy.
"""
streaming = False
@property
def status_code(self):
return self.status_int
@property
def _charset(self):
return self.charset
@property
def content(self):
return self.body
@property
def client(self):
client = Client()
client.cookies = SimpleCookie()
for k,v in self.test_app.cookies.items():
client.cookies[k] = v
return client
def __getitem__(self, item):
item = item.lower()
if item == 'location':
# django's test response returns location as http://testserver/,
# WebTest returns it as http://localhost:80/
e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(self.location)
if e_netloc == 'localhost:80':
e_netloc = 'testserver'
return urlparse.urlunsplit([e_scheme, e_netloc, e_path, e_query, e_fragment])
for header, value in self.headerlist:
if header.lower() == item:
return value
raise KeyError(item)
## Instruction:
Add url property to DjangoWebtestResponse so assertRedirects works in 1.6.
## Code After:
from django.test import Client
from django.http import SimpleCookie
from webtest import TestResponse
from django_webtest.compat import urlparse
class DjangoWebtestResponse(TestResponse):
"""
WebOb's Response quacking more like django's HttpResponse.
This is here to make more django's TestCase asserts work,
not to provide a generally useful proxy.
"""
streaming = False
@property
def status_code(self):
return self.status_int
@property
def _charset(self):
return self.charset
@property
def content(self):
return self.body
@property
def url(self):
return self['location']
@property
def client(self):
client = Client()
client.cookies = SimpleCookie()
for k,v in self.test_app.cookies.items():
client.cookies[k] = v
return client
def __getitem__(self, item):
item = item.lower()
if item == 'location':
# django's test response returns location as http://testserver/,
# WebTest returns it as http://localhost:80/
e_scheme, e_netloc, e_path, e_query, e_fragment = urlparse.urlsplit(self.location)
if e_netloc == 'localhost:80':
e_netloc = 'testserver'
return urlparse.urlunsplit([e_scheme, e_netloc, e_path, e_query, e_fragment])
for header, value in self.headerlist:
if header.lower() == item:
return value
raise KeyError(item)
|
# ... existing code ...
@property
def url(self):
return self['location']
@property
def client(self):
# ... rest of the code ...
|
568dce643d9e88ebd9e5b395accb3027e02febb7
|
backend/conferences/models/duration.py
|
backend/conferences/models/duration.py
|
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
related_name="durations",
)
name = models.CharField(_("name"), max_length=100)
duration = models.PositiveIntegerField(
_("duration"), validators=[MinValueValidator(1)]
)
notes = models.TextField(_("notes"), blank=True)
allowed_submission_types = models.ManyToManyField(
"submissions.SubmissionType", verbose_name=_("allowed submission types")
)
def __str__(self):
return f"{self.name} - {self.duration} mins ({self.conference_id})"
class Meta:
verbose_name = _("Duration")
verbose_name_plural = _("Durations")
|
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
related_name="durations",
)
name = models.CharField(_("name"), max_length=100)
duration = models.PositiveIntegerField(
_("duration"), validators=[MinValueValidator(1)]
)
notes = models.TextField(_("notes"), blank=True)
allowed_submission_types = models.ManyToManyField(
"submissions.SubmissionType", verbose_name=_("allowed submission types")
)
def __str__(self):
return (
f"{self.name} - {self.duration} mins (at Conference "
f"{self.conference.name} <{self.conference.code}>)"
)
class Meta:
verbose_name = _("Duration")
verbose_name_plural = _("Durations")
|
Fix Duration.__str__ to show Conference name and code
|
Fix Duration.__str__ to show Conference name and code
|
Python
|
mit
|
patrick91/pycon,patrick91/pycon
|
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
related_name="durations",
)
name = models.CharField(_("name"), max_length=100)
duration = models.PositiveIntegerField(
_("duration"), validators=[MinValueValidator(1)]
)
notes = models.TextField(_("notes"), blank=True)
allowed_submission_types = models.ManyToManyField(
"submissions.SubmissionType", verbose_name=_("allowed submission types")
)
def __str__(self):
+ return (
- return f"{self.name} - {self.duration} mins ({self.conference_id})"
+ f"{self.name} - {self.duration} mins (at Conference "
+ f"{self.conference.name} <{self.conference.code}>)"
+ )
class Meta:
verbose_name = _("Duration")
verbose_name_plural = _("Durations")
|
Fix Duration.__str__ to show Conference name and code
|
## Code Before:
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
related_name="durations",
)
name = models.CharField(_("name"), max_length=100)
duration = models.PositiveIntegerField(
_("duration"), validators=[MinValueValidator(1)]
)
notes = models.TextField(_("notes"), blank=True)
allowed_submission_types = models.ManyToManyField(
"submissions.SubmissionType", verbose_name=_("allowed submission types")
)
def __str__(self):
return f"{self.name} - {self.duration} mins ({self.conference_id})"
class Meta:
verbose_name = _("Duration")
verbose_name_plural = _("Durations")
## Instruction:
Fix Duration.__str__ to show Conference name and code
## Code After:
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Duration(models.Model):
conference = models.ForeignKey(
"conferences.Conference",
on_delete=models.CASCADE,
verbose_name=_("conference"),
related_name="durations",
)
name = models.CharField(_("name"), max_length=100)
duration = models.PositiveIntegerField(
_("duration"), validators=[MinValueValidator(1)]
)
notes = models.TextField(_("notes"), blank=True)
allowed_submission_types = models.ManyToManyField(
"submissions.SubmissionType", verbose_name=_("allowed submission types")
)
def __str__(self):
return (
f"{self.name} - {self.duration} mins (at Conference "
f"{self.conference.name} <{self.conference.code}>)"
)
class Meta:
verbose_name = _("Duration")
verbose_name_plural = _("Durations")
|
# ... existing code ...
def __str__(self):
return (
f"{self.name} - {self.duration} mins (at Conference "
f"{self.conference.name} <{self.conference.code}>)"
)
# ... rest of the code ...
|
091f9daf8758e56c82dbe7a88a50489ab279f793
|
adhocracy/lib/helpers/site_helper.py
|
adhocracy/lib/helpers/site_helper.py
|
from pylons import config, g
from pylons.i18n import _
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
|
from pylons import config, g
from pylons.i18n import _
def domain():
return config.get('adhocracy.domain').split(':')[0]
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
|
Add h.site.domain() to return the domian without the port
|
Add h.site.domain() to return the domian without the port
|
Python
|
agpl-3.0
|
DanielNeugebauer/adhocracy,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,SysTheron/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,SysTheron/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,SysTheron/adhocracy,phihag/adhocracy,phihag/adhocracy,phihag/adhocracy
|
from pylons import config, g
from pylons.i18n import _
+
+
+ def domain():
+ return config.get('adhocracy.domain').split(':')[0]
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
|
Add h.site.domain() to return the domian without the port
|
## Code Before:
from pylons import config, g
from pylons.i18n import _
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
## Instruction:
Add h.site.domain() to return the domian without the port
## Code After:
from pylons import config, g
from pylons.i18n import _
def domain():
return config.get('adhocracy.domain').split(':')[0]
def name():
return config.get('adhocracy.site.name', _("Adhocracy"))
def base_url(instance, path=None):
url = "%s://" % config.get('adhocracy.protocol', 'http').strip()
if instance is not None and g.single_instance is None:
url += instance.key + "."
url += config.get('adhocracy.domain').strip()
if path is not None:
url += path
return url
def shortlink_url(delegateable):
path = "/d/%s" % delegateable.id
return base_url(None, path=path)
|
# ... existing code ...
from pylons.i18n import _
def domain():
return config.get('adhocracy.domain').split(':')[0]
# ... rest of the code ...
|
31b7ad0eaf4f74503a970e0cee303eb3bc5ea460
|
charity_server.py
|
charity_server.py
|
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/")
def gci():
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
Switch to datetime based on calls for updates.
|
Switch to datetime based on calls for updates.
|
Python
|
mit
|
colmcoughlan/alchemy-server
|
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
+ from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
+ start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
- @app.route("/")
+ @app.route("/gci")
def gci():
+ delta = datetime.now() - start_time
+ if delta.total_seconds() > refresh_rate:
+ categories, charity_dict = refresh_charities()
+ payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
Switch to datetime based on calls for updates.
|
## Code Before:
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
refresh_rate = 24 * 60 * 60 #Seconds
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/")
def gci():
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
## Instruction:
Switch to datetime based on calls for updates.
## Code After:
from flask import Flask, jsonify
from parse_likecharity import refresh_charities
import threading
from datetime import datetime
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
# variables that are accessible from anywhere
payload = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
backgroundThread = threading.Thread()
app = Flask(__name__)
def update_charities():
print('Updating charities in background thread')
global payload
global backgroundThread
with dataLock:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
print('Running!')
# Set the next thread to happen
backgroundThread = threading.Timer(refresh_rate, update_charities, ())
backgroundThread.start()
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
if __name__ == "__main__":
update_charities()
app.run(host='0.0.0.0')
backgroundThread.cancel()
print('test')
|
...
import threading
from datetime import datetime
...
refresh_rate = 24 * 60 * 60 #Seconds
start_time = datetime.now()
...
@app.route("/gci")
def gci():
delta = datetime.now() - start_time
if delta.total_seconds() > refresh_rate:
categories, charity_dict = refresh_charities()
payload = {'categories':categories, 'charities':charity_dict}
return jsonify(payload)
...
|
b7175449096717dcce9d3f90dd55e341a350b47b
|
flask_nav/elements.py
|
flask_nav/elements.py
|
from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagItem(NavigationItem):
def __init__(self, title, **attribs):
self.title = title
self.attribs = attribs
class View(NavigationItem):
def __init__(self, title, endpoint, *args, **kwargs):
self.title = title
self.endpoint = endpoint
self.url_for_args = args
self.url_for_kwargs = kwargs
def get_url(self):
return url_for(self.endpoint,
*self.url_for_args,
**self.url_for_kwargs)
@property
def active(self):
# this is a better check because it takes arguments into account
return request.path == self.get_url()
class Separator(NavigationItem):
pass
class Subgroup(NavigationItem):
def __init__(self, title, *items):
self.title = title
self.items = items
class Label(TagItem):
pass
class Link(TagItem):
pass
class Navbar(Subgroup):
id = 'nav_no_id'
|
from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
active = False
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagItem(NavigationItem):
def __init__(self, title, **attribs):
self.title = title
self.attribs = attribs
class View(NavigationItem):
def __init__(self, title, endpoint, *args, **kwargs):
self.title = title
self.endpoint = endpoint
self.url_for_args = args
self.url_for_kwargs = kwargs
def get_url(self):
return url_for(self.endpoint,
*self.url_for_args,
**self.url_for_kwargs)
@property
def active(self):
# this is a better check because it takes arguments into account
return request.path == self.get_url()
class Separator(NavigationItem):
pass
class Subgroup(NavigationItem):
def __init__(self, title, *items):
self.title = title
self.items = items
class Label(TagItem):
pass
class Link(TagItem):
pass
class Navbar(Subgroup):
id = 'nav_no_id'
|
Make all navigation items have an active attribute.
|
Make all navigation items have an active attribute.
|
Python
|
mit
|
mbr/flask-nav,mbr/flask-nav
|
from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
+ active = False
+
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagItem(NavigationItem):
def __init__(self, title, **attribs):
self.title = title
self.attribs = attribs
class View(NavigationItem):
def __init__(self, title, endpoint, *args, **kwargs):
self.title = title
self.endpoint = endpoint
self.url_for_args = args
self.url_for_kwargs = kwargs
def get_url(self):
return url_for(self.endpoint,
*self.url_for_args,
**self.url_for_kwargs)
@property
def active(self):
# this is a better check because it takes arguments into account
return request.path == self.get_url()
class Separator(NavigationItem):
pass
class Subgroup(NavigationItem):
def __init__(self, title, *items):
self.title = title
self.items = items
class Label(TagItem):
pass
class Link(TagItem):
pass
class Navbar(Subgroup):
id = 'nav_no_id'
|
Make all navigation items have an active attribute.
|
## Code Before:
from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagItem(NavigationItem):
def __init__(self, title, **attribs):
self.title = title
self.attribs = attribs
class View(NavigationItem):
def __init__(self, title, endpoint, *args, **kwargs):
self.title = title
self.endpoint = endpoint
self.url_for_args = args
self.url_for_kwargs = kwargs
def get_url(self):
return url_for(self.endpoint,
*self.url_for_args,
**self.url_for_kwargs)
@property
def active(self):
# this is a better check because it takes arguments into account
return request.path == self.get_url()
class Separator(NavigationItem):
pass
class Subgroup(NavigationItem):
def __init__(self, title, *items):
self.title = title
self.items = items
class Label(TagItem):
pass
class Link(TagItem):
pass
class Navbar(Subgroup):
id = 'nav_no_id'
## Instruction:
Make all navigation items have an active attribute.
## Code After:
from flask import url_for, request, current_app
from markupsafe import Markup
from . import get_renderer
class NavigationItem(object):
active = False
def render(self, renderer=None, **kwargs):
return Markup(
get_renderer(current_app, renderer)(**kwargs).visit(self)
)
class TagItem(NavigationItem):
def __init__(self, title, **attribs):
self.title = title
self.attribs = attribs
class View(NavigationItem):
def __init__(self, title, endpoint, *args, **kwargs):
self.title = title
self.endpoint = endpoint
self.url_for_args = args
self.url_for_kwargs = kwargs
def get_url(self):
return url_for(self.endpoint,
*self.url_for_args,
**self.url_for_kwargs)
@property
def active(self):
# this is a better check because it takes arguments into account
return request.path == self.get_url()
class Separator(NavigationItem):
pass
class Subgroup(NavigationItem):
def __init__(self, title, *items):
self.title = title
self.items = items
class Label(TagItem):
pass
class Link(TagItem):
pass
class Navbar(Subgroup):
id = 'nav_no_id'
|
...
class NavigationItem(object):
active = False
def render(self, renderer=None, **kwargs):
...
|
c94598b8ce59b98213367b54164b1051d56a28da
|
scene.py
|
scene.py
|
import bpy
class Scene:
"""Scene object"""
def __init__(self, filepath, render_engine='CYCLES'):
self.filepath = filepath
self.render_engine = 'CYCLES'
def setup(self):
self._cleanup()
bpy.context.scene.render.filepath = self.filepath
bpy.context.scene.render.engine = self.render_engine
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 1
def render(self):
bpy.ops.render.render(animation=True)
def _cleanup(self):
"""Delete everything"""
bpy.ops.object.delete(use_global=False)
|
import bpy
class Scene:
"""Scene object"""
def __init__(self, filepath, render_engine='CYCLES'):
self.filepath = filepath
self.render_engine = 'CYCLES'
def setup(self):
self._cleanup()
bpy.context.scene.render.filepath = self.filepath
bpy.context.scene.render.engine = self.render_engine
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 1
def render(self, samples=50):
bpy.context.scene.cycles.samples = samples
bpy.ops.render.render(animation=True)
def _cleanup(self):
"""Delete everything"""
bpy.ops.object.delete(use_global=False)
|
Allow to set render samples
|
Allow to set render samples
|
Python
|
mit
|
josuemontano/blender_wrapper
|
import bpy
class Scene:
"""Scene object"""
def __init__(self, filepath, render_engine='CYCLES'):
self.filepath = filepath
self.render_engine = 'CYCLES'
def setup(self):
self._cleanup()
bpy.context.scene.render.filepath = self.filepath
bpy.context.scene.render.engine = self.render_engine
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 1
- def render(self):
+ def render(self, samples=50):
+ bpy.context.scene.cycles.samples = samples
bpy.ops.render.render(animation=True)
def _cleanup(self):
"""Delete everything"""
bpy.ops.object.delete(use_global=False)
|
Allow to set render samples
|
## Code Before:
import bpy
class Scene:
"""Scene object"""
def __init__(self, filepath, render_engine='CYCLES'):
self.filepath = filepath
self.render_engine = 'CYCLES'
def setup(self):
self._cleanup()
bpy.context.scene.render.filepath = self.filepath
bpy.context.scene.render.engine = self.render_engine
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 1
def render(self):
bpy.ops.render.render(animation=True)
def _cleanup(self):
"""Delete everything"""
bpy.ops.object.delete(use_global=False)
## Instruction:
Allow to set render samples
## Code After:
import bpy
class Scene:
"""Scene object"""
def __init__(self, filepath, render_engine='CYCLES'):
self.filepath = filepath
self.render_engine = 'CYCLES'
def setup(self):
self._cleanup()
bpy.context.scene.render.filepath = self.filepath
bpy.context.scene.render.engine = self.render_engine
bpy.context.scene.frame_start = 1
bpy.context.scene.frame_end = 1
def render(self, samples=50):
bpy.context.scene.cycles.samples = samples
bpy.ops.render.render(animation=True)
def _cleanup(self):
"""Delete everything"""
bpy.ops.object.delete(use_global=False)
|
...
def render(self, samples=50):
bpy.context.scene.cycles.samples = samples
bpy.ops.render.render(animation=True)
...
|
175bbd2f181d067712d38beeca9df4063654103a
|
nlppln/frog_to_saf.py
|
nlppln/frog_to_saf.py
|
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
out_file = os.path.join(output_dir, '{}.json'.format(tail))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
|
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
fname = tail.replace(os.path.splitext(tail)[1], '')
out_file = os.path.join(output_dir, '{}.json'.format(fname))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
|
Update script to remove extension from filename
|
Update script to remove extension from filename
Before, the script added the extension .json to whatever the file
name was. Now, it removes the last extension and then appends .json.
|
Python
|
apache-2.0
|
WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln
|
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
+ fname = tail.replace(os.path.splitext(tail)[1], '')
- out_file = os.path.join(output_dir, '{}.json'.format(tail))
+ out_file = os.path.join(output_dir, '{}.json'.format(fname))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
|
Update script to remove extension from filename
|
## Code Before:
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
out_file = os.path.join(output_dir, '{}.json'.format(tail))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
## Instruction:
Update script to remove extension from filename
## Code After:
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for fi in input_files:
with codecs.open(fi) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
saf_data = frog_to_saf(parse_frog(lines))
head, tail = os.path.split(fi)
fname = tail.replace(os.path.splitext(tail)[1], '')
out_file = os.path.join(output_dir, '{}.json'.format(fname))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
json.dump(saf_data, f, indent=4)
if __name__ == '__main__':
frog2saf()
|
...
head, tail = os.path.split(fi)
fname = tail.replace(os.path.splitext(tail)[1], '')
out_file = os.path.join(output_dir, '{}.json'.format(fname))
with codecs.open(out_file, 'wb', encoding='utf-8') as f:
...
|
6ec35a123f6156001f779ccb5ff3bbda2b1f4477
|
src/json_to_csv.py
|
src/json_to_csv.py
|
import json, os, sys
from utils.file import load_json
# Parse a json-formatted input instance and produce a csv file with
# all involved coordinates.
def coord_to_csv(array):
return str(array[0]) + ',' + str(array[1]) + '\n'
def write_to_csv(input_file):
input = load_json(input_file)
lines = []
for v in input['vehicles']:
if 'start' in v:
lines.append(coord_to_csv(v['start']))
if 'end' in v:
lines.append(coord_to_csv(v['end']))
for job in input['jobs']:
lines.append(coord_to_csv(job['location']))
output_name = input_file[:input_file.rfind('.json')] + '.csv'
with open(output_name, 'w') as output_file:
for l in lines:
output_file.write(l)
if __name__ == "__main__":
write_to_csv(sys.argv[1])
|
import json, os, sys
from utils.file import load_json
# Parse a json-formatted input instance and produce a csv file with
# all involved coordinates in Lat,Lng order.
def coord_to_csv(array):
return str(array[1]) + ',' + str(array[0]) + '\n'
def write_to_csv(input_file):
input = load_json(input_file)
lines = []
for v in input['vehicles']:
if 'start' in v:
lines.append(coord_to_csv(v['start']))
if 'end' in v:
lines.append(coord_to_csv(v['end']))
for job in input['jobs']:
lines.append(coord_to_csv(job['location']))
output_name = input_file[:input_file.rfind('.json')] + '.csv'
with open(output_name, 'w') as output_file:
for l in lines:
output_file.write(l)
if __name__ == "__main__":
write_to_csv(sys.argv[1])
|
Change coordinates order to Lat,Lng to match the frontend geocoding.
|
Change coordinates order to Lat,Lng to match the frontend geocoding.
|
Python
|
bsd-2-clause
|
VROOM-Project/vroom-scripts,VROOM-Project/vroom-scripts
|
import json, os, sys
from utils.file import load_json
# Parse a json-formatted input instance and produce a csv file with
- # all involved coordinates.
+ # all involved coordinates in Lat,Lng order.
def coord_to_csv(array):
- return str(array[0]) + ',' + str(array[1]) + '\n'
+ return str(array[1]) + ',' + str(array[0]) + '\n'
def write_to_csv(input_file):
input = load_json(input_file)
lines = []
for v in input['vehicles']:
if 'start' in v:
lines.append(coord_to_csv(v['start']))
if 'end' in v:
lines.append(coord_to_csv(v['end']))
for job in input['jobs']:
lines.append(coord_to_csv(job['location']))
output_name = input_file[:input_file.rfind('.json')] + '.csv'
with open(output_name, 'w') as output_file:
for l in lines:
output_file.write(l)
if __name__ == "__main__":
write_to_csv(sys.argv[1])
|
Change coordinates order to Lat,Lng to match the frontend geocoding.
|
## Code Before:
import json, os, sys
from utils.file import load_json
# Parse a json-formatted input instance and produce a csv file with
# all involved coordinates.
def coord_to_csv(array):
return str(array[0]) + ',' + str(array[1]) + '\n'
def write_to_csv(input_file):
input = load_json(input_file)
lines = []
for v in input['vehicles']:
if 'start' in v:
lines.append(coord_to_csv(v['start']))
if 'end' in v:
lines.append(coord_to_csv(v['end']))
for job in input['jobs']:
lines.append(coord_to_csv(job['location']))
output_name = input_file[:input_file.rfind('.json')] + '.csv'
with open(output_name, 'w') as output_file:
for l in lines:
output_file.write(l)
if __name__ == "__main__":
write_to_csv(sys.argv[1])
## Instruction:
Change coordinates order to Lat,Lng to match the frontend geocoding.
## Code After:
import json, os, sys
from utils.file import load_json
# Parse a json-formatted input instance and produce a csv file with
# all involved coordinates in Lat,Lng order.
def coord_to_csv(array):
return str(array[1]) + ',' + str(array[0]) + '\n'
def write_to_csv(input_file):
input = load_json(input_file)
lines = []
for v in input['vehicles']:
if 'start' in v:
lines.append(coord_to_csv(v['start']))
if 'end' in v:
lines.append(coord_to_csv(v['end']))
for job in input['jobs']:
lines.append(coord_to_csv(job['location']))
output_name = input_file[:input_file.rfind('.json')] + '.csv'
with open(output_name, 'w') as output_file:
for l in lines:
output_file.write(l)
if __name__ == "__main__":
write_to_csv(sys.argv[1])
|
// ... existing code ...
# Parse a json-formatted input instance and produce a csv file with
# all involved coordinates in Lat,Lng order.
// ... modified code ...
def coord_to_csv(array):
return str(array[1]) + ',' + str(array[0]) + '\n'
// ... rest of the code ...
|
f364b55a643c2768f80cb559eb0ec1988aa884c8
|
tests/htmlgeneration_test.py
|
tests/htmlgeneration_test.py
|
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
generator = HtmlGenerator()
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
assert_equal(expected_html, generator.for_document(document))
|
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_document(document))
@istest
def html_for_paragraph_uses_p_tag_if_there_is_no_style():
paragraph = openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
])
expected_html = html.element("p", [html.text("Hello")])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_paragraph(paragraph))
|
Add test just for paragraph HTML generation
|
Add test just for paragraph HTML generation
|
Python
|
bsd-2-clause
|
mwilliamson/wordbridge
|
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
- generator = HtmlGenerator()
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
+
+ generator = HtmlGenerator()
assert_equal(expected_html, generator.for_document(document))
+ @istest
+ def html_for_paragraph_uses_p_tag_if_there_is_no_style():
+ paragraph = openxml.paragraph([
+ openxml.run([
+ openxml.text("Hello")
+ ])
+ ])
+ expected_html = html.element("p", [html.text("Hello")])
+
+ generator = HtmlGenerator()
+ assert_equal(expected_html, generator.for_paragraph(paragraph))
+
|
Add test just for paragraph HTML generation
|
## Code Before:
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
generator = HtmlGenerator()
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
assert_equal(expected_html, generator.for_document(document))
## Instruction:
Add test just for paragraph HTML generation
## Code After:
from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
]),
openxml.paragraph([
openxml.run([
openxml.text("there")
])
])
])
expected_html = html.fragment([
html.element("p", [html.text("Hello")]),
html.element("p", [html.text("there")])
])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_document(document))
@istest
def html_for_paragraph_uses_p_tag_if_there_is_no_style():
paragraph = openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
])
expected_html = html.element("p", [html.text("Hello")])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_paragraph(paragraph))
|
...
html = HtmlBuilder()
...
])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_document(document))
@istest
def html_for_paragraph_uses_p_tag_if_there_is_no_style():
paragraph = openxml.paragraph([
openxml.run([
openxml.text("Hello")
])
])
expected_html = html.element("p", [html.text("Hello")])
generator = HtmlGenerator()
assert_equal(expected_html, generator.for_paragraph(paragraph))
...
|
8cb34f4d88184d0c42e8c1fc41f451fa3cd5a6be
|
plugins/keepkey/cmdline.py
|
plugins/keepkey/cmdline.py
|
from electrum.util import print_msg, raw_input
from .keepkey import KeepKeyPlugin
from ..hw_wallet import CmdLineHandler
class Plugin(KeepKeyPlugin):
handler = CmdLineHandler()
@hook
def init_keystore(self, keystore):
if not isinstance(keystore, self.keystore_class):
return
keystore.handler = self.handler
|
from electrum.plugins import hook
from electrum.util import print_msg, raw_input
from .keepkey import KeepKeyPlugin
from ..hw_wallet import CmdLineHandler
class Plugin(KeepKeyPlugin):
handler = CmdLineHandler()
@hook
def init_keystore(self, keystore):
if not isinstance(keystore, self.keystore_class):
return
keystore.handler = self.handler
|
Fix undefined reference error in command line KeepKey plugin.
|
Fix undefined reference error in command line KeepKey plugin.
|
Python
|
mit
|
romanz/electrum,wakiyamap/electrum-mona,vialectrum/vialectrum,romanz/electrum,digitalbitbox/electrum,kyuupichan/electrum,asfin/electrum,pooler/electrum-ltc,vialectrum/vialectrum,kyuupichan/electrum,spesmilo/electrum,digitalbitbox/electrum,cryptapus/electrum,kyuupichan/electrum,digitalbitbox/electrum,wakiyamap/electrum-mona,pooler/electrum-ltc,spesmilo/electrum,cryptapus/electrum,fyookball/electrum,fyookball/electrum,spesmilo/electrum,fujicoin/electrum-fjc,fyookball/electrum,pooler/electrum-ltc,pooler/electrum-ltc,digitalbitbox/electrum,neocogent/electrum,vialectrum/vialectrum,asfin/electrum,asfin/electrum,fujicoin/electrum-fjc,wakiyamap/electrum-mona,romanz/electrum,neocogent/electrum,neocogent/electrum,spesmilo/electrum,wakiyamap/electrum-mona,cryptapus/electrum,fujicoin/electrum-fjc
|
+ from electrum.plugins import hook
from electrum.util import print_msg, raw_input
from .keepkey import KeepKeyPlugin
from ..hw_wallet import CmdLineHandler
class Plugin(KeepKeyPlugin):
handler = CmdLineHandler()
@hook
def init_keystore(self, keystore):
if not isinstance(keystore, self.keystore_class):
return
keystore.handler = self.handler
|
Fix undefined reference error in command line KeepKey plugin.
|
## Code Before:
from electrum.util import print_msg, raw_input
from .keepkey import KeepKeyPlugin
from ..hw_wallet import CmdLineHandler
class Plugin(KeepKeyPlugin):
handler = CmdLineHandler()
@hook
def init_keystore(self, keystore):
if not isinstance(keystore, self.keystore_class):
return
keystore.handler = self.handler
## Instruction:
Fix undefined reference error in command line KeepKey plugin.
## Code After:
from electrum.plugins import hook
from electrum.util import print_msg, raw_input
from .keepkey import KeepKeyPlugin
from ..hw_wallet import CmdLineHandler
class Plugin(KeepKeyPlugin):
handler = CmdLineHandler()
@hook
def init_keystore(self, keystore):
if not isinstance(keystore, self.keystore_class):
return
keystore.handler = self.handler
|
...
from electrum.plugins import hook
from electrum.util import print_msg, raw_input
...
|
fcf30e1dfada272d0344ccb9e4054afeda003c8e
|
setup.py
|
setup.py
|
from distutils.core import setup
from os.path import dirname, join
setup(name='hashids',
version='0.8.3',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.5--3.',
long_description=open(join(dirname(__file__), 'README.rst'), 'r', -1, 'utf-8').read(),
author='David Aurelio',
author_email='[email protected]',
url='https://github.com/davidaurelio/hashids-python',
license='MIT License',
py_modules=('hashids',))
|
from distutils.core import setup
from os.path import dirname, join
from codecs import open
setup(name='hashids',
version='0.8.3',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.5--3.',
long_description=open(join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
author='David Aurelio',
author_email='[email protected]',
url='https://github.com/davidaurelio/hashids-python',
license='MIT License',
py_modules=('hashids',))
|
Make it work with older python versions as well
|
Make it work with older python versions as well
|
Python
|
mit
|
davidaurelio/hashids-python,Dubz/hashids-python,pombredanne/hashids-python
|
from distutils.core import setup
from os.path import dirname, join
+ from codecs import open
setup(name='hashids',
version='0.8.3',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.5--3.',
- long_description=open(join(dirname(__file__), 'README.rst'), 'r', -1, 'utf-8').read(),
+ long_description=open(join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
author='David Aurelio',
author_email='[email protected]',
url='https://github.com/davidaurelio/hashids-python',
license='MIT License',
py_modules=('hashids',))
|
Make it work with older python versions as well
|
## Code Before:
from distutils.core import setup
from os.path import dirname, join
setup(name='hashids',
version='0.8.3',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.5--3.',
long_description=open(join(dirname(__file__), 'README.rst'), 'r', -1, 'utf-8').read(),
author='David Aurelio',
author_email='[email protected]',
url='https://github.com/davidaurelio/hashids-python',
license='MIT License',
py_modules=('hashids',))
## Instruction:
Make it work with older python versions as well
## Code After:
from distutils.core import setup
from os.path import dirname, join
from codecs import open
setup(name='hashids',
version='0.8.3',
description='Python implementation of hashids (http://www.hashids.org).'
'Compatible with python 2.5--3.',
long_description=open(join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
author='David Aurelio',
author_email='[email protected]',
url='https://github.com/davidaurelio/hashids-python',
license='MIT License',
py_modules=('hashids',))
|
// ... existing code ...
from os.path import dirname, join
from codecs import open
// ... modified code ...
'Compatible with python 2.5--3.',
long_description=open(join(dirname(__file__), 'README.rst'), encoding='utf-8').read(),
author='David Aurelio',
// ... rest of the code ...
|
bed7f5c80f6c5b5ce9b9a17aea5c9eadd047ee47
|
mfr/conftest.py
|
mfr/conftest.py
|
import io
import pytest
@pytest.fixture
def fakefile():
return io.BytesIO(b'foo')
|
import pytest
import mock
@pytest.fixture
def fakefile():
"""A simple file-like object."""
return mock.Mock(spec=file)
|
Make fakefile a mock instead of an io object
|
Make fakefile a mock instead of an io object
Makes it possible to mutate attributes, e.g. the name,
for tests
|
Python
|
apache-2.0
|
felliott/modular-file-renderer,CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,CenterForOpenScience/modular-file-renderer,Johnetordoff/modular-file-renderer,mfraezz/modular-file-renderer,icereval/modular-file-renderer,icereval/modular-file-renderer,AddisonSchiller/modular-file-renderer,chrisseto/modular-file-renderer,haoyuchen1992/modular-file-renderer,erinspace/modular-file-renderer,rdhyee/modular-file-renderer,TomBaxter/modular-file-renderer,rdhyee/modular-file-renderer,CenterForOpenScience/modular-file-renderer,Johnetordoff/modular-file-renderer,felliott/modular-file-renderer,erinspace/modular-file-renderer,chrisseto/modular-file-renderer,felliott/modular-file-renderer,felliott/modular-file-renderer,rdhyee/modular-file-renderer,haoyuchen1992/modular-file-renderer,chrisseto/modular-file-renderer,CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,AddisonSchiller/modular-file-renderer,haoyuchen1992/modular-file-renderer,haoyuchen1992/modular-file-renderer,mfraezz/modular-file-renderer,TomBaxter/modular-file-renderer,rdhyee/modular-file-renderer,erinspace/modular-file-renderer,TomBaxter/modular-file-renderer,icereval/modular-file-renderer,AddisonSchiller/modular-file-renderer,Johnetordoff/modular-file-renderer,TomBaxter/modular-file-renderer,AddisonSchiller/modular-file-renderer,Johnetordoff/modular-file-renderer
|
- import io
import pytest
+ import mock
@pytest.fixture
def fakefile():
- return io.BytesIO(b'foo')
+ """A simple file-like object."""
+ return mock.Mock(spec=file)
|
Make fakefile a mock instead of an io object
|
## Code Before:
import io
import pytest
@pytest.fixture
def fakefile():
return io.BytesIO(b'foo')
## Instruction:
Make fakefile a mock instead of an io object
## Code After:
import pytest
import mock
@pytest.fixture
def fakefile():
"""A simple file-like object."""
return mock.Mock(spec=file)
|
...
import pytest
import mock
...
def fakefile():
"""A simple file-like object."""
return mock.Mock(spec=file)
...
|
77fd12a850fbca0b3308e964e457f234d12d7c11
|
src/wad.blog/wad/blog/utils.py
|
src/wad.blog/wad/blog/utils.py
|
from zope.component import getUtility, getMultiAdapter, ComponentLookupError
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
def find_assignment_context(assignment, context):
# Finds the creation context of the assignment
context = context.aq_inner
manager_name = assignment.manager.__name__
assignment_name = assignment.__name__
while True:
try:
manager = getUtility(IPortletManager, manager_name,
context=context)
mapping = getMultiAdapter((context, manager),
IPortletAssignmentMapping)
if assignment_name in mapping:
if mapping[assignment_name] is assignment.aq_base:
return context
except ComponentLookupError:
pass
parent = context.aq_parent
if parent is context:
return None
context = parent
|
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import aq_base
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
from zope.component import getUtility, getMultiAdapter, ComponentLookupError
def find_assignment_context(assignment, context):
# Finds the creation context of the assignment
context = aq_inner(context)
manager_name = assignment.manager.__name__
assignment_name = assignment.__name__
while True:
try:
manager = getUtility(IPortletManager,
manager_name,
context=context)
mapping = getMultiAdapter((context, manager),
IPortletAssignmentMapping)
if assignment_name in mapping:
if mapping[assignment_name] is aq_base(assignment):
return context
except ComponentLookupError:
pass
parent = aq_parent(context)
if parent is context:
return None
context = parent
|
Fix portlet assignment context utility
|
Fix portlet assignment context utility
|
Python
|
mit
|
potzenheimer/buildout.wad,potzenheimer/buildout.wad
|
- from zope.component import getUtility, getMultiAdapter, ComponentLookupError
+ from Acquisition import aq_inner
+ from Acquisition import aq_parent
+ from Acquisition import aq_base
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
+
+ from zope.component import getUtility, getMultiAdapter, ComponentLookupError
def find_assignment_context(assignment, context):
# Finds the creation context of the assignment
- context = context.aq_inner
+ context = aq_inner(context)
manager_name = assignment.manager.__name__
assignment_name = assignment.__name__
while True:
try:
- manager = getUtility(IPortletManager, manager_name,
+ manager = getUtility(IPortletManager,
+ manager_name,
context=context)
mapping = getMultiAdapter((context, manager),
IPortletAssignmentMapping)
if assignment_name in mapping:
- if mapping[assignment_name] is assignment.aq_base:
+ if mapping[assignment_name] is aq_base(assignment):
return context
except ComponentLookupError:
pass
- parent = context.aq_parent
+ parent = aq_parent(context)
if parent is context:
return None
context = parent
|
Fix portlet assignment context utility
|
## Code Before:
from zope.component import getUtility, getMultiAdapter, ComponentLookupError
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
def find_assignment_context(assignment, context):
# Finds the creation context of the assignment
context = context.aq_inner
manager_name = assignment.manager.__name__
assignment_name = assignment.__name__
while True:
try:
manager = getUtility(IPortletManager, manager_name,
context=context)
mapping = getMultiAdapter((context, manager),
IPortletAssignmentMapping)
if assignment_name in mapping:
if mapping[assignment_name] is assignment.aq_base:
return context
except ComponentLookupError:
pass
parent = context.aq_parent
if parent is context:
return None
context = parent
## Instruction:
Fix portlet assignment context utility
## Code After:
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import aq_base
from plone.portlets.interfaces import IPortletAssignmentMapping
from plone.portlets.interfaces import IPortletManager
from zope.component import getUtility, getMultiAdapter, ComponentLookupError
def find_assignment_context(assignment, context):
# Finds the creation context of the assignment
context = aq_inner(context)
manager_name = assignment.manager.__name__
assignment_name = assignment.__name__
while True:
try:
manager = getUtility(IPortletManager,
manager_name,
context=context)
mapping = getMultiAdapter((context, manager),
IPortletAssignmentMapping)
if assignment_name in mapping:
if mapping[assignment_name] is aq_base(assignment):
return context
except ComponentLookupError:
pass
parent = aq_parent(context)
if parent is context:
return None
context = parent
|
# ... existing code ...
from Acquisition import aq_inner
from Acquisition import aq_parent
from Acquisition import aq_base
from plone.portlets.interfaces import IPortletAssignmentMapping
# ... modified code ...
from plone.portlets.interfaces import IPortletManager
from zope.component import getUtility, getMultiAdapter, ComponentLookupError
...
# Finds the creation context of the assignment
context = aq_inner(context)
manager_name = assignment.manager.__name__
...
try:
manager = getUtility(IPortletManager,
manager_name,
context=context)
...
if assignment_name in mapping:
if mapping[assignment_name] is aq_base(assignment):
return context
...
pass
parent = aq_parent(context)
if parent is context:
# ... rest of the code ...
|
f0984c9855a6283de27e717fad73bb4f1b6394ab
|
flatten-array/flatten_array.py
|
flatten-array/flatten_array.py
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
Tidy and simplify generator code
|
Tidy and simplify generator code
|
Python
|
agpl-3.0
|
CubicComet/exercism-python-solutions
|
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
- if isinstance(lst, (list, tuple)):
- for item in lst:
+ for item in lst:
+ if isinstance(item, (list, tuple)):
- if item is None:
- continue
- else:
- yield from _flatten(item)
+ yield from _flatten(item)
- else:
+ elif item is not None:
- yield lst
+ yield item
|
Tidy and simplify generator code
|
## Code Before:
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
if isinstance(lst, (list, tuple)):
for item in lst:
if item is None:
continue
else:
yield from _flatten(item)
else:
yield lst
## Instruction:
Tidy and simplify generator code
## Code After:
def flatten(lst):
"""Completely flatten an arbitrarily-deep list"""
return [*_flatten(lst)]
def _flatten(lst):
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
|
# ... existing code ...
"""Generator for flattening arbitrarily-deep lists"""
for item in lst:
if isinstance(item, (list, tuple)):
yield from _flatten(item)
elif item is not None:
yield item
# ... rest of the code ...
|
c783af3af004ec2de31b85045d1c517f5c3a9ccc
|
tests/v6/test_date_generator.py
|
tests/v6/test_date_generator.py
|
import datetime as dt
from .context import tohu
from tohu.v6.primitive_generators import Date
def test_single_date():
g = Date(start="2018-01-01", end="2018-01-01")
dates = g.generate(100, seed=12345)
assert all([x == dt.date(2018, 1, 1) for x in dates])
def test_date_range():
g = Date(start="1999-11-28", end="1999-12-01")
dates = g.generate(1000, seed=12345)
dates_expected = [
dt.date(1999, 11, 28),
dt.date(1999, 11, 29),
dt.date(1999, 11, 30),
dt.date(1999, 12, 1),
]
assert set(dates_expected) == set(dates)
|
import datetime as dt
from .context import tohu
from tohu.v6.primitive_generators import Date
def test_single_date():
g = Date(start="2018-01-01", end="2018-01-01")
dates = g.generate(100, seed=12345)
assert all([x == dt.date(2018, 1, 1) for x in dates])
def test_date_range():
g = Date(start="1999-11-28", end="1999-12-01")
dates = g.generate(1000, seed=12345)
dates_expected = [
dt.date(1999, 11, 28),
dt.date(1999, 11, 29),
dt.date(1999, 11, 30),
dt.date(1999, 12, 1),
]
assert set(dates_expected) == set(dates)
def test_start_and_end():
g = Date(start="1999-11-28", end="1999-12-01")
assert g.start == dt.date(1999, 11, 28)
assert g.end == dt.date(1999, 12, 1)
|
Add test for start/end values
|
Add test for start/end values
|
Python
|
mit
|
maxalbert/tohu
|
import datetime as dt
from .context import tohu
from tohu.v6.primitive_generators import Date
def test_single_date():
g = Date(start="2018-01-01", end="2018-01-01")
dates = g.generate(100, seed=12345)
assert all([x == dt.date(2018, 1, 1) for x in dates])
def test_date_range():
g = Date(start="1999-11-28", end="1999-12-01")
dates = g.generate(1000, seed=12345)
dates_expected = [
dt.date(1999, 11, 28),
dt.date(1999, 11, 29),
dt.date(1999, 11, 30),
dt.date(1999, 12, 1),
]
assert set(dates_expected) == set(dates)
+
+ def test_start_and_end():
+ g = Date(start="1999-11-28", end="1999-12-01")
+ assert g.start == dt.date(1999, 11, 28)
+ assert g.end == dt.date(1999, 12, 1)
+
|
Add test for start/end values
|
## Code Before:
import datetime as dt
from .context import tohu
from tohu.v6.primitive_generators import Date
def test_single_date():
g = Date(start="2018-01-01", end="2018-01-01")
dates = g.generate(100, seed=12345)
assert all([x == dt.date(2018, 1, 1) for x in dates])
def test_date_range():
g = Date(start="1999-11-28", end="1999-12-01")
dates = g.generate(1000, seed=12345)
dates_expected = [
dt.date(1999, 11, 28),
dt.date(1999, 11, 29),
dt.date(1999, 11, 30),
dt.date(1999, 12, 1),
]
assert set(dates_expected) == set(dates)
## Instruction:
Add test for start/end values
## Code After:
import datetime as dt
from .context import tohu
from tohu.v6.primitive_generators import Date
def test_single_date():
g = Date(start="2018-01-01", end="2018-01-01")
dates = g.generate(100, seed=12345)
assert all([x == dt.date(2018, 1, 1) for x in dates])
def test_date_range():
g = Date(start="1999-11-28", end="1999-12-01")
dates = g.generate(1000, seed=12345)
dates_expected = [
dt.date(1999, 11, 28),
dt.date(1999, 11, 29),
dt.date(1999, 11, 30),
dt.date(1999, 12, 1),
]
assert set(dates_expected) == set(dates)
def test_start_and_end():
g = Date(start="1999-11-28", end="1999-12-01")
assert g.start == dt.date(1999, 11, 28)
assert g.end == dt.date(1999, 12, 1)
|
...
assert set(dates_expected) == set(dates)
def test_start_and_end():
g = Date(start="1999-11-28", end="1999-12-01")
assert g.start == dt.date(1999, 11, 28)
assert g.end == dt.date(1999, 12, 1)
...
|
fc8ac6ba5081e7847847d31588a65db8ea13416c
|
openprescribing/matrixstore/build/dates.py
|
openprescribing/matrixstore/build/dates.py
|
DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
months = DEFAULT_NUM_MONTHS
end_date = parse_date(end_str)
assert months > 0
dates = []
for offset in range(1-months, 1):
date = increment_months(end_date, offset)
dates.append('{:04d}-{:02d}-01'.format(date[0], date[1]))
return dates
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace('_', '-').split('-')[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
def increment_months((year, month), months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
i = (year*12) + (month - 1)
i += months
return int(i/12), (i % 12) + 1
|
DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
months = DEFAULT_NUM_MONTHS
end_date = parse_date(end_str)
assert months > 0
dates = []
for offset in range(1-months, 1):
date = increment_months(end_date, offset)
dates.append('{:04d}-{:02d}-01'.format(date[0], date[1]))
return dates
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace('_', '-').split('-')[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
def increment_months(year_month, months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
year, month = year_month
i = (year*12) + (month - 1)
i += months
return int(i/12), (i % 12) + 1
|
Fix another py27-ism which Black can't handle
|
Fix another py27-ism which Black can't handle
Not sure how I missed this one last time.
|
Python
|
mit
|
ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc
|
DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
months = DEFAULT_NUM_MONTHS
end_date = parse_date(end_str)
assert months > 0
dates = []
for offset in range(1-months, 1):
date = increment_months(end_date, offset)
dates.append('{:04d}-{:02d}-01'.format(date[0], date[1]))
return dates
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace('_', '-').split('-')[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
- def increment_months((year, month), months):
+ def increment_months(year_month, months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
+ year, month = year_month
i = (year*12) + (month - 1)
i += months
return int(i/12), (i % 12) + 1
|
Fix another py27-ism which Black can't handle
|
## Code Before:
DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
months = DEFAULT_NUM_MONTHS
end_date = parse_date(end_str)
assert months > 0
dates = []
for offset in range(1-months, 1):
date = increment_months(end_date, offset)
dates.append('{:04d}-{:02d}-01'.format(date[0], date[1]))
return dates
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace('_', '-').split('-')[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
def increment_months((year, month), months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
i = (year*12) + (month - 1)
i += months
return int(i/12), (i % 12) + 1
## Instruction:
Fix another py27-ism which Black can't handle
## Code After:
DEFAULT_NUM_MONTHS = 60
def generate_dates(end_str, months=None):
"""
Given an end date as a string in YYYY-MM form (or the underscore separated
equivalent), return a list of N consecutive months as strings in YYYY-MM-01
form, with that month as the final member
"""
if months is None:
months = DEFAULT_NUM_MONTHS
end_date = parse_date(end_str)
assert months > 0
dates = []
for offset in range(1-months, 1):
date = increment_months(end_date, offset)
dates.append('{:04d}-{:02d}-01'.format(date[0], date[1]))
return dates
def parse_date(date_str):
"""
Given a date string in YYYY-MM form (or the underscore separated
equivalent), return a pair of (year, month) integers
"""
year_str, month_str = date_str.replace('_', '-').split('-')[:2]
assert len(year_str) == 4
assert len(month_str) == 2
return int(year_str), int(month_str)
def increment_months(year_month, months):
"""
Given a pair of (year, month) integers return the (year, month) pair N
months in the future
"""
year, month = year_month
i = (year*12) + (month - 1)
i += months
return int(i/12), (i % 12) + 1
|
...
def increment_months(year_month, months):
"""
...
"""
year, month = year_month
i = (year*12) + (month - 1)
...
|
70863101a882eee0811460cf9bf0f8442d9b0775
|
djproxy/urls.py
|
djproxy/urls.py
|
from django.conf.urls import patterns
from djproxy.views import HttpProxy
def generate_routes(config):
routes = []
for service_name, proxy_config in config.items():
ProxyClass = type(
'ProxyClass',
(HttpProxy, ),
{'base_url': proxy_config['base_url']}
)
routes.append((
r'^%s' % proxy_config['prefix'],
ProxyClass.as_view()
))
return routes
|
import re
from django.conf.urls import patterns, url
from djproxy.views import HttpProxy
def generate_routes(config):
routes = ()
for service_name, proxy_config in config.items():
base_url = proxy_config['base_url']
prefix = proxy_config['prefix']
ProxyClass = type('ProxyClass', (HttpProxy,), {'base_url': base_url})
routes += url(r'^%s' % prefix.lstrip('/'), ProxyClass.as_view()),
return patterns('', *routes)
|
Return a `patterns` rather than a list of tuples
|
Return a `patterns` rather than a list of tuples
|
Python
|
mit
|
thomasw/djproxy
|
+ import re
+
- from django.conf.urls import patterns
+ from django.conf.urls import patterns, url
+
from djproxy.views import HttpProxy
def generate_routes(config):
- routes = []
+ routes = ()
for service_name, proxy_config in config.items():
- ProxyClass = type(
- 'ProxyClass',
- (HttpProxy, ),
- {'base_url': proxy_config['base_url']}
+ base_url = proxy_config['base_url']
- )
- routes.append((
- r'^%s' % proxy_config['prefix'],
+ prefix = proxy_config['prefix']
- ProxyClass.as_view()
- ))
- return routes
+ ProxyClass = type('ProxyClass', (HttpProxy,), {'base_url': base_url})
+
+ routes += url(r'^%s' % prefix.lstrip('/'), ProxyClass.as_view()),
+
+ return patterns('', *routes)
+
|
Return a `patterns` rather than a list of tuples
|
## Code Before:
from django.conf.urls import patterns
from djproxy.views import HttpProxy
def generate_routes(config):
routes = []
for service_name, proxy_config in config.items():
ProxyClass = type(
'ProxyClass',
(HttpProxy, ),
{'base_url': proxy_config['base_url']}
)
routes.append((
r'^%s' % proxy_config['prefix'],
ProxyClass.as_view()
))
return routes
## Instruction:
Return a `patterns` rather than a list of tuples
## Code After:
import re
from django.conf.urls import patterns, url
from djproxy.views import HttpProxy
def generate_routes(config):
routes = ()
for service_name, proxy_config in config.items():
base_url = proxy_config['base_url']
prefix = proxy_config['prefix']
ProxyClass = type('ProxyClass', (HttpProxy,), {'base_url': base_url})
routes += url(r'^%s' % prefix.lstrip('/'), ProxyClass.as_view()),
return patterns('', *routes)
|
// ... existing code ...
import re
from django.conf.urls import patterns, url
from djproxy.views import HttpProxy
// ... modified code ...
def generate_routes(config):
routes = ()
for service_name, proxy_config in config.items():
base_url = proxy_config['base_url']
prefix = proxy_config['prefix']
ProxyClass = type('ProxyClass', (HttpProxy,), {'base_url': base_url})
routes += url(r'^%s' % prefix.lstrip('/'), ProxyClass.as_view()),
return patterns('', *routes)
// ... rest of the code ...
|
bdd842f55f3a234fefee4cd2a701fa23e07c3789
|
scikits/umfpack/setup.py
|
scikits/umfpack/setup.py
|
from __future__ import division, print_function, absolute_import
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, dict_append
config = Configuration('umfpack', parent_package, top_path)
config.add_data_dir('tests')
umf_info = get_info('umfpack', notfound_action=1)
## The following addition is needed when linking against a umfpack built
## from the latest SparseSuite. Not (strictly) needed when linking against
## the version in the ubuntu repositories.
umf_info['libraries'].insert(0, 'rt')
umfpack_i_file = config.paths('umfpack.i')[0]
def umfpack_i(ext, build_dir):
if umf_info:
return umfpack_i_file
blas_info = get_info('blas_opt')
build_info = {}
dict_append(build_info, **umf_info)
dict_append(build_info, **blas_info)
config.add_extension('__umfpack',
sources=[umfpack_i],
depends=['umfpack.i'],
**build_info)
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
from __future__ import division, print_function, absolute_import
import sys
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, dict_append
config = Configuration('umfpack', parent_package, top_path)
config.add_data_dir('tests')
umf_info = get_info('umfpack', notfound_action=1)
## The following addition is needed when linking against a umfpack built
## from the latest SparseSuite. Not (strictly) needed when linking against
## the version in the ubuntu repositories.
if not sys.platform == 'darwin':
umf_info['libraries'].insert(0, 'rt')
umfpack_i_file = config.paths('umfpack.i')[0]
def umfpack_i(ext, build_dir):
if umf_info:
return umfpack_i_file
blas_info = get_info('blas_opt')
build_info = {}
dict_append(build_info, **umf_info)
dict_append(build_info, **blas_info)
config.add_extension('__umfpack',
sources=[umfpack_i],
depends=['umfpack.i'],
**build_info)
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
|
Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
|
Python
|
bsd-3-clause
|
scikit-umfpack/scikit-umfpack,scikit-umfpack/scikit-umfpack,rc/scikit-umfpack-rc,rc/scikit-umfpack,rc/scikit-umfpack,rc/scikit-umfpack-rc
|
from __future__ import division, print_function, absolute_import
+ import sys
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, dict_append
config = Configuration('umfpack', parent_package, top_path)
config.add_data_dir('tests')
umf_info = get_info('umfpack', notfound_action=1)
## The following addition is needed when linking against a umfpack built
## from the latest SparseSuite. Not (strictly) needed when linking against
## the version in the ubuntu repositories.
+ if not sys.platform == 'darwin':
- umf_info['libraries'].insert(0, 'rt')
+ umf_info['libraries'].insert(0, 'rt')
umfpack_i_file = config.paths('umfpack.i')[0]
def umfpack_i(ext, build_dir):
if umf_info:
return umfpack_i_file
blas_info = get_info('blas_opt')
build_info = {}
dict_append(build_info, **umf_info)
dict_append(build_info, **blas_info)
config.add_extension('__umfpack',
sources=[umfpack_i],
depends=['umfpack.i'],
**build_info)
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
|
## Code Before:
from __future__ import division, print_function, absolute_import
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, dict_append
config = Configuration('umfpack', parent_package, top_path)
config.add_data_dir('tests')
umf_info = get_info('umfpack', notfound_action=1)
## The following addition is needed when linking against a umfpack built
## from the latest SparseSuite. Not (strictly) needed when linking against
## the version in the ubuntu repositories.
umf_info['libraries'].insert(0, 'rt')
umfpack_i_file = config.paths('umfpack.i')[0]
def umfpack_i(ext, build_dir):
if umf_info:
return umfpack_i_file
blas_info = get_info('blas_opt')
build_info = {}
dict_append(build_info, **umf_info)
dict_append(build_info, **blas_info)
config.add_extension('__umfpack',
sources=[umfpack_i],
depends=['umfpack.i'],
**build_info)
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
## Instruction:
Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
## Code After:
from __future__ import division, print_function, absolute_import
import sys
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, dict_append
config = Configuration('umfpack', parent_package, top_path)
config.add_data_dir('tests')
umf_info = get_info('umfpack', notfound_action=1)
## The following addition is needed when linking against a umfpack built
## from the latest SparseSuite. Not (strictly) needed when linking against
## the version in the ubuntu repositories.
if not sys.platform == 'darwin':
umf_info['libraries'].insert(0, 'rt')
umfpack_i_file = config.paths('umfpack.i')[0]
def umfpack_i(ext, build_dir):
if umf_info:
return umfpack_i_file
blas_info = get_info('blas_opt')
build_info = {}
dict_append(build_info, **umf_info)
dict_append(build_info, **blas_info)
config.add_extension('__umfpack',
sources=[umfpack_i],
depends=['umfpack.i'],
**build_info)
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
|
// ... existing code ...
from __future__ import division, print_function, absolute_import
import sys
// ... modified code ...
## the version in the ubuntu repositories.
if not sys.platform == 'darwin':
umf_info['libraries'].insert(0, 'rt')
// ... rest of the code ...
|
1101fd3855c90ece679e4b9af37c5f3f5dc343eb
|
spacy/en/__init__.py
|
spacy/en/__init__.py
|
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language
from ..lemmatizer import Lemmatizer
from ..vocab import Vocab
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..deprecated import fix_glove_vectors_loading
from .language_data import *
try:
basestring
except NameError:
basestring = str
class English(Language):
lang = 'en'
class Defaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'en'
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
tag_map = TAG_MAP
stop_words = STOP_WORDS
def __init__(self, **overrides):
# Special-case hack for loading the GloVe vectors, to support <1.0
overrides = fix_glove_vectors_loading(overrides)
Language.__init__(self, **overrides)
|
from __future__ import unicode_literals
from ..language import Language
from ..lemmatizer import Lemmatizer
from ..vocab import Vocab
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..deprecated import fix_glove_vectors_loading
from .language_data import *
try:
basestring
except NameError:
basestring = str
class English(Language):
lang = 'en'
class Defaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'en'
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
tag_map = TAG_MAP
stop_words = STOP_WORDS
def __init__(self, **overrides):
# Special-case hack for loading the GloVe vectors, to support <1.0
overrides = fix_glove_vectors_loading(overrides)
Language.__init__(self, **overrides)
|
Fix formatting and remove unused imports
|
Fix formatting and remove unused imports
|
Python
|
mit
|
recognai/spaCy,raphael0202/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,raphael0202/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,raphael0202/spaCy,raphael0202/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,honnibal/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,explosion/spaCy,raphael0202/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,raphael0202/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy
|
- from __future__ import unicode_literals, print_function
+ from __future__ import unicode_literals
- from os import path
from ..language import Language
from ..lemmatizer import Lemmatizer
from ..vocab import Vocab
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..deprecated import fix_glove_vectors_loading
from .language_data import *
+
try:
basestring
except NameError:
basestring = str
class English(Language):
lang = 'en'
class Defaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'en'
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
tag_map = TAG_MAP
stop_words = STOP_WORDS
def __init__(self, **overrides):
# Special-case hack for loading the GloVe vectors, to support <1.0
overrides = fix_glove_vectors_loading(overrides)
Language.__init__(self, **overrides)
|
Fix formatting and remove unused imports
|
## Code Before:
from __future__ import unicode_literals, print_function
from os import path
from ..language import Language
from ..lemmatizer import Lemmatizer
from ..vocab import Vocab
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..deprecated import fix_glove_vectors_loading
from .language_data import *
try:
basestring
except NameError:
basestring = str
class English(Language):
lang = 'en'
class Defaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'en'
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
tag_map = TAG_MAP
stop_words = STOP_WORDS
def __init__(self, **overrides):
# Special-case hack for loading the GloVe vectors, to support <1.0
overrides = fix_glove_vectors_loading(overrides)
Language.__init__(self, **overrides)
## Instruction:
Fix formatting and remove unused imports
## Code After:
from __future__ import unicode_literals
from ..language import Language
from ..lemmatizer import Lemmatizer
from ..vocab import Vocab
from ..tokenizer import Tokenizer
from ..attrs import LANG
from ..deprecated import fix_glove_vectors_loading
from .language_data import *
try:
basestring
except NameError:
basestring = str
class English(Language):
lang = 'en'
class Defaults(Language.Defaults):
lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
lex_attr_getters[LANG] = lambda text: 'en'
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
tag_map = TAG_MAP
stop_words = STOP_WORDS
def __init__(self, **overrides):
# Special-case hack for loading the GloVe vectors, to support <1.0
overrides = fix_glove_vectors_loading(overrides)
Language.__init__(self, **overrides)
|
// ... existing code ...
from __future__ import unicode_literals
from ..language import Language
// ... modified code ...
from .language_data import *
// ... rest of the code ...
|
79cbfc35ecca75434cf31839416e5866bad7909d
|
app/__init__.py
|
app/__init__.py
|
import logging
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
|
import logging
logging.root.handlers = []
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
filename='triggear.log')
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
logging.getLogger("").addHandler(console)
|
Add logging to file on side of logging to stdout
|
Add logging to file on side of logging to stdout
|
Python
|
mit
|
futuresimple/triggear
|
import logging
- logging.basicConfig(
+ logging.root.handlers = []
- format='%(asctime)s %(levelname)-8s %(message)s',
+ logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
- level=logging.INFO,
- datefmt='%Y-%m-%d %H:%M:%S')
+ datefmt='%Y-%m-%d %H:%M:%S',
+ level=logging.INFO,
+ filename='triggear.log')
+ console = logging.StreamHandler()
+ console.setLevel(logging.WARNING)
+ logging.getLogger("").addHandler(console)
+
|
Add logging to file on side of logging to stdout
|
## Code Before:
import logging
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
## Instruction:
Add logging to file on side of logging to stdout
## Code After:
import logging
logging.root.handlers = []
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
filename='triggear.log')
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
logging.getLogger("").addHandler(console)
|
# ... existing code ...
logging.root.handlers = []
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
filename='triggear.log')
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
logging.getLogger("").addHandler(console)
# ... rest of the code ...
|
eca911a1b1623368f991dbf47002c0b59abc15db
|
script/lib/config.py
|
script/lib/config.py
|
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '1df8e7cdac8aa74c91c19ae0691ce512d560ab3e'
|
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'aa4874a6bcc51fdd87ca7ae0928514ce83645988'
|
Update libchromiumcontent: Suppress CFAllocator warning.
|
Update libchromiumcontent: Suppress CFAllocator warning.
|
Python
|
mit
|
jjz/electron,Ivshti/electron,howmuchcomputer/electron,simonfork/electron,takashi/electron,SufianHassan/electron,micalan/electron,tylergibson/electron,Gerhut/electron,mattdesl/electron,edulan/electron,edulan/electron,d-salas/electron,gerhardberger/electron,micalan/electron,brenca/electron,stevekinney/electron,pandoraui/electron,rreimann/electron,Jacobichou/electron,SufianHassan/electron,bright-sparks/electron,sshiting/electron,dongjoon-hyun/electron,bpasero/electron,neutrous/electron,mattotodd/electron,shennushi/electron,SufianHassan/electron,dahal/electron,DivyaKMenon/electron,dongjoon-hyun/electron,roadev/electron,aichingm/electron,kokdemo/electron,coderhaoxin/electron,JussMee15/electron,Jonekee/electron,faizalpribadi/electron,pirafrank/electron,mjaniszew/electron,shiftkey/electron,mjaniszew/electron,felixrieseberg/electron,deepak1556/atom-shell,aliib/electron,RIAEvangelist/electron,wan-qy/electron,thingsinjars/electron,takashi/electron,vHanda/electron,cqqccqc/electron,kokdemo/electron,kikong/electron,natgolov/electron,darwin/electron,LadyNaggaga/electron,iftekeriba/electron,d-salas/electron,Zagorakiss/electron,jacksondc/electron,bpasero/electron,eric-seekas/electron,Ivshti/electron,ianscrivener/electron,eric-seekas/electron,farmisen/electron,tonyganch/electron,yalexx/electron,michaelchiche/electron,GoooIce/electron,kcrt/electron,DivyaKMenon/electron,aliib/electron,jtburke/electron,cos2004/electron,Neron-X5/electron,shaundunne/electron,systembugtj/electron,brave/muon,kazupon/electron,jacksondc/electron,coderhaoxin/electron,micalan/electron,kenmozi/electron,arusakov/electron,abhishekgahlot/electron,simonfork/electron,jjz/electron,deed02392/electron,natgolov/electron,gbn972/electron,arturts/electron,preco21/electron,JesselJohn/electron,natgolov/electron,mrwizard82d1/electron,kenmozi/electron,subblue/electron,beni55/electron,yalexx/electron,adcentury/electron,biblerule/UMCTelnetHub,mjaniszew/electron,astoilkov/electron,ervinb/electron,aliib/electron,christian-bromann/electron,astoilkov/electron,fffej/electron,seanchas116/electron,Floato/electron,thompsonemerson/electron,etiktin/electron,shennushi/electron,chrisswk/electron,adamjgray/electron,jjz/electron,iftekeriba/electron,thingsinjars/electron,simongregory/electron,christian-bromann/electron,seanchas116/electron,MaxWhere/electron,gabrielPeart/electron,MaxGraey/electron,trigrass2/electron,soulteary/electron,fabien-d/electron,bobwol/electron,vHanda/electron,neutrous/electron,beni55/electron,voidbridge/electron,miniak/electron,John-Lin/electron,saronwei/electron,brave/electron,jhen0409/electron,tomashanacek/electron,BionicClick/electron,matiasinsaurralde/electron,LadyNaggaga/electron,systembugtj/electron,webmechanicx/electron,micalan/electron,subblue/electron,rhencke/electron,abhishekgahlot/electron,leethomas/electron,abhishekgahlot/electron,vHanda/electron,howmuchcomputer/electron,destan/electron,mirrh/electron,trigrass2/electron,nicobot/electron,pombredanne/electron,jonatasfreitasv/electron,JussMee15/electron,iftekeriba/electron,ervinb/electron,neutrous/electron,takashi/electron,gabrielPeart/electron,preco21/electron,ankitaggarwal011/electron,xiruibing/electron,simongregory/electron,gabriel/electron,the-ress/electron,mjaniszew/electron,gamedevsam/electron,felixrieseberg/electron,bright-sparks/electron,nagyistoce/electron-atom-shell,seanchas116/electron,JussMee15/electron,minggo/electron,synaptek/electron,gerhardberger/electron,zhakui/electron,anko/electron,RobertJGabriel/electron,medixdev/electron,bpasero/electron,jjz/electron,lzpfmh/electron,pandoraui/electron,nicholasess/electron,evgenyzinoviev/electron,pirafrank/electron,mirrh/electron,vaginessa/electron,kcrt/electron,pandoraui/electron,timruffles/electron,aaron-goshine/electron,beni55/electron,GoooIce/electron,RobertJGabriel/electron,bitemyapp/electron,kazupon/electron,robinvandernoord/electron,eric-seekas/electron,eriser/electron,MaxWhere/electron,yalexx/electron,lrlna/electron,jannishuebl/electron,Evercoder/electron,natgolov/electron,cqqccqc/electron,digideskio/electron,kenmozi/electron,renaesop/electron,lrlna/electron,kostia/electron,tomashanacek/electron,jlord/electron,stevekinney/electron,joaomoreno/atom-shell,the-ress/electron,chriskdon/electron,farmisen/electron,jjz/electron,shaundunne/electron,vipulroxx/electron,jsutcodes/electron,sshiting/electron,christian-bromann/electron,simongregory/electron,miniak/electron,beni55/electron,christian-bromann/electron,bbondy/electron,tonyganch/electron,voidbridge/electron,setzer777/electron,icattlecoder/electron,kokdemo/electron,chriskdon/electron,jtburke/electron,carsonmcdonald/electron,joneit/electron,destan/electron,tonyganch/electron,twolfson/electron,felixrieseberg/electron,Faiz7412/electron,yalexx/electron,wan-qy/electron,aichingm/electron,jannishuebl/electron,leethomas/electron,sircharleswatson/electron,Jonekee/electron,nagyistoce/electron-atom-shell,miniak/electron,Faiz7412/electron,Andrey-Pavlov/electron,dahal/electron,arturts/electron,setzer777/electron,thompsonemerson/electron,d-salas/electron,evgenyzinoviev/electron,destan/electron,electron/electron,arusakov/electron,fabien-d/electron,matiasinsaurralde/electron,fabien-d/electron,Floato/electron,mrwizard82d1/electron,xiruibing/electron,ervinb/electron,mattotodd/electron,ianscrivener/electron,kikong/electron,nekuz0r/electron,gbn972/electron,medixdev/electron,Jacobichou/electron,tonyganch/electron,vHanda/electron,bright-sparks/electron,gerhardberger/electron,bbondy/electron,timruffles/electron,Gerhut/electron,tylergibson/electron,subblue/electron,nicobot/electron,gamedevsam/electron,posix4e/electron,sircharleswatson/electron,yan-foto/electron,nekuz0r/electron,setzer777/electron,bpasero/electron,brave/electron,pandoraui/electron,posix4e/electron,MaxWhere/electron,rreimann/electron,timruffles/electron,subblue/electron,jlhbaseball15/electron,sshiting/electron,twolfson/electron,gamedevsam/electron,ianscrivener/electron,Jonekee/electron,xfstudio/electron,tomashanacek/electron,evgenyzinoviev/electron,pirafrank/electron,nagyistoce/electron-atom-shell,jacksondc/electron,carsonmcdonald/electron,aichingm/electron,vaginessa/electron,bwiggs/electron,adcentury/electron,MaxWhere/electron,aliib/electron,dongjoon-hyun/electron,Faiz7412/electron,wan-qy/electron,mirrh/electron,subblue/electron,shockone/electron,bobwol/electron,electron/electron,roadev/electron,cqqccqc/electron,shiftkey/electron,edulan/electron,jlord/electron,deed02392/electron,John-Lin/electron,GoooIce/electron,noikiy/electron,digideskio/electron,timruffles/electron,MaxWhere/electron,rprichard/electron,trigrass2/electron,chrisswk/electron,ankitaggarwal011/electron,fabien-d/electron,jonatasfreitasv/electron,rhencke/electron,rreimann/electron,RIAEvangelist/electron,jiaz/electron,carsonmcdonald/electron,kokdemo/electron,webmechanicx/electron,lrlna/electron,yan-foto/electron,edulan/electron,wolfflow/electron,jhen0409/electron,the-ress/electron,edulan/electron,miniak/electron,smczk/electron,maxogden/atom-shell,fomojola/electron,brave/muon,RIAEvangelist/electron,jcblw/electron,jcblw/electron,nekuz0r/electron,Evercoder/electron,icattlecoder/electron,sky7sea/electron,gamedevsam/electron,fomojola/electron,fritx/electron,electron/electron,shockone/electron,bruce/electron,zhakui/electron,gerhardberger/electron,shennushi/electron,systembugtj/electron,adcentury/electron,arturts/electron,LadyNaggaga/electron,icattlecoder/electron,gamedevsam/electron,astoilkov/electron,gbn972/electron,bruce/electron,mattdesl/electron,mrwizard82d1/electron,brave/electron,mattotodd/electron,deepak1556/atom-shell,kcrt/electron,jlord/electron,rajatsingla28/electron,IonicaBizauKitchen/electron,bpasero/electron,tylergibson/electron,wolfflow/electron,pombredanne/electron,baiwyc119/electron,howmuchcomputer/electron,leolujuyi/electron,brenca/electron,Ivshti/electron,jonatasfreitasv/electron,jannishuebl/electron,jlhbaseball15/electron,synaptek/electron,dkfiresky/electron,greyhwndz/electron,bwiggs/electron,Andrey-Pavlov/electron,miniak/electron,iftekeriba/electron,medixdev/electron,bright-sparks/electron,nicobot/electron,noikiy/electron,Evercoder/electron,mubassirhayat/electron,bwiggs/electron,renaesop/electron,gabriel/electron,trankmichael/electron,soulteary/electron,felixrieseberg/electron,oiledCode/electron,mattotodd/electron,the-ress/electron,thingsinjars/electron,felixrieseberg/electron,tylergibson/electron,nicholasess/electron,minggo/electron,icattlecoder/electron,lrlna/electron,fireball-x/atom-shell,synaptek/electron,jsutcodes/electron,jjz/electron,shockone/electron,smczk/electron,fomojola/electron,yalexx/electron,tinydew4/electron,egoist/electron,mirrh/electron,meowlab/electron,wolfflow/electron,dahal/electron,sircharleswatson/electron,tincan24/electron,Gerhut/electron,voidbridge/electron,jlhbaseball15/electron,cos2004/electron,stevekinney/electron,neutrous/electron,preco21/electron,stevemao/electron,meowlab/electron,gabrielPeart/electron,kikong/electron,faizalpribadi/electron,arusakov/electron,Zagorakiss/electron,mattdesl/electron,tylergibson/electron,SufianHassan/electron,yan-foto/electron,dkfiresky/electron,mirrh/electron,LadyNaggaga/electron,cos2004/electron,kenmozi/electron,stevekinney/electron,RIAEvangelist/electron,brenca/electron,fritx/electron,astoilkov/electron,ianscrivener/electron,carsonmcdonald/electron,biblerule/UMCTelnetHub,Faiz7412/electron,farmisen/electron,arturts/electron,leolujuyi/electron,Neron-X5/electron,digideskio/electron,jtburke/electron,deed02392/electron,Rokt33r/electron,JesselJohn/electron,thompsonemerson/electron,neutrous/electron,yalexx/electron,coderhaoxin/electron,xiruibing/electron,bbondy/electron,the-ress/electron,jacksondc/electron,IonicaBizauKitchen/electron,renaesop/electron,BionicClick/electron,ianscrivener/electron,bpasero/electron,baiwyc119/electron,jannishuebl/electron,joneit/electron,thomsonreuters/electron,trankmichael/electron,eriser/electron,gerhardberger/electron,webmechanicx/electron,leftstick/electron,jaanus/electron,maxogden/atom-shell,Rokt33r/electron,MaxGraey/electron,rajatsingla28/electron,joaomoreno/atom-shell,eriser/electron,leolujuyi/electron,JesselJohn/electron,gamedevsam/electron,digideskio/electron,Jacobichou/electron,etiktin/electron,matiasinsaurralde/electron,robinvandernoord/electron,JussMee15/electron,greyhwndz/electron,rhencke/electron,minggo/electron,anko/electron,jsutcodes/electron,fffej/electron,jtburke/electron,deepak1556/atom-shell,jannishuebl/electron,bwiggs/electron,evgenyzinoviev/electron,tomashanacek/electron,noikiy/electron,vaginessa/electron,faizalpribadi/electron,DivyaKMenon/electron,davazp/electron,dongjoon-hyun/electron,davazp/electron,mattotodd/electron,jtburke/electron,deed02392/electron,fireball-x/atom-shell,RobertJGabriel/electron,Andrey-Pavlov/electron,stevekinney/electron,anko/electron,egoist/electron,takashi/electron,astoilkov/electron,sircharleswatson/electron,dahal/electron,mhkeller/electron,nekuz0r/electron,minggo/electron,coderhaoxin/electron,adamjgray/electron,gabrielPeart/electron,JussMee15/electron,aaron-goshine/electron,tincan24/electron,the-ress/electron,aaron-goshine/electron,jaanus/electron,LadyNaggaga/electron,jsutcodes/electron,stevekinney/electron,abhishekgahlot/electron,mattotodd/electron,Gerhut/electron,adamjgray/electron,tincan24/electron,preco21/electron,saronwei/electron,baiwyc119/electron,ankitaggarwal011/electron,wan-qy/electron,JesselJohn/electron,jsutcodes/electron,posix4e/electron,John-Lin/electron,wan-qy/electron,Andrey-Pavlov/electron,posix4e/electron,gstack/infinium-shell,pirafrank/electron,John-Lin/electron,aaron-goshine/electron,RobertJGabriel/electron,ankitaggarwal011/electron,synaptek/electron,electron/electron,arusakov/electron,leethomas/electron,shiftkey/electron,roadev/electron,miniak/electron,chriskdon/electron,shockone/electron,xfstudio/electron,seanchas116/electron,medixdev/electron,cos2004/electron,Jonekee/electron,rajatsingla28/electron,electron/electron,rsvip/electron,RIAEvangelist/electron,rreimann/electron,Evercoder/electron,gabriel/electron,carsonmcdonald/electron,fireball-x/atom-shell,posix4e/electron,Jacobichou/electron,pombredanne/electron,bruce/electron,DivyaKMenon/electron,brave/electron,smczk/electron,minggo/electron,shaundunne/electron,stevemao/electron,jtburke/electron,subblue/electron,jhen0409/electron,jonatasfreitasv/electron,jiaz/electron,fritx/electron,systembugtj/electron,oiledCode/electron,greyhwndz/electron,baiwyc119/electron,cos2004/electron,rsvip/electron,Floato/electron,mjaniszew/electron,jiaz/electron,Neron-X5/electron,hokein/atom-shell,IonicaBizauKitchen/electron,digideskio/electron,tinydew4/electron,adcentury/electron,fireball-x/atom-shell,sky7sea/electron,nicobot/electron,vipulroxx/electron,biblerule/UMCTelnetHub,nicholasess/electron,LadyNaggaga/electron,ervinb/electron,ankitaggarwal011/electron,biblerule/UMCTelnetHub,aliib/electron,darwin/electron,etiktin/electron,chriskdon/electron,webmechanicx/electron,michaelchiche/electron,MaxGraey/electron,lzpfmh/electron,bitemyapp/electron,iftekeriba/electron,MaxGraey/electron,edulan/electron,brenca/electron,baiwyc119/electron,gabriel/electron,Ivshti/electron,bruce/electron,tinydew4/electron,tinydew4/electron,IonicaBizauKitchen/electron,rhencke/electron,eriser/electron,kazupon/electron,kokdemo/electron,fritx/electron,joaomoreno/atom-shell,benweissmann/electron,bruce/electron,thompsonemerson/electron,fireball-x/atom-shell,fomojola/electron,lrlna/electron,voidbridge/electron,kostia/electron,leftstick/electron,mhkeller/electron,pandoraui/electron,ervinb/electron,meowlab/electron,fffej/electron,aecca/electron,webmechanicx/electron,Gerhut/electron,aaron-goshine/electron,nicobot/electron,sky7sea/electron,trankmichael/electron,tylergibson/electron,JussMee15/electron,mubassirhayat/electron,Floato/electron,rajatsingla28/electron,brave/muon,shennushi/electron,ianscrivener/electron,xfstudio/electron,shockone/electron,Gerhut/electron,coderhaoxin/electron,eric-seekas/electron,medixdev/electron,fritx/electron,meowlab/electron,lzpfmh/electron,davazp/electron,cqqccqc/electron,lzpfmh/electron,GoooIce/electron,sircharleswatson/electron,sshiting/electron,faizalpribadi/electron,egoist/electron,bright-sparks/electron,rreimann/electron,christian-bromann/electron,synaptek/electron,voidbridge/electron,stevemao/electron,stevemao/electron,yan-foto/electron,gabrielPeart/electron,timruffles/electron,michaelchiche/electron,vaginessa/electron,Zagorakiss/electron,trigrass2/electron,tincan24/electron,shennushi/electron,thomsonreuters/electron,icattlecoder/electron,tinydew4/electron,Rokt33r/electron,destan/electron,roadev/electron,rsvip/electron,xfstudio/electron,gbn972/electron,egoist/electron,jlhbaseball15/electron,systembugtj/electron,anko/electron,d-salas/electron,leolujuyi/electron,Evercoder/electron,kostia/electron,bobwol/electron,aecca/electron,deed02392/electron,GoooIce/electron,jlord/electron,systembugtj/electron,d-salas/electron,jiaz/electron,mjaniszew/electron,lzpfmh/electron,zhakui/electron,Jonekee/electron,rhencke/electron,howmuchcomputer/electron,vHanda/electron,jlhbaseball15/electron,electron/electron,seanchas116/electron,kikong/electron,kazupon/electron,MaxGraey/electron,shiftkey/electron,michaelchiche/electron,simonfork/electron,micalan/electron,leftstick/electron,voidbridge/electron,jiaz/electron,bobwol/electron,kostia/electron,bbondy/electron,GoooIce/electron,tinydew4/electron,cqqccqc/electron,chrisswk/electron,hokein/atom-shell,robinvandernoord/electron,robinvandernoord/electron,maxogden/atom-shell,John-Lin/electron,jaanus/electron,tincan24/electron,shiftkey/electron,natgolov/electron,astoilkov/electron,pandoraui/electron,mirrh/electron,michaelchiche/electron,rreimann/electron,oiledCode/electron,deed02392/electron,mhkeller/electron,thingsinjars/electron,mattdesl/electron,RobertJGabriel/electron,noikiy/electron,brave/electron,BionicClick/electron,beni55/electron,thomsonreuters/electron,renaesop/electron,matiasinsaurralde/electron,gabrielPeart/electron,simongregory/electron,greyhwndz/electron,dahal/electron,nicobot/electron,tomashanacek/electron,jacksondc/electron,Evercoder/electron,bitemyapp/electron,saronwei/electron,jhen0409/electron,brave/electron,vHanda/electron,benweissmann/electron,brenca/electron,wolfflow/electron,tonyganch/electron,Floato/electron,Ivshti/electron,smczk/electron,deepak1556/atom-shell,shiftkey/electron,hokein/atom-shell,mhkeller/electron,ervinb/electron,zhakui/electron,christian-bromann/electron,aecca/electron,jonatasfreitasv/electron,beni55/electron,yan-foto/electron,joneit/electron,adamjgray/electron,twolfson/electron,zhakui/electron,bruce/electron,digideskio/electron,trankmichael/electron,oiledCode/electron,saronwei/electron,Zagorakiss/electron,rajatsingla28/electron,rprichard/electron,seanchas116/electron,Rokt33r/electron,jacksondc/electron,arusakov/electron,nicholasess/electron,mubassirhayat/electron,nekuz0r/electron,shaundunne/electron,icattlecoder/electron,gstack/infinium-shell,fritx/electron,howmuchcomputer/electron,anko/electron,aliib/electron,leftstick/electron,bitemyapp/electron,wolfflow/electron,rprichard/electron,mrwizard82d1/electron,trigrass2/electron,twolfson/electron,dkfiresky/electron,nagyistoce/electron-atom-shell,shennushi/electron,nicholasess/electron,kikong/electron,kostia/electron,maxogden/atom-shell,natgolov/electron,brave/muon,gerhardberger/electron,arusakov/electron,rsvip/electron,benweissmann/electron,Jacobichou/electron,oiledCode/electron,bwiggs/electron,sshiting/electron,fabien-d/electron,soulteary/electron,the-ress/electron,egoist/electron,kcrt/electron,jhen0409/electron,rprichard/electron,d-salas/electron,fffej/electron,adamjgray/electron,meowlab/electron,darwin/electron,bobwol/electron,renaesop/electron,kostia/electron,adcentury/electron,jcblw/electron,etiktin/electron,saronwei/electron,Zagorakiss/electron,joaomoreno/atom-shell,davazp/electron,thomsonreuters/electron,lrlna/electron,posix4e/electron,joneit/electron,simongregory/electron,thompsonemerson/electron,faizalpribadi/electron,dkfiresky/electron,gstack/infinium-shell,jannishuebl/electron,bobwol/electron,pombredanne/electron,jcblw/electron,howmuchcomputer/electron,Jacobichou/electron,gbn972/electron,Neron-X5/electron,oiledCode/electron,wolfflow/electron,brave/muon,destan/electron,Floato/electron,benweissmann/electron,tincan24/electron,soulteary/electron,kcrt/electron,bitemyapp/electron,simonfork/electron,evgenyzinoviev/electron,trigrass2/electron,biblerule/UMCTelnetHub,coderhaoxin/electron,shockone/electron,iftekeriba/electron,thompsonemerson/electron,jaanus/electron,stevemao/electron,Jonekee/electron,farmisen/electron,medixdev/electron,mrwizard82d1/electron,BionicClick/electron,jaanus/electron,adamjgray/electron,baiwyc119/electron,Andrey-Pavlov/electron,matiasinsaurralde/electron,maxogden/atom-shell,setzer777/electron,benweissmann/electron,nicholasess/electron,electron/electron,MaxWhere/electron,twolfson/electron,biblerule/UMCTelnetHub,gabriel/electron,vaginessa/electron,DivyaKMenon/electron,robinvandernoord/electron,jhen0409/electron,dkfiresky/electron,setzer777/electron,leftstick/electron,vaginessa/electron,rajatsingla28/electron,deepak1556/atom-shell,vipulroxx/electron,bitemyapp/electron,aaron-goshine/electron,davazp/electron,jcblw/electron,mattdesl/electron,wan-qy/electron,trankmichael/electron,trankmichael/electron,farmisen/electron,rsvip/electron,vipulroxx/electron,aichingm/electron,eric-seekas/electron,jsutcodes/electron,micalan/electron,aecca/electron,thomsonreuters/electron,davazp/electron,ankitaggarwal011/electron,fffej/electron,mrwizard82d1/electron,webmechanicx/electron,xiruibing/electron,adcentury/electron,synaptek/electron,matiasinsaurralde/electron,lzpfmh/electron,DivyaKMenon/electron,soulteary/electron,kazupon/electron,RobertJGabriel/electron,sky7sea/electron,chrisswk/electron,IonicaBizauKitchen/electron,Neron-X5/electron,nekuz0r/electron,jonatasfreitasv/electron,michaelchiche/electron,gstack/infinium-shell,etiktin/electron,xfstudio/electron,mubassirhayat/electron,Andrey-Pavlov/electron,chrisswk/electron,nagyistoce/electron-atom-shell,fomojola/electron,smczk/electron,stevemao/electron,kenmozi/electron,carsonmcdonald/electron,eric-seekas/electron,neutrous/electron,thomsonreuters/electron,evgenyzinoviev/electron,simonfork/electron,leethomas/electron,vipulroxx/electron,takashi/electron,leethomas/electron,SufianHassan/electron,dahal/electron,JesselJohn/electron,joneit/electron,sky7sea/electron,jaanus/electron,darwin/electron,simonfork/electron,bpasero/electron,xfstudio/electron,greyhwndz/electron,twolfson/electron,leftstick/electron,aecca/electron,arturts/electron,jiaz/electron,chriskdon/electron,mhkeller/electron,roadev/electron,egoist/electron,sircharleswatson/electron,kazupon/electron,noikiy/electron,bbondy/electron,brenca/electron,joneit/electron,fomojola/electron,thingsinjars/electron,dongjoon-hyun/electron,minggo/electron,tomashanacek/electron,Neron-X5/electron,aecca/electron,dongjoon-hyun/electron,pirafrank/electron,zhakui/electron,greyhwndz/electron,yan-foto/electron,Rokt33r/electron,xiruibing/electron,xiruibing/electron,roadev/electron,soulteary/electron,mhkeller/electron,John-Lin/electron,leolujuyi/electron,gstack/infinium-shell,smczk/electron,destan/electron,setzer777/electron,Zagorakiss/electron,bbondy/electron,gerhardberger/electron,preco21/electron,chriskdon/electron,jcblw/electron,bright-sparks/electron,eriser/electron,Rokt33r/electron,gabriel/electron,leolujuyi/electron,fffej/electron,renaesop/electron,tonyganch/electron,meowlab/electron,aichingm/electron,sky7sea/electron,robinvandernoord/electron,sshiting/electron,vipulroxx/electron,leethomas/electron,benweissmann/electron,darwin/electron,thingsinjars/electron,preco21/electron,abhishekgahlot/electron,joaomoreno/atom-shell,mubassirhayat/electron,kokdemo/electron,farmisen/electron,bwiggs/electron,cos2004/electron,joaomoreno/atom-shell,shaundunne/electron,kcrt/electron,hokein/atom-shell,SufianHassan/electron,felixrieseberg/electron,Faiz7412/electron,eriser/electron,aichingm/electron,mattdesl/electron,RIAEvangelist/electron,gbn972/electron,dkfiresky/electron,takashi/electron,noikiy/electron,IonicaBizauKitchen/electron,jlord/electron,shaundunne/electron,JesselJohn/electron,pirafrank/electron,BionicClick/electron,anko/electron,pombredanne/electron,abhishekgahlot/electron,faizalpribadi/electron,simongregory/electron,rhencke/electron,arturts/electron,hokein/atom-shell,saronwei/electron,cqqccqc/electron,brave/muon,kenmozi/electron,etiktin/electron,pombredanne/electron,jlhbaseball15/electron,BionicClick/electron
|
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
- LIBCHROMIUMCONTENT_COMMIT = '1df8e7cdac8aa74c91c19ae0691ce512d560ab3e'
+ LIBCHROMIUMCONTENT_COMMIT = 'aa4874a6bcc51fdd87ca7ae0928514ce83645988'
|
Update libchromiumcontent: Suppress CFAllocator warning.
|
## Code Before:
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '1df8e7cdac8aa74c91c19ae0691ce512d560ab3e'
## Instruction:
Update libchromiumcontent: Suppress CFAllocator warning.
## Code After:
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'aa4874a6bcc51fdd87ca7ae0928514ce83645988'
|
# ... existing code ...
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'aa4874a6bcc51fdd87ca7ae0928514ce83645988'
# ... rest of the code ...
|
82121f05032f83de538c4a16596b24b5b012a3be
|
chaco/shell/tests/test_tutorial_example.py
|
chaco/shell/tests/test_tutorial_example.py
|
import unittest
from numpy import linspace, pi, sin
from enthought.chaco.shell import plot, show, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
x = linspace(-2*pi, 2*pi, 100)
y = sin(x)
plot(x, y, "r-")
title("First plot")
ytitle("sin(x)")
if __name__ == "__main__":
unittest.main()
|
import unittest
from numpy import linspace, pi, sin
from chaco.shell import plot, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
x = linspace(-2*pi, 2*pi, 100)
y = sin(x)
plot(x, y, "r-")
title("First plot")
ytitle("sin(x)")
if __name__ == "__main__":
unittest.main()
|
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
|
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
|
Python
|
bsd-3-clause
|
tommy-u/chaco,burnpanck/chaco,burnpanck/chaco,tommy-u/chaco,tommy-u/chaco,burnpanck/chaco
|
import unittest
from numpy import linspace, pi, sin
- from enthought.chaco.shell import plot, show, title, ytitle
+ from chaco.shell import plot, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
x = linspace(-2*pi, 2*pi, 100)
y = sin(x)
plot(x, y, "r-")
title("First plot")
ytitle("sin(x)")
if __name__ == "__main__":
unittest.main()
|
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
|
## Code Before:
import unittest
from numpy import linspace, pi, sin
from enthought.chaco.shell import plot, show, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
x = linspace(-2*pi, 2*pi, 100)
y = sin(x)
plot(x, y, "r-")
title("First plot")
ytitle("sin(x)")
if __name__ == "__main__":
unittest.main()
## Instruction:
Clean up: pyflakes and remove enthought.chaco import. We should and will update the tutorial later.
## Code After:
import unittest
from numpy import linspace, pi, sin
from chaco.shell import plot, title, ytitle
class InteractiveTestCase(unittest.TestCase):
def test_script(self):
x = linspace(-2*pi, 2*pi, 100)
y = sin(x)
plot(x, y, "r-")
title("First plot")
ytitle("sin(x)")
if __name__ == "__main__":
unittest.main()
|
...
from numpy import linspace, pi, sin
from chaco.shell import plot, title, ytitle
...
|
8f0b72dcad39fbd6072185bf2244eb75f0f45a96
|
better_od/core.py
|
better_od/core.py
|
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
def __init__(self, **kwargs):
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
return self._keys.index(key)
def insert(self, key, value, index):
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
|
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
'''BetterOrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
def __init__(self, **kwargs):
'''BetterOrderedDict accepts an optional iterable of two-tuples
indicating keys and values.'''
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
'''Accepts a parameter, :key:, and returns an integer value
representing its index in the ordered list of keys.'''
return self._keys.index(key)
def insert(self, key, value, index):
'''Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.'''
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
|
Add docstrings for most public API methods.
|
Add docstrings for most public API methods.
|
Python
|
mit
|
JustusW/BetterOrderedDict,therealfakemoot/collections2
|
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
+ '''BetterOrderedDict is a mapping object that allows for ordered access
+ and insertion of keys. With the exception of the key_index, insert, and
+ reorder_keys methods behavior is identical to stock dictionary objects.'''
+
def __init__(self, **kwargs):
+ '''BetterOrderedDict accepts an optional iterable of two-tuples
+ indicating keys and values.'''
+
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
+ '''Accepts a parameter, :key:, and returns an integer value
+ representing its index in the ordered list of keys.'''
return self._keys.index(key)
def insert(self, key, value, index):
+ '''Accepts a :key:, :value:, and :index: parameter and inserts
+ a new key, value member at the desired index.'''
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
+ '''Accepts a :keys: parameter, an iterable of keys in the
+ desired new order. The :keys: parameter must contain all
+ existing keys.'''
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
|
Add docstrings for most public API methods.
|
## Code Before:
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
def __init__(self, **kwargs):
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
return self._keys.index(key)
def insert(self, key, value, index):
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
## Instruction:
Add docstrings for most public API methods.
## Code After:
from collections import MutableMapping
class BetterOrderedDict(MutableMapping):
'''BetterOrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
def __init__(self, **kwargs):
'''BetterOrderedDict accepts an optional iterable of two-tuples
indicating keys and values.'''
self._d = dict()
self._keys = []
def __len__(self):
return len(self._d)
def __iter__(self):
for key in self._keys:
yield key
def __setitem__(self, key, value):
self._keys.append(key)
self._d[key] = value
def __getitem__(self, key):
return self._d[key]
def __delitem__(self, key):
self._keys.pop(key)
del self._d[key]
def key_index(self, key):
'''Accepts a parameter, :key:, and returns an integer value
representing its index in the ordered list of keys.'''
return self._keys.index(key)
def insert(self, key, value, index):
'''Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.'''
if key in self._d:
self._keys.pop(key)
self._keys.insert(index, key)
self._d[key] = value
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if self._keys != self._d:
raise ValueError('Keys do not match.')
self._keys = keys
|
# ... existing code ...
class BetterOrderedDict(MutableMapping):
'''BetterOrderedDict is a mapping object that allows for ordered access
and insertion of keys. With the exception of the key_index, insert, and
reorder_keys methods behavior is identical to stock dictionary objects.'''
def __init__(self, **kwargs):
'''BetterOrderedDict accepts an optional iterable of two-tuples
indicating keys and values.'''
self._d = dict()
# ... modified code ...
def key_index(self, key):
'''Accepts a parameter, :key:, and returns an integer value
representing its index in the ordered list of keys.'''
return self._keys.index(key)
...
def insert(self, key, value, index):
'''Accepts a :key:, :value:, and :index: parameter and inserts
a new key, value member at the desired index.'''
if key in self._d:
...
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if self._keys != self._d:
# ... rest of the code ...
|
ee6bd389e3e602b67fac399cdb4a50c3a67666b9
|
twitter/admin.py
|
twitter/admin.py
|
from django.contrib import admin
from twitter.models import User, Tweet, Analytics, AnalyticsReport
class UserAdmin(admin.ModelAdmin):
list_display = ('screen_name', 'current_followers')
class AnalyticsAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'followers',
'following',
'listed',
'tweet_count',
'retweet_count',
'reply_count',
'user_mention_count',
'link_count',
'hashtag_count',
)
class AnalyticsReportAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'tweets_reweeted_count',
'tweets_favorited_count',
)
admin.site.register(User, UserAdmin)
admin.site.register(Tweet)
admin.site.register(Analytics, AnalyticsAdmin)
admin.site.register(AnalyticsReport, AnalyticsReportAdmin)
|
from django.contrib import admin
from twitter.models import User, Tweet, Analytics, AnalyticsReport
class UserAdmin(admin.ModelAdmin):
list_display = ('screen_name', 'current_followers')
class AnalyticsAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'followers',
'following',
'listed',
'tweet_count',
'retweet_count',
'reply_count',
'user_mention_count',
'link_count',
'hashtag_count',
)
list_filter = ('user',)
class AnalyticsReportAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'tweets_reweeted_count',
'tweets_favorited_count',
)
admin.site.register(User, UserAdmin)
admin.site.register(Tweet)
admin.site.register(Analytics, AnalyticsAdmin)
admin.site.register(AnalyticsReport, AnalyticsReportAdmin)
|
Add a list filter to make looking a specific users easier.
|
Add a list filter to make looking a specific users easier.
|
Python
|
mit
|
CIGIHub/tweet_cache,albertoconnor/tweet_cache
|
from django.contrib import admin
from twitter.models import User, Tweet, Analytics, AnalyticsReport
class UserAdmin(admin.ModelAdmin):
list_display = ('screen_name', 'current_followers')
class AnalyticsAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'followers',
'following',
'listed',
'tweet_count',
'retweet_count',
'reply_count',
'user_mention_count',
'link_count',
'hashtag_count',
)
+ list_filter = ('user',)
class AnalyticsReportAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'tweets_reweeted_count',
'tweets_favorited_count',
)
admin.site.register(User, UserAdmin)
admin.site.register(Tweet)
admin.site.register(Analytics, AnalyticsAdmin)
admin.site.register(AnalyticsReport, AnalyticsReportAdmin)
|
Add a list filter to make looking a specific users easier.
|
## Code Before:
from django.contrib import admin
from twitter.models import User, Tweet, Analytics, AnalyticsReport
class UserAdmin(admin.ModelAdmin):
list_display = ('screen_name', 'current_followers')
class AnalyticsAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'followers',
'following',
'listed',
'tweet_count',
'retweet_count',
'reply_count',
'user_mention_count',
'link_count',
'hashtag_count',
)
class AnalyticsReportAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'tweets_reweeted_count',
'tweets_favorited_count',
)
admin.site.register(User, UserAdmin)
admin.site.register(Tweet)
admin.site.register(Analytics, AnalyticsAdmin)
admin.site.register(AnalyticsReport, AnalyticsReportAdmin)
## Instruction:
Add a list filter to make looking a specific users easier.
## Code After:
from django.contrib import admin
from twitter.models import User, Tweet, Analytics, AnalyticsReport
class UserAdmin(admin.ModelAdmin):
list_display = ('screen_name', 'current_followers')
class AnalyticsAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'followers',
'following',
'listed',
'tweet_count',
'retweet_count',
'reply_count',
'user_mention_count',
'link_count',
'hashtag_count',
)
list_filter = ('user',)
class AnalyticsReportAdmin(admin.ModelAdmin):
list_display = (
'date',
'user',
'tweets_reweeted_count',
'tweets_favorited_count',
)
admin.site.register(User, UserAdmin)
admin.site.register(Tweet)
admin.site.register(Analytics, AnalyticsAdmin)
admin.site.register(AnalyticsReport, AnalyticsReportAdmin)
|
...
)
list_filter = ('user',)
...
|
11abf077a8c429825c2ba55e42ffa590448da502
|
examples/django_app/tests/test_settings.py
|
examples/django_app/tests/test_settings.py
|
from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
def test_name_setting(self):
from django.core.urlresolvers import reverse
api_url = reverse('chatterbot:chatterbot')
response = self.client.get(api_url)
self.assertEqual(response.status_code, 405)
self.assertIn('detail', response.json())
self.assertIn('name', response.json())
self.assertEqual('Django ChatterBot Example', response.json()['name'])
|
from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
def test_name_setting(self):
from django.core.urlresolvers import reverse
api_url = reverse('chatterbot:chatterbot')
response = self.client.get(api_url)
self.assertEqual(response.status_code, 405)
self.assertIn('detail', response.content)
self.assertIn('name', response.content)
self.assertIn('Django ChatterBot Example', response.content)
|
Fix unit tests for Django 1.8
|
Fix unit tests for Django 1.8
|
Python
|
bsd-3-clause
|
vkosuri/ChatterBot,davizucon/ChatterBot,Reinaesaya/OUIRL-ChatBot,gunthercox/ChatterBot,Gustavo6046/ChatterBot,maclogan/VirtualPenPal,Reinaesaya/OUIRL-ChatBot
|
from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
def test_name_setting(self):
from django.core.urlresolvers import reverse
api_url = reverse('chatterbot:chatterbot')
response = self.client.get(api_url)
self.assertEqual(response.status_code, 405)
- self.assertIn('detail', response.json())
+ self.assertIn('detail', response.content)
- self.assertIn('name', response.json())
+ self.assertIn('name', response.content)
- self.assertEqual('Django ChatterBot Example', response.json()['name'])
+ self.assertIn('Django ChatterBot Example', response.content)
|
Fix unit tests for Django 1.8
|
## Code Before:
from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
def test_name_setting(self):
from django.core.urlresolvers import reverse
api_url = reverse('chatterbot:chatterbot')
response = self.client.get(api_url)
self.assertEqual(response.status_code, 405)
self.assertIn('detail', response.json())
self.assertIn('name', response.json())
self.assertEqual('Django ChatterBot Example', response.json()['name'])
## Instruction:
Fix unit tests for Django 1.8
## Code After:
from django.test import TestCase
from django.conf import settings
class SettingsTestCase(TestCase):
def test_modified_settings(self):
with self.settings(CHATTERBOT={'name': 'Jim'}):
self.assertIn('name', settings.CHATTERBOT)
self.assertEqual('Jim', settings.CHATTERBOT['name'])
def test_name_setting(self):
from django.core.urlresolvers import reverse
api_url = reverse('chatterbot:chatterbot')
response = self.client.get(api_url)
self.assertEqual(response.status_code, 405)
self.assertIn('detail', response.content)
self.assertIn('name', response.content)
self.assertIn('Django ChatterBot Example', response.content)
|
// ... existing code ...
self.assertEqual(response.status_code, 405)
self.assertIn('detail', response.content)
self.assertIn('name', response.content)
self.assertIn('Django ChatterBot Example', response.content)
// ... rest of the code ...
|
d9ffd877f646b3a5c020ed823d3541135af74fef
|
tests/test_question.py
|
tests/test_question.py
|
from pywatson.question.question import Question
class TestQuestion:
def test___init___basic(self, questions):
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test_ask_question_basic(self, watson):
answer = watson.ask_question('What is the Labour Code?')
assert type(answer) is Answer
|
from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test___init___complete(self, questions):
"""Question is constructed properly with all parameters provided"""
q = questions[1]
er = q['evidenceRequest']
evidence_request = EvidenceRequest(er['items'], er['profile'])
filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
question = Question(question_text=q['questionText'],
answer_assertion=q['answerAssertion'],
category=q['category'],
context=q['context'],
evidence_request=evidence_request,
filters=filters,
formatted_answer=q['formattedAnswer'],
items=q['items'],
lat=q['lat'],
passthru=q['passthru'],
synonym_list=q['synonymList'])
assert question.question_text == q['questionText']
assert question.answer_assertion == q['answerAssertion']
assert question.category == q['category']
assert question.context == q['context']
assert question.evidence_request == er
assert question.filters == filters
|
Add complete question constructor test
|
Add complete question constructor test
|
Python
|
mit
|
sherlocke/pywatson
|
+ from pywatson.question.evidence_request import EvidenceRequest
+ from pywatson.question.filter import Filter
from pywatson.question.question import Question
- class TestQuestion:
+ class TestQuestion(object):
+ """Unit tests for the Question class"""
+
def test___init___basic(self, questions):
+ """Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
- def test_ask_question_basic(self, watson):
- answer = watson.ask_question('What is the Labour Code?')
- assert type(answer) is Answer
+ def test___init___complete(self, questions):
+ """Question is constructed properly with all parameters provided"""
+ q = questions[1]
+ er = q['evidenceRequest']
+ evidence_request = EvidenceRequest(er['items'], er['profile'])
+ filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
+ question = Question(question_text=q['questionText'],
+ answer_assertion=q['answerAssertion'],
+ category=q['category'],
+ context=q['context'],
+ evidence_request=evidence_request,
+ filters=filters,
+ formatted_answer=q['formattedAnswer'],
+ items=q['items'],
+ lat=q['lat'],
+ passthru=q['passthru'],
+ synonym_list=q['synonymList'])
+ assert question.question_text == q['questionText']
+ assert question.answer_assertion == q['answerAssertion']
+ assert question.category == q['category']
+ assert question.context == q['context']
+ assert question.evidence_request == er
+ assert question.filters == filters
+
|
Add complete question constructor test
|
## Code Before:
from pywatson.question.question import Question
class TestQuestion:
def test___init___basic(self, questions):
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test_ask_question_basic(self, watson):
answer = watson.ask_question('What is the Labour Code?')
assert type(answer) is Answer
## Instruction:
Add complete question constructor test
## Code After:
from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
assert question.question_text == questions[0]['questionText']
def test___init___complete(self, questions):
"""Question is constructed properly with all parameters provided"""
q = questions[1]
er = q['evidenceRequest']
evidence_request = EvidenceRequest(er['items'], er['profile'])
filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
question = Question(question_text=q['questionText'],
answer_assertion=q['answerAssertion'],
category=q['category'],
context=q['context'],
evidence_request=evidence_request,
filters=filters,
formatted_answer=q['formattedAnswer'],
items=q['items'],
lat=q['lat'],
passthru=q['passthru'],
synonym_list=q['synonymList'])
assert question.question_text == q['questionText']
assert question.answer_assertion == q['answerAssertion']
assert question.category == q['category']
assert question.context == q['context']
assert question.evidence_request == er
assert question.filters == filters
|
...
from pywatson.question.evidence_request import EvidenceRequest
from pywatson.question.filter import Filter
from pywatson.question.question import Question
...
class TestQuestion(object):
"""Unit tests for the Question class"""
def test___init___basic(self, questions):
"""Question is constructed properly with just question_text"""
question = Question(questions[0]['questionText'])
...
def test___init___complete(self, questions):
"""Question is constructed properly with all parameters provided"""
q = questions[1]
er = q['evidenceRequest']
evidence_request = EvidenceRequest(er['items'], er['profile'])
filters = [Filter(f['filterType'], f['filterName'], f['values']) for f in q['filters']]
question = Question(question_text=q['questionText'],
answer_assertion=q['answerAssertion'],
category=q['category'],
context=q['context'],
evidence_request=evidence_request,
filters=filters,
formatted_answer=q['formattedAnswer'],
items=q['items'],
lat=q['lat'],
passthru=q['passthru'],
synonym_list=q['synonymList'])
assert question.question_text == q['questionText']
assert question.answer_assertion == q['answerAssertion']
assert question.category == q['category']
assert question.context == q['context']
assert question.evidence_request == er
assert question.filters == filters
...
|
e63a914457fc10d895eb776a164939da3ddd9464
|
waftools/gogobject.py
|
waftools/gogobject.py
|
from waflib.Task import Task
from waflib.TaskGen import extension
class gogobject(Task):
run_str = '${GGG} ${GGGFLAGS} -o ${TGT[0].parent.abspath()} ${SRC}'
@extension('.go.in')
def gogobject_hook(self, node):
tg = self.bld.get_tgen_by_name('go-gobject-gen')
ggg = tg.link_task.outputs[0]
if not self.env.GGG:
self.env.GGG = ggg.abspath()
go_out = node.change_ext('')
c_out = go_out.change_ext('.gen.c')
h_out = go_out.change_ext('.gen.h')
task = self.create_task('gogobject', node, [go_out, c_out, h_out])
task.dep_nodes = [ggg]
return task
|
from waflib.Task import Task
from waflib.TaskGen import extension
class gogobject(Task):
run_str = '${GGG} ${GGGFLAGS} -o ${TGT[0].parent.abspath()} ${SRC}'
@extension('.go.in')
def gogobject_hook(self, node):
tg = self.bld.get_tgen_by_name('go-gobject-gen')
ggg = tg.link_task.outputs[0]
if not self.env.GGG:
self.env.GGG = ggg.abspath()
go_out = node.change_ext('')
c_out = go_out.change_ext('.gen.c')
h_out = go_out.change_ext('.gen.h')
task = self.create_task('gogobject', node, [go_out, c_out, h_out])
task.dep_nodes = [ggg, node.parent.find_node('config.json')]
return task
|
Use config.json as a go-gobject-gen dependency as well.
|
Use config.json as a go-gobject-gen dependency as well.
|
Python
|
mit
|
nsf/gogobject,nsf/gogobject,nsf/gogobject,nsf/gogobject
|
from waflib.Task import Task
from waflib.TaskGen import extension
class gogobject(Task):
run_str = '${GGG} ${GGGFLAGS} -o ${TGT[0].parent.abspath()} ${SRC}'
@extension('.go.in')
def gogobject_hook(self, node):
tg = self.bld.get_tgen_by_name('go-gobject-gen')
ggg = tg.link_task.outputs[0]
if not self.env.GGG:
self.env.GGG = ggg.abspath()
go_out = node.change_ext('')
c_out = go_out.change_ext('.gen.c')
h_out = go_out.change_ext('.gen.h')
task = self.create_task('gogobject', node, [go_out, c_out, h_out])
- task.dep_nodes = [ggg]
+ task.dep_nodes = [ggg, node.parent.find_node('config.json')]
return task
|
Use config.json as a go-gobject-gen dependency as well.
|
## Code Before:
from waflib.Task import Task
from waflib.TaskGen import extension
class gogobject(Task):
run_str = '${GGG} ${GGGFLAGS} -o ${TGT[0].parent.abspath()} ${SRC}'
@extension('.go.in')
def gogobject_hook(self, node):
tg = self.bld.get_tgen_by_name('go-gobject-gen')
ggg = tg.link_task.outputs[0]
if not self.env.GGG:
self.env.GGG = ggg.abspath()
go_out = node.change_ext('')
c_out = go_out.change_ext('.gen.c')
h_out = go_out.change_ext('.gen.h')
task = self.create_task('gogobject', node, [go_out, c_out, h_out])
task.dep_nodes = [ggg]
return task
## Instruction:
Use config.json as a go-gobject-gen dependency as well.
## Code After:
from waflib.Task import Task
from waflib.TaskGen import extension
class gogobject(Task):
run_str = '${GGG} ${GGGFLAGS} -o ${TGT[0].parent.abspath()} ${SRC}'
@extension('.go.in')
def gogobject_hook(self, node):
tg = self.bld.get_tgen_by_name('go-gobject-gen')
ggg = tg.link_task.outputs[0]
if not self.env.GGG:
self.env.GGG = ggg.abspath()
go_out = node.change_ext('')
c_out = go_out.change_ext('.gen.c')
h_out = go_out.change_ext('.gen.h')
task = self.create_task('gogobject', node, [go_out, c_out, h_out])
task.dep_nodes = [ggg, node.parent.find_node('config.json')]
return task
|
// ... existing code ...
task = self.create_task('gogobject', node, [go_out, c_out, h_out])
task.dep_nodes = [ggg, node.parent.find_node('config.json')]
return task
// ... rest of the code ...
|
179df740725c0d3c9e256629e4718afcfa3b0cec
|
terminal_notifier.py
|
terminal_notifier.py
|
import distutils.spawn
import os
import pipes
import weechat
def notify(data, signal, signal_data):
command = ("terminal-notifier -message %s -title WeeChat -sound Hero"
% pipes.quote(signal_data))
exit_code = os.system(command)
if exit_code == 0:
return weechat.WEECHAT_RC_ERROR
else:
return weechat.WEECHAT_RC_OK
def main():
if distutils.spawn.find_executable("terminal-notifier") is None:
return weechat.WEECHAT_RC_ERROR
if not weechat.register("terminal_notifier", "Keith Smiley", "1.0.0", "MIT",
"Get OS X notifications for messages", "", ""):
return weechat.WEECHAT_RC_ERROR
weechat.hook_signal("weechat_pv", "notify", "")
weechat.hook_signal("weechat_highlight", "notify", "")
return weechat.WEECHAT_RC_OK
if __name__ == "__main__":
main()
|
import distutils.spawn
import os
import pipes
import weechat
def notify(data, signal, signal_data):
message = signal_data
if message[0] is "[":
message = "\\%s" % message
elif message[0] is "-":
message = "\\%s" % message
command = ("terminal-notifier -message %s -title WeeChat -sound Hero"
% pipes.quote(message))
exit_code = os.system(command)
if exit_code == 0:
return weechat.WEECHAT_RC_ERROR
else:
return weechat.WEECHAT_RC_OK
def main():
if distutils.spawn.find_executable("terminal-notifier") is None:
return weechat.WEECHAT_RC_ERROR
if not weechat.register("terminal_notifier", "Keith Smiley", "1.0.0", "MIT",
"Get OS X notifications for messages", "", ""):
return weechat.WEECHAT_RC_ERROR
weechat.hook_signal("weechat_pv", "notify", "")
weechat.hook_signal("weechat_highlight", "notify", "")
return weechat.WEECHAT_RC_OK
if __name__ == "__main__":
main()
|
Fix characters which break terminal-notifier
|
Fix characters which break terminal-notifier
If your message starts with either a [ or - (and probably more I haven't
found yet) terminal-notifier blows up because of the way it parses its
arguments
|
Python
|
mit
|
keith/terminal-notifier-weechat
|
import distutils.spawn
import os
import pipes
import weechat
def notify(data, signal, signal_data):
+ message = signal_data
+ if message[0] is "[":
+ message = "\\%s" % message
+ elif message[0] is "-":
+ message = "\\%s" % message
+
command = ("terminal-notifier -message %s -title WeeChat -sound Hero"
- % pipes.quote(signal_data))
+ % pipes.quote(message))
exit_code = os.system(command)
if exit_code == 0:
return weechat.WEECHAT_RC_ERROR
else:
return weechat.WEECHAT_RC_OK
def main():
if distutils.spawn.find_executable("terminal-notifier") is None:
return weechat.WEECHAT_RC_ERROR
if not weechat.register("terminal_notifier", "Keith Smiley", "1.0.0", "MIT",
"Get OS X notifications for messages", "", ""):
return weechat.WEECHAT_RC_ERROR
weechat.hook_signal("weechat_pv", "notify", "")
weechat.hook_signal("weechat_highlight", "notify", "")
return weechat.WEECHAT_RC_OK
if __name__ == "__main__":
main()
|
Fix characters which break terminal-notifier
|
## Code Before:
import distutils.spawn
import os
import pipes
import weechat
def notify(data, signal, signal_data):
command = ("terminal-notifier -message %s -title WeeChat -sound Hero"
% pipes.quote(signal_data))
exit_code = os.system(command)
if exit_code == 0:
return weechat.WEECHAT_RC_ERROR
else:
return weechat.WEECHAT_RC_OK
def main():
if distutils.spawn.find_executable("terminal-notifier") is None:
return weechat.WEECHAT_RC_ERROR
if not weechat.register("terminal_notifier", "Keith Smiley", "1.0.0", "MIT",
"Get OS X notifications for messages", "", ""):
return weechat.WEECHAT_RC_ERROR
weechat.hook_signal("weechat_pv", "notify", "")
weechat.hook_signal("weechat_highlight", "notify", "")
return weechat.WEECHAT_RC_OK
if __name__ == "__main__":
main()
## Instruction:
Fix characters which break terminal-notifier
## Code After:
import distutils.spawn
import os
import pipes
import weechat
def notify(data, signal, signal_data):
message = signal_data
if message[0] is "[":
message = "\\%s" % message
elif message[0] is "-":
message = "\\%s" % message
command = ("terminal-notifier -message %s -title WeeChat -sound Hero"
% pipes.quote(message))
exit_code = os.system(command)
if exit_code == 0:
return weechat.WEECHAT_RC_ERROR
else:
return weechat.WEECHAT_RC_OK
def main():
if distutils.spawn.find_executable("terminal-notifier") is None:
return weechat.WEECHAT_RC_ERROR
if not weechat.register("terminal_notifier", "Keith Smiley", "1.0.0", "MIT",
"Get OS X notifications for messages", "", ""):
return weechat.WEECHAT_RC_ERROR
weechat.hook_signal("weechat_pv", "notify", "")
weechat.hook_signal("weechat_highlight", "notify", "")
return weechat.WEECHAT_RC_OK
if __name__ == "__main__":
main()
|
...
def notify(data, signal, signal_data):
message = signal_data
if message[0] is "[":
message = "\\%s" % message
elif message[0] is "-":
message = "\\%s" % message
command = ("terminal-notifier -message %s -title WeeChat -sound Hero"
% pipes.quote(message))
exit_code = os.system(command)
...
|
96780184daeb63ea5eb5fa3229e32bc6b4968ba6
|
meterbus/telegram_ack.py
|
meterbus/telegram_ack.py
|
from .exceptions import MBusFrameDecodeError, MBusFrameCRCError, FrameMismatch
class TelegramACK(object):
@staticmethod
def parse(data):
if data is None:
raise MBusFrameDecodeError("Data is None")
if data is not None and len(data) < 1:
raise MBusFrameDecodeError("Invalid M-Bus length")
if data[0] != 0xE5:
raise FrameMismatch()
return TelegramACK()
def __init__(self, dbuf=None):
self.type = 0xE5
self.base_size = 1
|
from .exceptions import MBusFrameDecodeError, MBusFrameCRCError, FrameMismatch
class TelegramACK(object):
@staticmethod
def parse(data):
if data is None:
raise MBusFrameDecodeError("Data is None")
if data is not None and len(data) < 1:
raise MBusFrameDecodeError("Invalid M-Bus length")
if data[0] != 0xE5:
raise FrameMismatch()
return TelegramACK()
def __init__(self, dbuf=None):
self.type = 0xE5
self.base_size = 1
def __len__(self):
return 1
def __iter__(self):
yield 0xE5
|
Support for writing this frame to serial port
|
Support for writing this frame to serial port
|
Python
|
bsd-3-clause
|
ganehag/pyMeterBus
|
from .exceptions import MBusFrameDecodeError, MBusFrameCRCError, FrameMismatch
class TelegramACK(object):
@staticmethod
def parse(data):
if data is None:
raise MBusFrameDecodeError("Data is None")
if data is not None and len(data) < 1:
raise MBusFrameDecodeError("Invalid M-Bus length")
if data[0] != 0xE5:
raise FrameMismatch()
return TelegramACK()
def __init__(self, dbuf=None):
self.type = 0xE5
self.base_size = 1
+ def __len__(self):
+ return 1
+
+ def __iter__(self):
+ yield 0xE5
+
|
Support for writing this frame to serial port
|
## Code Before:
from .exceptions import MBusFrameDecodeError, MBusFrameCRCError, FrameMismatch
class TelegramACK(object):
@staticmethod
def parse(data):
if data is None:
raise MBusFrameDecodeError("Data is None")
if data is not None and len(data) < 1:
raise MBusFrameDecodeError("Invalid M-Bus length")
if data[0] != 0xE5:
raise FrameMismatch()
return TelegramACK()
def __init__(self, dbuf=None):
self.type = 0xE5
self.base_size = 1
## Instruction:
Support for writing this frame to serial port
## Code After:
from .exceptions import MBusFrameDecodeError, MBusFrameCRCError, FrameMismatch
class TelegramACK(object):
@staticmethod
def parse(data):
if data is None:
raise MBusFrameDecodeError("Data is None")
if data is not None and len(data) < 1:
raise MBusFrameDecodeError("Invalid M-Bus length")
if data[0] != 0xE5:
raise FrameMismatch()
return TelegramACK()
def __init__(self, dbuf=None):
self.type = 0xE5
self.base_size = 1
def __len__(self):
return 1
def __iter__(self):
yield 0xE5
|
// ... existing code ...
self.base_size = 1
def __len__(self):
return 1
def __iter__(self):
yield 0xE5
// ... rest of the code ...
|
6bf762b7aeabcb47571fe4d23fe13ae8e4b3ebc3
|
editorsnotes/main/views.py
|
editorsnotes/main/views.py
|
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from models import Term, Reference
@login_required
def index(request):
o = {}
o['term_list'] = Term.objects.all()
return render_to_response('index.html', o)
@login_required
def term(request, slug):
o = {}
o['contact'] = { 'name': settings.ADMINS[0][0],
'email': settings.ADMINS[0][1] }
o['term'] = Term.objects.get(slug=slug)
o['note_list'] = list(o['term'].note_set.filter(type__exact='N'))
o['query_list'] = list(o['term'].note_set.filter(type__exact='Q'))
o['note_dict'] = [ (n, n.references.all()) for n in o['note_list'] ]
o['query_dict'] = [ (q, q.references.all()) for q in o['query_list'] ]
for note in o['note_list'] + o['query_list']:
if ('last_updated' not in o) or (note.last_updated > o['last_updated']):
o['last_updated'] = note.last_updated
o['last_updater'] = note.last_updater.username
o['last_updated_display'] = note.last_updated_display()
return render_to_response('term.html', o)
|
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from models import Term, Reference
@login_required
def index(request):
o = {}
o['term_list'] = Term.objects.all()
return render_to_response('index.html', o)
@login_required
def term(request, slug):
o = {}
o['term'] = get_object_or_404(Term, slug=slug)
o['contact'] = { 'name': settings.ADMINS[0][0],
'email': settings.ADMINS[0][1] }
o['note_list'] = list(o['term'].note_set.filter(type__exact='N'))
o['query_list'] = list(o['term'].note_set.filter(type__exact='Q'))
o['note_dict'] = [ (n, n.references.all()) for n in o['note_list'] ]
o['query_dict'] = [ (q, q.references.all()) for q in o['query_list'] ]
for note in o['note_list'] + o['query_list']:
if ('last_updated' not in o) or (note.last_updated > o['last_updated']):
o['last_updated'] = note.last_updated
o['last_updater'] = note.last_updater.username
o['last_updated_display'] = note.last_updated_display()
return render_to_response('term.html', o)
|
Throw 404 for non-existent terms.
|
Throw 404 for non-existent terms.
|
Python
|
agpl-3.0
|
editorsnotes/editorsnotes,editorsnotes/editorsnotes
|
from django.conf import settings
from django.http import HttpResponse
- from django.shortcuts import render_to_response
+ from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from models import Term, Reference
@login_required
def index(request):
o = {}
o['term_list'] = Term.objects.all()
return render_to_response('index.html', o)
@login_required
def term(request, slug):
o = {}
+ o['term'] = get_object_or_404(Term, slug=slug)
o['contact'] = { 'name': settings.ADMINS[0][0],
'email': settings.ADMINS[0][1] }
- o['term'] = Term.objects.get(slug=slug)
o['note_list'] = list(o['term'].note_set.filter(type__exact='N'))
o['query_list'] = list(o['term'].note_set.filter(type__exact='Q'))
o['note_dict'] = [ (n, n.references.all()) for n in o['note_list'] ]
o['query_dict'] = [ (q, q.references.all()) for q in o['query_list'] ]
for note in o['note_list'] + o['query_list']:
if ('last_updated' not in o) or (note.last_updated > o['last_updated']):
o['last_updated'] = note.last_updated
o['last_updater'] = note.last_updater.username
o['last_updated_display'] = note.last_updated_display()
return render_to_response('term.html', o)
|
Throw 404 for non-existent terms.
|
## Code Before:
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from models import Term, Reference
@login_required
def index(request):
o = {}
o['term_list'] = Term.objects.all()
return render_to_response('index.html', o)
@login_required
def term(request, slug):
o = {}
o['contact'] = { 'name': settings.ADMINS[0][0],
'email': settings.ADMINS[0][1] }
o['term'] = Term.objects.get(slug=slug)
o['note_list'] = list(o['term'].note_set.filter(type__exact='N'))
o['query_list'] = list(o['term'].note_set.filter(type__exact='Q'))
o['note_dict'] = [ (n, n.references.all()) for n in o['note_list'] ]
o['query_dict'] = [ (q, q.references.all()) for q in o['query_list'] ]
for note in o['note_list'] + o['query_list']:
if ('last_updated' not in o) or (note.last_updated > o['last_updated']):
o['last_updated'] = note.last_updated
o['last_updater'] = note.last_updater.username
o['last_updated_display'] = note.last_updated_display()
return render_to_response('term.html', o)
## Instruction:
Throw 404 for non-existent terms.
## Code After:
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
from models import Term, Reference
@login_required
def index(request):
o = {}
o['term_list'] = Term.objects.all()
return render_to_response('index.html', o)
@login_required
def term(request, slug):
o = {}
o['term'] = get_object_or_404(Term, slug=slug)
o['contact'] = { 'name': settings.ADMINS[0][0],
'email': settings.ADMINS[0][1] }
o['note_list'] = list(o['term'].note_set.filter(type__exact='N'))
o['query_list'] = list(o['term'].note_set.filter(type__exact='Q'))
o['note_dict'] = [ (n, n.references.all()) for n in o['note_list'] ]
o['query_dict'] = [ (q, q.references.all()) for q in o['query_list'] ]
for note in o['note_list'] + o['query_list']:
if ('last_updated' not in o) or (note.last_updated > o['last_updated']):
o['last_updated'] = note.last_updated
o['last_updater'] = note.last_updater.username
o['last_updated_display'] = note.last_updated_display()
return render_to_response('term.html', o)
|
# ... existing code ...
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required
# ... modified code ...
o = {}
o['term'] = get_object_or_404(Term, slug=slug)
o['contact'] = { 'name': settings.ADMINS[0][0],
...
'email': settings.ADMINS[0][1] }
o['note_list'] = list(o['term'].note_set.filter(type__exact='N'))
# ... rest of the code ...
|
0ec5aeca33676172f458ec6761282157dcb19635
|
tests/test_set_pref.py
|
tests/test_set_pref.py
|
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)
bible = yvs.shared.get_bible_data(user_prefs['language'])
nose.assert_equal(user_prefs['version'], bible['default_version'])
def test_set_version():
"""should set preferred version"""
new_version = 59
yvs.main('version:{}'.format(new_version))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['version'], new_version)
|
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)
bible = yvs.shared.get_bible_data(user_prefs['language'])
nose.assert_equal(user_prefs['version'], bible['default_version'])
def test_set_version():
"""should set preferred version"""
new_version = 59
yvs.main('version:{}'.format(new_version))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['version'], new_version)
def test_set_search_engine():
"""should set preferred search engine"""
new_search_engine = 'yahoo'
yvs.main('searchEngine:{}'.format(new_search_engine))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['searchEngine'], new_search_engine)
|
Add test for setting preferred search engine
|
Add test for setting preferred search engine
|
Python
|
mit
|
caleb531/youversion-suggest,caleb531/youversion-suggest
|
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)
bible = yvs.shared.get_bible_data(user_prefs['language'])
nose.assert_equal(user_prefs['version'], bible['default_version'])
def test_set_version():
"""should set preferred version"""
new_version = 59
yvs.main('version:{}'.format(new_version))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['version'], new_version)
+
+ def test_set_search_engine():
+ """should set preferred search engine"""
+ new_search_engine = 'yahoo'
+ yvs.main('searchEngine:{}'.format(new_search_engine))
+ user_prefs = yvs.shared.get_user_prefs()
+ nose.assert_equal(user_prefs['searchEngine'], new_search_engine)
+
|
Add test for setting preferred search engine
|
## Code Before:
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)
bible = yvs.shared.get_bible_data(user_prefs['language'])
nose.assert_equal(user_prefs['version'], bible['default_version'])
def test_set_version():
"""should set preferred version"""
new_version = 59
yvs.main('version:{}'.format(new_version))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['version'], new_version)
## Instruction:
Add test for setting preferred search engine
## Code After:
import nose.tools as nose
import yvs.set_pref as yvs
def test_set_language():
"""should set preferred language"""
new_language = 'es'
yvs.main('language:{}'.format(new_language))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['language'], new_language)
bible = yvs.shared.get_bible_data(user_prefs['language'])
nose.assert_equal(user_prefs['version'], bible['default_version'])
def test_set_version():
"""should set preferred version"""
new_version = 59
yvs.main('version:{}'.format(new_version))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['version'], new_version)
def test_set_search_engine():
"""should set preferred search engine"""
new_search_engine = 'yahoo'
yvs.main('searchEngine:{}'.format(new_search_engine))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['searchEngine'], new_search_engine)
|
# ... existing code ...
nose.assert_equal(user_prefs['version'], new_version)
def test_set_search_engine():
"""should set preferred search engine"""
new_search_engine = 'yahoo'
yvs.main('searchEngine:{}'.format(new_search_engine))
user_prefs = yvs.shared.get_user_prefs()
nose.assert_equal(user_prefs['searchEngine'], new_search_engine)
# ... rest of the code ...
|
fc5614c040cccff6411c87ad6cc191f7ec0b6971
|
SoftLayer/CLI/account/bandwidth_pools.py
|
SoftLayer/CLI/account/bandwidth_pools.py
|
"""Displays information about the accounts bandwidth pools"""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.account import AccountManager as AccountManager
from SoftLayer import utils
@click.command()
@environment.pass_env
def cli(env):
"""Displays bandwidth pool information
Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr
"""
manager = AccountManager(env.client)
items = manager.get_bandwidth_pools()
table = formatting.Table([
"Pool Name",
"Region",
"Servers",
"Allocation",
"Current Usage",
"Projected Usage"
], title="Bandwidth Pools")
table.align = 'l'
for item in items:
name = item.get('name')
region = utils.lookup(item, 'locationGroup', 'name')
servers = manager.get_bandwidth_pool_counts(identifier=item.get('id'))
allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0))
current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut'))
projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0))
table.add_row([name, region, servers, allocation, current, projected])
env.fout(table)
|
"""Displays information about the accounts bandwidth pools"""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.account import AccountManager as AccountManager
from SoftLayer import utils
@click.command()
@environment.pass_env
def cli(env):
"""Displays bandwidth pool information
Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr
"""
manager = AccountManager(env.client)
items = manager.get_bandwidth_pools()
table = formatting.Table([
"Id",
"Pool Name",
"Region",
"Servers",
"Allocation",
"Current Usage",
"Projected Usage"
], title="Bandwidth Pools")
table.align = 'l'
for item in items:
id = item.get('id')
name = item.get('name')
region = utils.lookup(item, 'locationGroup', 'name')
servers = manager.get_bandwidth_pool_counts(identifier=item.get('id'))
allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0))
current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut'))
projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0))
table.add_row([id, name, region, servers, allocation, current, projected])
env.fout(table)
|
Add id in the result in the command bandwidth-pools
|
Add id in the result in the command bandwidth-pools
|
Python
|
mit
|
softlayer/softlayer-python,allmightyspiff/softlayer-python
|
"""Displays information about the accounts bandwidth pools"""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.account import AccountManager as AccountManager
from SoftLayer import utils
@click.command()
@environment.pass_env
def cli(env):
"""Displays bandwidth pool information
Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr
"""
manager = AccountManager(env.client)
items = manager.get_bandwidth_pools()
table = formatting.Table([
+ "Id",
"Pool Name",
"Region",
"Servers",
"Allocation",
"Current Usage",
"Projected Usage"
], title="Bandwidth Pools")
table.align = 'l'
-
for item in items:
+ id = item.get('id')
name = item.get('name')
region = utils.lookup(item, 'locationGroup', 'name')
servers = manager.get_bandwidth_pool_counts(identifier=item.get('id'))
allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0))
current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut'))
projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0))
- table.add_row([name, region, servers, allocation, current, projected])
+ table.add_row([id, name, region, servers, allocation, current, projected])
env.fout(table)
|
Add id in the result in the command bandwidth-pools
|
## Code Before:
"""Displays information about the accounts bandwidth pools"""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.account import AccountManager as AccountManager
from SoftLayer import utils
@click.command()
@environment.pass_env
def cli(env):
"""Displays bandwidth pool information
Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr
"""
manager = AccountManager(env.client)
items = manager.get_bandwidth_pools()
table = formatting.Table([
"Pool Name",
"Region",
"Servers",
"Allocation",
"Current Usage",
"Projected Usage"
], title="Bandwidth Pools")
table.align = 'l'
for item in items:
name = item.get('name')
region = utils.lookup(item, 'locationGroup', 'name')
servers = manager.get_bandwidth_pool_counts(identifier=item.get('id'))
allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0))
current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut'))
projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0))
table.add_row([name, region, servers, allocation, current, projected])
env.fout(table)
## Instruction:
Add id in the result in the command bandwidth-pools
## Code After:
"""Displays information about the accounts bandwidth pools"""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.account import AccountManager as AccountManager
from SoftLayer import utils
@click.command()
@environment.pass_env
def cli(env):
"""Displays bandwidth pool information
Similiar to https://cloud.ibm.com/classic/network/bandwidth/vdr
"""
manager = AccountManager(env.client)
items = manager.get_bandwidth_pools()
table = formatting.Table([
"Id",
"Pool Name",
"Region",
"Servers",
"Allocation",
"Current Usage",
"Projected Usage"
], title="Bandwidth Pools")
table.align = 'l'
for item in items:
id = item.get('id')
name = item.get('name')
region = utils.lookup(item, 'locationGroup', 'name')
servers = manager.get_bandwidth_pool_counts(identifier=item.get('id'))
allocation = "{} GB".format(item.get('totalBandwidthAllocated', 0))
current = "{} GB".format(utils.lookup(item, 'billingCyclePublicBandwidthUsage', 'amountOut'))
projected = "{} GB".format(item.get('projectedPublicBandwidthUsage', 0))
table.add_row([id, name, region, servers, allocation, current, projected])
env.fout(table)
|
// ... existing code ...
table = formatting.Table([
"Id",
"Pool Name",
// ... modified code ...
table.align = 'l'
for item in items:
id = item.get('id')
name = item.get('name')
...
table.add_row([id, name, region, servers, allocation, current, projected])
env.fout(table)
// ... rest of the code ...
|
51f6272870e4e72d2364b2c2f660457b5c9286ef
|
doc/sample_code/search_forking_pro.py
|
doc/sample_code/search_forking_pro.py
|
import os
import sys
sys.path.append('./../../')
from pyogi.ki2converter import *
from pyogi.kifu import *
if __name__ == '__main__':
for n in range(0, 50000):
n1 = (n // 10000)
n2 = int(n < 10000)
relpath = '~/data/shogi/2chkifu/{0}000{1}/{2:0>5}.KI2'.format(n1, n2, n)
kifile = os.path.expanduser(relpath)
if not os.path.exists(kifile):
continue
ki2converter = Ki2converter()
ki2converter.from_path(kifile)
csa = ki2converter.to_csa()
kifu = Kifu(csa)
res = kifu.get_forking(['OU', 'HI'])
if res[2] or res[3]:
print(kifu.players)
|
import os
import sys
import pandas as pd
sys.path.append('./../../')
from pyogi.ki2converter import *
from pyogi.kifu import *
if __name__ == '__main__':
res_table = []
for n in range(0, 50000):
n1 = (n // 10000)
n2 = int(n < 10000)
relpath = '~/data/shogi/2chkifu/{0}000{1}/{2:0>5}.KI2'.format(n1, n2, n)
kifile = os.path.expanduser(relpath)
if not os.path.exists(kifile):
continue
ki2converter = Ki2converter()
ki2converter.from_path(kifile)
csa = ki2converter.to_csa()
if not csa:
continue
kifu = Kifu(csa)
res = kifu.get_forking(['OU', 'HI'])
if res[2] or res[3]:
print(kifu.players)
# Output
# 1. sente forked | gote forked
# 2. (sente won & sente forked) | (gote won & gote forked)
res_table.append(
[res[2] != [] or res[3] != [],
(kifu.sente_win and res[2]!=[]) or
((not kifu.sente_win) and res[3]!=[])])
df = pd.DataFrame(res_table, columns=['fork', 'fork&win'])
pd.crosstab(df.loc[:, 'fork'], df.loc[:, 'fork&win'])
|
Add sum up part using pd.crosstab
|
Add sum up part using pd.crosstab
|
Python
|
mit
|
tosh1ki/pyogi,tosh1ki/pyogi
|
import os
import sys
+ import pandas as pd
sys.path.append('./../../')
from pyogi.ki2converter import *
from pyogi.kifu import *
if __name__ == '__main__':
+
+ res_table = []
for n in range(0, 50000):
n1 = (n // 10000)
n2 = int(n < 10000)
relpath = '~/data/shogi/2chkifu/{0}000{1}/{2:0>5}.KI2'.format(n1, n2, n)
kifile = os.path.expanduser(relpath)
if not os.path.exists(kifile):
continue
ki2converter = Ki2converter()
ki2converter.from_path(kifile)
csa = ki2converter.to_csa()
+ if not csa:
+ continue
kifu = Kifu(csa)
res = kifu.get_forking(['OU', 'HI'])
if res[2] or res[3]:
print(kifu.players)
+ # Output
+ # 1. sente forked | gote forked
+ # 2. (sente won & sente forked) | (gote won & gote forked)
+ res_table.append(
+ [res[2] != [] or res[3] != [],
+ (kifu.sente_win and res[2]!=[]) or
+ ((not kifu.sente_win) and res[3]!=[])])
+
+
+
+ df = pd.DataFrame(res_table, columns=['fork', 'fork&win'])
+ pd.crosstab(df.loc[:, 'fork'], df.loc[:, 'fork&win'])
+
|
Add sum up part using pd.crosstab
|
## Code Before:
import os
import sys
sys.path.append('./../../')
from pyogi.ki2converter import *
from pyogi.kifu import *
if __name__ == '__main__':
for n in range(0, 50000):
n1 = (n // 10000)
n2 = int(n < 10000)
relpath = '~/data/shogi/2chkifu/{0}000{1}/{2:0>5}.KI2'.format(n1, n2, n)
kifile = os.path.expanduser(relpath)
if not os.path.exists(kifile):
continue
ki2converter = Ki2converter()
ki2converter.from_path(kifile)
csa = ki2converter.to_csa()
kifu = Kifu(csa)
res = kifu.get_forking(['OU', 'HI'])
if res[2] or res[3]:
print(kifu.players)
## Instruction:
Add sum up part using pd.crosstab
## Code After:
import os
import sys
import pandas as pd
sys.path.append('./../../')
from pyogi.ki2converter import *
from pyogi.kifu import *
if __name__ == '__main__':
res_table = []
for n in range(0, 50000):
n1 = (n // 10000)
n2 = int(n < 10000)
relpath = '~/data/shogi/2chkifu/{0}000{1}/{2:0>5}.KI2'.format(n1, n2, n)
kifile = os.path.expanduser(relpath)
if not os.path.exists(kifile):
continue
ki2converter = Ki2converter()
ki2converter.from_path(kifile)
csa = ki2converter.to_csa()
if not csa:
continue
kifu = Kifu(csa)
res = kifu.get_forking(['OU', 'HI'])
if res[2] or res[3]:
print(kifu.players)
# Output
# 1. sente forked | gote forked
# 2. (sente won & sente forked) | (gote won & gote forked)
res_table.append(
[res[2] != [] or res[3] != [],
(kifu.sente_win and res[2]!=[]) or
((not kifu.sente_win) and res[3]!=[])])
df = pd.DataFrame(res_table, columns=['fork', 'fork&win'])
pd.crosstab(df.loc[:, 'fork'], df.loc[:, 'fork&win'])
|
...
import sys
import pandas as pd
sys.path.append('./../../')
...
if __name__ == '__main__':
res_table = []
...
if not csa:
continue
...
print(kifu.players)
# Output
# 1. sente forked | gote forked
# 2. (sente won & sente forked) | (gote won & gote forked)
res_table.append(
[res[2] != [] or res[3] != [],
(kifu.sente_win and res[2]!=[]) or
((not kifu.sente_win) and res[3]!=[])])
df = pd.DataFrame(res_table, columns=['fork', 'fork&win'])
pd.crosstab(df.loc[:, 'fork'], df.loc[:, 'fork&win'])
...
|
9177ffa65ac50026078610193b67fdfd6ac8358b
|
tests/app/utils/test_pagination.py
|
tests/app/utils/test_pagination.py
|
from app.utils.pagination import generate_next_dict, generate_previous_dict
def test_generate_previous_dict(client):
ret = generate_previous_dict('main.view_jobs', 'foo', 2, {})
assert 'page=1' in ret['url']
assert ret['title'] == 'Previous page'
assert ret['label'] == 'page 1'
def test_generate_next_dict(client):
ret = generate_next_dict('main.view_jobs', 'foo', 2, {})
assert 'page=3' in ret['url']
assert ret['title'] == 'Next page'
assert ret['label'] == 'page 3'
def test_generate_previous_next_dict_adds_other_url_args(client):
ret = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'})
assert 'notifications/blah' in ret['url']
|
from app.utils.pagination import generate_next_dict, generate_previous_dict
def test_generate_previous_dict(client):
result = generate_previous_dict('main.view_jobs', 'foo', 2, {})
assert 'page=1' in result['url']
assert result['title'] == 'Previous page'
assert result['label'] == 'page 1'
def test_generate_next_dict(client):
result = generate_next_dict('main.view_jobs', 'foo', 2, {})
assert 'page=3' in result['url']
assert result['title'] == 'Next page'
assert result['label'] == 'page 3'
def test_generate_previous_next_dict_adds_other_url_args(client):
result = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'})
assert 'notifications/blah' in result['url']
|
Clarify variable name in pagination tests
|
Clarify variable name in pagination tests
We should avoid using abbreviations, as they aren't universally
understood i.e. they're not worth the small saving in typing.
|
Python
|
mit
|
alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
|
from app.utils.pagination import generate_next_dict, generate_previous_dict
def test_generate_previous_dict(client):
- ret = generate_previous_dict('main.view_jobs', 'foo', 2, {})
+ result = generate_previous_dict('main.view_jobs', 'foo', 2, {})
- assert 'page=1' in ret['url']
+ assert 'page=1' in result['url']
- assert ret['title'] == 'Previous page'
+ assert result['title'] == 'Previous page'
- assert ret['label'] == 'page 1'
+ assert result['label'] == 'page 1'
def test_generate_next_dict(client):
- ret = generate_next_dict('main.view_jobs', 'foo', 2, {})
+ result = generate_next_dict('main.view_jobs', 'foo', 2, {})
- assert 'page=3' in ret['url']
+ assert 'page=3' in result['url']
- assert ret['title'] == 'Next page'
+ assert result['title'] == 'Next page'
- assert ret['label'] == 'page 3'
+ assert result['label'] == 'page 3'
def test_generate_previous_next_dict_adds_other_url_args(client):
- ret = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'})
+ result = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'})
- assert 'notifications/blah' in ret['url']
+ assert 'notifications/blah' in result['url']
|
Clarify variable name in pagination tests
|
## Code Before:
from app.utils.pagination import generate_next_dict, generate_previous_dict
def test_generate_previous_dict(client):
ret = generate_previous_dict('main.view_jobs', 'foo', 2, {})
assert 'page=1' in ret['url']
assert ret['title'] == 'Previous page'
assert ret['label'] == 'page 1'
def test_generate_next_dict(client):
ret = generate_next_dict('main.view_jobs', 'foo', 2, {})
assert 'page=3' in ret['url']
assert ret['title'] == 'Next page'
assert ret['label'] == 'page 3'
def test_generate_previous_next_dict_adds_other_url_args(client):
ret = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'})
assert 'notifications/blah' in ret['url']
## Instruction:
Clarify variable name in pagination tests
## Code After:
from app.utils.pagination import generate_next_dict, generate_previous_dict
def test_generate_previous_dict(client):
result = generate_previous_dict('main.view_jobs', 'foo', 2, {})
assert 'page=1' in result['url']
assert result['title'] == 'Previous page'
assert result['label'] == 'page 1'
def test_generate_next_dict(client):
result = generate_next_dict('main.view_jobs', 'foo', 2, {})
assert 'page=3' in result['url']
assert result['title'] == 'Next page'
assert result['label'] == 'page 3'
def test_generate_previous_next_dict_adds_other_url_args(client):
result = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'})
assert 'notifications/blah' in result['url']
|
# ... existing code ...
def test_generate_previous_dict(client):
result = generate_previous_dict('main.view_jobs', 'foo', 2, {})
assert 'page=1' in result['url']
assert result['title'] == 'Previous page'
assert result['label'] == 'page 1'
# ... modified code ...
def test_generate_next_dict(client):
result = generate_next_dict('main.view_jobs', 'foo', 2, {})
assert 'page=3' in result['url']
assert result['title'] == 'Next page'
assert result['label'] == 'page 3'
...
def test_generate_previous_next_dict_adds_other_url_args(client):
result = generate_next_dict('main.view_notifications', 'foo', 2, {'message_type': 'blah'})
assert 'notifications/blah' in result['url']
# ... rest of the code ...
|
13e70f822e3cf96a0604bb4ce6ed46dbe2dcf376
|
zsl/application/initializers/__init__.py
|
zsl/application/initializers/__init__.py
|
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
|
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer
|
FIX import order - cyclic dependencies
|
FIX import order - cyclic dependencies
|
Python
|
mit
|
AtteqCom/zsl,AtteqCom/zsl
|
-
- from .logger_initializer import LoggerInitializer
- from .unittest_initializer import UnitTestInitializer
- from .library_initializer import LibraryInitializer
- from .database_initializer import DatabaseInitializer
- from .application_initializer import ApplicationInitializer
- from .service_initializer import ServiceInitializer
- from .cache_initializer import CacheInitializer
- from .context_initializer import ContextInitializer
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
+
+ from .logger_initializer import LoggerInitializer
+ from .unittest_initializer import UnitTestInitializer
+ from .library_initializer import LibraryInitializer
+ from .database_initializer import DatabaseInitializer
+ from .application_initializer import ApplicationInitializer
+ from .service_initializer import ServiceInitializer
+ from .cache_initializer import CacheInitializer
+ from .context_initializer import ContextInitializer
|
FIX import order - cyclic dependencies
|
## Code Before:
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
## Instruction:
FIX import order - cyclic dependencies
## Code After:
injection_views = []
injection_modules = []
def injection_view(f):
"""
Adds the view to the list of Injector-enabled views to add to the Flask app.
:param callable f: The decorated view function.
"""
injection_views.append(f)
return f
def injection_module(f):
"""
Adds the module to the list of injection enabled modules. The decorated function is then called in the
initialization phase and can create and initialize the object which will be able to be injected.
:param callable f: The decorated initializing function.
"""
injection_modules.append(f)
return f
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer
|
# ... existing code ...
# ... modified code ...
return f
from .logger_initializer import LoggerInitializer
from .unittest_initializer import UnitTestInitializer
from .library_initializer import LibraryInitializer
from .database_initializer import DatabaseInitializer
from .application_initializer import ApplicationInitializer
from .service_initializer import ServiceInitializer
from .cache_initializer import CacheInitializer
from .context_initializer import ContextInitializer
# ... rest of the code ...
|
b3f206d9b8cbde42ce2def6d8b9d8c1d90abfeeb
|
pyexperiment/utils/interactive.py
|
pyexperiment/utils/interactive.py
|
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyexperiment import state
from pyexperiment import conf
def embed_interactive(**kwargs):
"""Embed an interactive terminal into a running python process
"""
if not 'state' in kwargs:
kwargs['state'] = state
if not 'conf' in kwargs:
kwargs['conf'] = conf
try:
import IPython
ipython_config = IPython.Config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
if IPython.__version__ == '1.2.1':
IPython.embed(config=ipython_config,
banner1='',
user_ns=kwargs)
else:
IPython.embed(config=ipython_config,
banner1='',
local_ns=kwargs)
except ImportError:
import readline # pylint: disable=unused-variable
import code
code.InteractiveConsole(kwargs).interact()
|
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyexperiment import state
from pyexperiment import conf
def embed_interactive(**kwargs):
"""Embed an interactive terminal into a running python process
"""
if 'state' not in kwargs:
kwargs['state'] = state
if 'conf' not in kwargs:
kwargs['conf'] = conf
try:
import IPython
ipython_config = IPython.Config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
if IPython.__version__ == '1.2.1':
IPython.embed(config=ipython_config,
banner1='',
user_ns=kwargs)
else:
IPython.embed(config=ipython_config,
banner1='',
local_ns=kwargs)
except ImportError:
import readline # pylint: disable=unused-variable
import code
code.InteractiveConsole(kwargs).interact()
|
Fix style: not foo in [] => foo not in
|
Fix style: not foo in [] => foo not in
|
Python
|
mit
|
duerrp/pyexperiment,kinverarity1/pyexperiment,DeercoderResearch/pyexperiment,shaunstanislaus/pyexperiment,shaunstanislaus/pyexperiment,kinverarity1/pyexperiment,kinverarity1/pyexperiment,duerrp/pyexperiment,DeercoderResearch/pyexperiment,shaunstanislaus/pyexperiment,duerrp/pyexperiment,DeercoderResearch/pyexperiment,DeercoderResearch/pyexperiment,kinverarity1/pyexperiment,shaunstanislaus/pyexperiment
|
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyexperiment import state
from pyexperiment import conf
def embed_interactive(**kwargs):
"""Embed an interactive terminal into a running python process
"""
- if not 'state' in kwargs:
+ if 'state' not in kwargs:
kwargs['state'] = state
- if not 'conf' in kwargs:
+ if 'conf' not in kwargs:
kwargs['conf'] = conf
try:
import IPython
ipython_config = IPython.Config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
if IPython.__version__ == '1.2.1':
IPython.embed(config=ipython_config,
banner1='',
user_ns=kwargs)
else:
IPython.embed(config=ipython_config,
banner1='',
local_ns=kwargs)
except ImportError:
import readline # pylint: disable=unused-variable
import code
code.InteractiveConsole(kwargs).interact()
|
Fix style: not foo in [] => foo not in
|
## Code Before:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyexperiment import state
from pyexperiment import conf
def embed_interactive(**kwargs):
"""Embed an interactive terminal into a running python process
"""
if not 'state' in kwargs:
kwargs['state'] = state
if not 'conf' in kwargs:
kwargs['conf'] = conf
try:
import IPython
ipython_config = IPython.Config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
if IPython.__version__ == '1.2.1':
IPython.embed(config=ipython_config,
banner1='',
user_ns=kwargs)
else:
IPython.embed(config=ipython_config,
banner1='',
local_ns=kwargs)
except ImportError:
import readline # pylint: disable=unused-variable
import code
code.InteractiveConsole(kwargs).interact()
## Instruction:
Fix style: not foo in [] => foo not in
## Code After:
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from pyexperiment import state
from pyexperiment import conf
def embed_interactive(**kwargs):
"""Embed an interactive terminal into a running python process
"""
if 'state' not in kwargs:
kwargs['state'] = state
if 'conf' not in kwargs:
kwargs['conf'] = conf
try:
import IPython
ipython_config = IPython.Config()
ipython_config.TerminalInteractiveShell.confirm_exit = False
if IPython.__version__ == '1.2.1':
IPython.embed(config=ipython_config,
banner1='',
user_ns=kwargs)
else:
IPython.embed(config=ipython_config,
banner1='',
local_ns=kwargs)
except ImportError:
import readline # pylint: disable=unused-variable
import code
code.InteractiveConsole(kwargs).interact()
|
// ... existing code ...
"""
if 'state' not in kwargs:
kwargs['state'] = state
if 'conf' not in kwargs:
kwargs['conf'] = conf
// ... rest of the code ...
|
795b661962915221ddab186b66523896316b2a79
|
jobs/jobs/items.py
|
jobs/jobs/items.py
|
import scrapy
def single_item_serializer(value):
# values are nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fist value when serializing
return value[0]
class JobsItem(scrapy.Item):
title = scrapy.Field(serializer=single_item_serializer)
company = scrapy.Field(serializer=single_item_serializer)
url = scrapy.Field(serializer=single_item_serializer)
posted = scrapy.Field(serializer=single_item_serializer)
deadline = scrapy.Field(serializer=single_item_serializer)
views = scrapy.Field(serializer=int)
|
import scrapy
def single_item_serializer(value):
# values are sometimes nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fist value when serializing
if isinstance(value, (list, tuple)):
return value[0]
return value
class JobsItem(scrapy.Item):
title = scrapy.Field(serializer=single_item_serializer)
company = scrapy.Field(serializer=single_item_serializer)
url = scrapy.Field(serializer=single_item_serializer)
posted = scrapy.Field(serializer=single_item_serializer)
deadline = scrapy.Field(serializer=single_item_serializer)
views = scrapy.Field(serializer=int)
|
Fix rendering of alfred.is data to json file
|
Fix rendering of alfred.is data to json file
|
Python
|
apache-2.0
|
multiplechoice/workplace
|
import scrapy
def single_item_serializer(value):
- # values are nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
+ # values are sometimes nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fist value when serializing
+ if isinstance(value, (list, tuple)):
+ return value[0]
- return value[0]
+ return value
class JobsItem(scrapy.Item):
title = scrapy.Field(serializer=single_item_serializer)
company = scrapy.Field(serializer=single_item_serializer)
url = scrapy.Field(serializer=single_item_serializer)
posted = scrapy.Field(serializer=single_item_serializer)
deadline = scrapy.Field(serializer=single_item_serializer)
views = scrapy.Field(serializer=int)
|
Fix rendering of alfred.is data to json file
|
## Code Before:
import scrapy
def single_item_serializer(value):
# values are nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fist value when serializing
return value[0]
class JobsItem(scrapy.Item):
title = scrapy.Field(serializer=single_item_serializer)
company = scrapy.Field(serializer=single_item_serializer)
url = scrapy.Field(serializer=single_item_serializer)
posted = scrapy.Field(serializer=single_item_serializer)
deadline = scrapy.Field(serializer=single_item_serializer)
views = scrapy.Field(serializer=int)
## Instruction:
Fix rendering of alfred.is data to json file
## Code After:
import scrapy
def single_item_serializer(value):
# values are sometimes nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fist value when serializing
if isinstance(value, (list, tuple)):
return value[0]
return value
class JobsItem(scrapy.Item):
title = scrapy.Field(serializer=single_item_serializer)
company = scrapy.Field(serializer=single_item_serializer)
url = scrapy.Field(serializer=single_item_serializer)
posted = scrapy.Field(serializer=single_item_serializer)
deadline = scrapy.Field(serializer=single_item_serializer)
views = scrapy.Field(serializer=int)
|
// ... existing code ...
def single_item_serializer(value):
# values are sometimes nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fist value when serializing
if isinstance(value, (list, tuple)):
return value[0]
return value
// ... rest of the code ...
|
2685b94838c8ec7ce31da60bc6f28953152c788a
|
pixelmap/pixelmap.py
|
pixelmap/pixelmap.py
|
from pixel import Pixel
class Pixelmap:
def __init__(self, width, height):
"""Pixelmap constructor
:param width: Width of map in pixels.
:param height: Height of map in pixels.
"""
self.width = width
self.height = height
self.map_matrix = [[0]*self.width for _ in range(self.height)]
for row in range(self.height):
for col in range(self.width):
self.map_matrix[row][col] = Pixel()
def __str__(self):
"""Human readable pixelmap description.
Pretty much just the matrix.
:return: Description of pixelmap.
"""
return str('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in self.map_matrix]))
def __repr__(self):
"""Internal representation
Just use str for now.
"""
return self.__str__()
|
from .pixel import Pixel
class Pixelmap:
def __init__(self, cols, rows, default_val=None):
"""Pixelmap constructor
:param cols: Width of map in pixels.
:param rows: Height of map in pixels.
:param default_val: Default value for pixels.
"""
assert cols >= 0, 'Invalid Pixelmap width'
assert rows >= 0, 'Invalid Pixelmap height'
self.cols = cols
self.rows = rows
self.map_matrix = [[0]*self.cols for _ in range(self.rows)]
for row in range(self.rows):
for col in range(self.cols):
self.map_matrix[row][col] = Pixel(default_val)
def num_cols(self):
return self.cols
def num_rows(self):
return self.rows
def __str__(self):
"""Human readable pixelmap description.
Pretty much just the matrix.
:return: Description of pixelmap.
"""
return str('\n'.join([''.join(['{:6}'.format(str(item)) for item in row]) for row in self.map_matrix]))
|
Add default value for matrix and methods to get columns and rows.
|
Add default value for matrix and methods to get columns and rows.
|
Python
|
mit
|
yebra06/pixelmap
|
- from pixel import Pixel
+ from .pixel import Pixel
class Pixelmap:
- def __init__(self, width, height):
+ def __init__(self, cols, rows, default_val=None):
"""Pixelmap constructor
- :param width: Width of map in pixels.
+ :param cols: Width of map in pixels.
- :param height: Height of map in pixels.
+ :param rows: Height of map in pixels.
+ :param default_val: Default value for pixels.
"""
- self.width = width
- self.height = height
+ assert cols >= 0, 'Invalid Pixelmap width'
+ assert rows >= 0, 'Invalid Pixelmap height'
+ self.cols = cols
+ self.rows = rows
- self.map_matrix = [[0]*self.width for _ in range(self.height)]
+ self.map_matrix = [[0]*self.cols for _ in range(self.rows)]
- for row in range(self.height):
+ for row in range(self.rows):
- for col in range(self.width):
+ for col in range(self.cols):
- self.map_matrix[row][col] = Pixel()
+ self.map_matrix[row][col] = Pixel(default_val)
+
+ def num_cols(self):
+ return self.cols
+
+ def num_rows(self):
+ return self.rows
def __str__(self):
"""Human readable pixelmap description.
Pretty much just the matrix.
:return: Description of pixelmap.
"""
- return str('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in self.map_matrix]))
+ return str('\n'.join([''.join(['{:6}'.format(str(item)) for item in row]) for row in self.map_matrix]))
- def __repr__(self):
- """Internal representation
-
- Just use str for now.
- """
- return self.__str__()
-
|
Add default value for matrix and methods to get columns and rows.
|
## Code Before:
from pixel import Pixel
class Pixelmap:
def __init__(self, width, height):
"""Pixelmap constructor
:param width: Width of map in pixels.
:param height: Height of map in pixels.
"""
self.width = width
self.height = height
self.map_matrix = [[0]*self.width for _ in range(self.height)]
for row in range(self.height):
for col in range(self.width):
self.map_matrix[row][col] = Pixel()
def __str__(self):
"""Human readable pixelmap description.
Pretty much just the matrix.
:return: Description of pixelmap.
"""
return str('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in self.map_matrix]))
def __repr__(self):
"""Internal representation
Just use str for now.
"""
return self.__str__()
## Instruction:
Add default value for matrix and methods to get columns and rows.
## Code After:
from .pixel import Pixel
class Pixelmap:
def __init__(self, cols, rows, default_val=None):
"""Pixelmap constructor
:param cols: Width of map in pixels.
:param rows: Height of map in pixels.
:param default_val: Default value for pixels.
"""
assert cols >= 0, 'Invalid Pixelmap width'
assert rows >= 0, 'Invalid Pixelmap height'
self.cols = cols
self.rows = rows
self.map_matrix = [[0]*self.cols for _ in range(self.rows)]
for row in range(self.rows):
for col in range(self.cols):
self.map_matrix[row][col] = Pixel(default_val)
def num_cols(self):
return self.cols
def num_rows(self):
return self.rows
def __str__(self):
"""Human readable pixelmap description.
Pretty much just the matrix.
:return: Description of pixelmap.
"""
return str('\n'.join([''.join(['{:6}'.format(str(item)) for item in row]) for row in self.map_matrix]))
|
// ... existing code ...
from .pixel import Pixel
// ... modified code ...
def __init__(self, cols, rows, default_val=None):
"""Pixelmap constructor
...
:param cols: Width of map in pixels.
:param rows: Height of map in pixels.
:param default_val: Default value for pixels.
"""
assert cols >= 0, 'Invalid Pixelmap width'
assert rows >= 0, 'Invalid Pixelmap height'
self.cols = cols
self.rows = rows
self.map_matrix = [[0]*self.cols for _ in range(self.rows)]
for row in range(self.rows):
for col in range(self.cols):
self.map_matrix[row][col] = Pixel(default_val)
def num_cols(self):
return self.cols
def num_rows(self):
return self.rows
...
"""
return str('\n'.join([''.join(['{:6}'.format(str(item)) for item in row]) for row in self.map_matrix]))
// ... rest of the code ...
|
83617b63544ccb0336a8afc2726fd2e8dfacb69f
|
avalon/nuke/workio.py
|
avalon/nuke/workio.py
|
"""Host API required Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.root().modified()
def save_file(filepath):
path = filepath.replace("\\", "/")
nuke.scriptSaveAs(path)
nuke.Root()["name"].setValue(path)
nuke.Root()["project_directory"].setValue(os.path.dirname(path))
nuke.Root().setModified(False)
def open_file(filepath):
filepath = filepath.replace("\\", "/")
# To remain in the same window, we have to clear the script and read
# in the contents of the workfile.
nuke.scriptClear()
nuke.scriptReadFile(filepath)
nuke.Root()["name"].setValue(filepath)
nuke.Root()["project_directory"].setValue(os.path.dirname(filepath))
nuke.Root().setModified(False)
return True
def current_file():
current_file = nuke.root().name()
# Unsaved current file
if current_file == 'Root':
return None
return os.path.normpath(current_file).replace("\\", "/")
def work_root(session):
if scene_dir:
path = os.path.join(work_dir, scene_dir)
else:
path = work_dir
return os.path.normpath(path).replace("\\", "/")
|
"""Host API required Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.root().modified()
def save_file(filepath):
path = filepath.replace("\\", "/")
nuke.scriptSaveAs(path)
nuke.Root()["name"].setValue(path)
nuke.Root()["project_directory"].setValue(os.path.dirname(path))
nuke.Root().setModified(False)
def open_file(filepath):
filepath = filepath.replace("\\", "/")
# To remain in the same window, we have to clear the script and read
# in the contents of the workfile.
nuke.scriptClear()
nuke.scriptReadFile(filepath)
nuke.Root()["name"].setValue(filepath)
nuke.Root()["project_directory"].setValue(os.path.dirname(filepath))
nuke.Root().setModified(False)
return True
def current_file():
current_file = nuke.root().name()
# Unsaved current file
if current_file == 'Root':
return None
return os.path.normpath(current_file).replace("\\", "/")
def work_root(session):
work_dir = session["AVALON_WORKDIR"]
scene_dir = session.get("AVALON_SCENEDIR")
if scene_dir:
path = os.path.join(work_dir, scene_dir)
else:
path = work_dir
return os.path.normpath(path).replace("\\", "/")
|
Fix undefined work_dir and scene_dir variables
|
Fix undefined work_dir and scene_dir variables
|
Python
|
mit
|
mindbender-studio/core,mindbender-studio/core,getavalon/core,getavalon/core
|
"""Host API required Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.root().modified()
def save_file(filepath):
path = filepath.replace("\\", "/")
nuke.scriptSaveAs(path)
nuke.Root()["name"].setValue(path)
nuke.Root()["project_directory"].setValue(os.path.dirname(path))
nuke.Root().setModified(False)
def open_file(filepath):
filepath = filepath.replace("\\", "/")
# To remain in the same window, we have to clear the script and read
# in the contents of the workfile.
nuke.scriptClear()
nuke.scriptReadFile(filepath)
nuke.Root()["name"].setValue(filepath)
nuke.Root()["project_directory"].setValue(os.path.dirname(filepath))
nuke.Root().setModified(False)
return True
def current_file():
current_file = nuke.root().name()
# Unsaved current file
if current_file == 'Root':
return None
return os.path.normpath(current_file).replace("\\", "/")
def work_root(session):
+ work_dir = session["AVALON_WORKDIR"]
+ scene_dir = session.get("AVALON_SCENEDIR")
if scene_dir:
path = os.path.join(work_dir, scene_dir)
else:
path = work_dir
return os.path.normpath(path).replace("\\", "/")
|
Fix undefined work_dir and scene_dir variables
|
## Code Before:
"""Host API required Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.root().modified()
def save_file(filepath):
path = filepath.replace("\\", "/")
nuke.scriptSaveAs(path)
nuke.Root()["name"].setValue(path)
nuke.Root()["project_directory"].setValue(os.path.dirname(path))
nuke.Root().setModified(False)
def open_file(filepath):
filepath = filepath.replace("\\", "/")
# To remain in the same window, we have to clear the script and read
# in the contents of the workfile.
nuke.scriptClear()
nuke.scriptReadFile(filepath)
nuke.Root()["name"].setValue(filepath)
nuke.Root()["project_directory"].setValue(os.path.dirname(filepath))
nuke.Root().setModified(False)
return True
def current_file():
current_file = nuke.root().name()
# Unsaved current file
if current_file == 'Root':
return None
return os.path.normpath(current_file).replace("\\", "/")
def work_root(session):
if scene_dir:
path = os.path.join(work_dir, scene_dir)
else:
path = work_dir
return os.path.normpath(path).replace("\\", "/")
## Instruction:
Fix undefined work_dir and scene_dir variables
## Code After:
"""Host API required Work Files tool"""
import os
import nuke
def file_extensions():
return [".nk"]
def has_unsaved_changes():
return nuke.root().modified()
def save_file(filepath):
path = filepath.replace("\\", "/")
nuke.scriptSaveAs(path)
nuke.Root()["name"].setValue(path)
nuke.Root()["project_directory"].setValue(os.path.dirname(path))
nuke.Root().setModified(False)
def open_file(filepath):
filepath = filepath.replace("\\", "/")
# To remain in the same window, we have to clear the script and read
# in the contents of the workfile.
nuke.scriptClear()
nuke.scriptReadFile(filepath)
nuke.Root()["name"].setValue(filepath)
nuke.Root()["project_directory"].setValue(os.path.dirname(filepath))
nuke.Root().setModified(False)
return True
def current_file():
current_file = nuke.root().name()
# Unsaved current file
if current_file == 'Root':
return None
return os.path.normpath(current_file).replace("\\", "/")
def work_root(session):
work_dir = session["AVALON_WORKDIR"]
scene_dir = session.get("AVALON_SCENEDIR")
if scene_dir:
path = os.path.join(work_dir, scene_dir)
else:
path = work_dir
return os.path.normpath(path).replace("\\", "/")
|
// ... existing code ...
work_dir = session["AVALON_WORKDIR"]
scene_dir = session.get("AVALON_SCENEDIR")
if scene_dir:
// ... rest of the code ...
|
0fb5a8b5caa99b82845712703bf53f2348227f78
|
examples/string_expansion.py
|
examples/string_expansion.py
|
"""Example of expanding and unexpanding string variables in entry fields."""
from __future__ import print_function
import bibpy
import os
def get_path_for(path):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
def print_entries(entries):
print(os.linesep.join(map(str, entries)))
print()
if __name__ == '__main__':
filename = get_path_for('../tests/data/string_variables.bib')
entries, strings = bibpy.read_file(filename, format='relaxed')[:2]
print("* String entries:")
print_entries(strings)
print("* Without string expansion:")
print_entries(entries)
# Expand string variables in-place
bibpy.expand_strings(entries, strings, ignore_duplicates=False)
print("* With string expansion:")
print_entries(entries)
# Unexpand string variables in-place
bibpy.unexpand_strings(entries, strings, ignore_duplicates=False)
print("* And without string expansion again:")
print_entries(entries)
|
"""Example of expanding and unexpanding string variables in entry fields."""
from __future__ import print_function
import bibpy
import os
def get_path_for(path):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
def print_entries(entries):
print(os.linesep.join(map(str, entries)))
print()
if __name__ == '__main__':
filename = get_path_for('../tests/data/string_variables.bib')
result = bibpy.read_file(filename, format='relaxed')
entries, strings = result.entries, result.strings
print("* String entries:")
print_entries(strings)
print("* Without string expansion:")
print_entries(entries)
# Expand string variables in-place
bibpy.expand_strings(entries, strings, ignore_duplicates=False)
print("* With string expansion:")
print_entries(entries)
# Unexpand string variables in-place
bibpy.unexpand_strings(entries, strings, ignore_duplicates=False)
print("* And without string expansion again:")
print_entries(entries)
|
Fix ordering in string expansion example
|
Fix ordering in string expansion example
|
Python
|
mit
|
MisanthropicBit/bibpy,MisanthropicBit/bibpy
|
"""Example of expanding and unexpanding string variables in entry fields."""
from __future__ import print_function
import bibpy
import os
def get_path_for(path):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
def print_entries(entries):
print(os.linesep.join(map(str, entries)))
print()
if __name__ == '__main__':
filename = get_path_for('../tests/data/string_variables.bib')
- entries, strings = bibpy.read_file(filename, format='relaxed')[:2]
+ result = bibpy.read_file(filename, format='relaxed')
+ entries, strings = result.entries, result.strings
print("* String entries:")
print_entries(strings)
print("* Without string expansion:")
print_entries(entries)
# Expand string variables in-place
bibpy.expand_strings(entries, strings, ignore_duplicates=False)
print("* With string expansion:")
print_entries(entries)
# Unexpand string variables in-place
bibpy.unexpand_strings(entries, strings, ignore_duplicates=False)
print("* And without string expansion again:")
print_entries(entries)
|
Fix ordering in string expansion example
|
## Code Before:
"""Example of expanding and unexpanding string variables in entry fields."""
from __future__ import print_function
import bibpy
import os
def get_path_for(path):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
def print_entries(entries):
print(os.linesep.join(map(str, entries)))
print()
if __name__ == '__main__':
filename = get_path_for('../tests/data/string_variables.bib')
entries, strings = bibpy.read_file(filename, format='relaxed')[:2]
print("* String entries:")
print_entries(strings)
print("* Without string expansion:")
print_entries(entries)
# Expand string variables in-place
bibpy.expand_strings(entries, strings, ignore_duplicates=False)
print("* With string expansion:")
print_entries(entries)
# Unexpand string variables in-place
bibpy.unexpand_strings(entries, strings, ignore_duplicates=False)
print("* And without string expansion again:")
print_entries(entries)
## Instruction:
Fix ordering in string expansion example
## Code After:
"""Example of expanding and unexpanding string variables in entry fields."""
from __future__ import print_function
import bibpy
import os
def get_path_for(path):
return os.path.join(os.path.dirname(os.path.abspath(__file__)), path)
def print_entries(entries):
print(os.linesep.join(map(str, entries)))
print()
if __name__ == '__main__':
filename = get_path_for('../tests/data/string_variables.bib')
result = bibpy.read_file(filename, format='relaxed')
entries, strings = result.entries, result.strings
print("* String entries:")
print_entries(strings)
print("* Without string expansion:")
print_entries(entries)
# Expand string variables in-place
bibpy.expand_strings(entries, strings, ignore_duplicates=False)
print("* With string expansion:")
print_entries(entries)
# Unexpand string variables in-place
bibpy.unexpand_strings(entries, strings, ignore_duplicates=False)
print("* And without string expansion again:")
print_entries(entries)
|
// ... existing code ...
filename = get_path_for('../tests/data/string_variables.bib')
result = bibpy.read_file(filename, format='relaxed')
entries, strings = result.entries, result.strings
// ... rest of the code ...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.