commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
0
2.94k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
444
message
stringlengths
16
3.45k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43.2k
prompt
stringlengths
17
4.58k
response
stringlengths
1
4.43k
prompt_tagged
stringlengths
58
4.62k
response_tagged
stringlengths
1
4.43k
text
stringlengths
132
7.29k
text_tagged
stringlengths
173
7.33k
86971c0aef3a470adf73f13b95aad67590725b3a
LC-Parser/problem.py
LC-Parser/problem.py
from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() if args.tree is not None: return args.tree else: return None def main(): s = Solution() t = TreeGenerator(parse_args()) #print <<!paste your method name here!>> print s.<<!paste your method here!>> if __name__ == "__main__": main()
from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree1', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree2', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() return args def main(): s = Solution() args = parse_args() if args.tree is not None: t = TreeGenerator(args.tree) if args.tree1 is not None: t1 = TreeGenerator(args.tree1) if args.tree2 is not None: t2 = TreeGenerator(args.tree2) print <<!paste your method name here!>> if __name__ == "__main__": main()
Add support for multiple trees imput
Add support for multiple trees imput
Python
bsd-3-clause
fabriziodemaria/LeetCode-Tree-Parser
from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() if args.tree is not None: return args.tree else: return None def main(): s = Solution() t = TreeGenerator(parse_args()) #print <<!paste your method name here!>> print s.<<!paste your method here!>> if __name__ == "__main__": main() Add support for multiple trees imput
from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree1', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree2', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() return args def main(): s = Solution() args = parse_args() if args.tree is not None: t = TreeGenerator(args.tree) if args.tree1 is not None: t1 = TreeGenerator(args.tree1) if args.tree2 is not None: t2 = TreeGenerator(args.tree2) print <<!paste your method name here!>> if __name__ == "__main__": main()
<commit_before>from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() if args.tree is not None: return args.tree else: return None def main(): s = Solution() t = TreeGenerator(parse_args()) #print <<!paste your method name here!>> print s.<<!paste your method here!>> if __name__ == "__main__": main() <commit_msg>Add support for multiple trees imput<commit_after>
from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree1', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree2', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() return args def main(): s = Solution() args = parse_args() if args.tree is not None: t = TreeGenerator(args.tree) if args.tree1 is not None: t1 = TreeGenerator(args.tree1) if args.tree2 is not None: t2 = TreeGenerator(args.tree2) print <<!paste your method name here!>> if __name__ == "__main__": main()
from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() if args.tree is not None: return args.tree else: return None def main(): s = Solution() t = TreeGenerator(parse_args()) #print <<!paste your method name here!>> print s.<<!paste your method here!>> if __name__ == "__main__": main() Add support for multiple trees imputfrom lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree1', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree2', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() return args def main(): s = Solution() args = parse_args() if args.tree is not None: t = TreeGenerator(args.tree) if args.tree1 is not None: t1 = TreeGenerator(args.tree1) if args.tree2 is not None: t2 = TreeGenerator(args.tree2) print <<!paste your method name here!>> if __name__ == "__main__": main()
<commit_before>from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() if args.tree is not None: return args.tree else: return None def main(): s = Solution() t = TreeGenerator(parse_args()) #print <<!paste your method name here!>> print s.<<!paste your method here!>> if __name__ == "__main__": main() <commit_msg>Add support for multiple trees imput<commit_after>from lcparser import * import pdb """ Usage: 1) Paste the code under Solution(object) line 2) Paste the method called by LeetCode in the corresponding line you find the "main" method 3) Insert "pdb.set_trace()" wherever in your code to enable debugging 4) From the shell: <python problem.py --tree [1,2,3...]> Note: --tree is optional and you can still use the debugging tool even for exercises that don't reqiure tree structures. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): <<!paste your code here!>> def parse_args(): import argparse import itertools import sys parser = argparse.ArgumentParser(description='Paste your code in this module and start debugging!') parser.add_argument('--tree', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree1', action="store", help='Paste the LeetCode string representing the Tree structure') parser.add_argument('--tree2', action="store", help='Paste the LeetCode string representing the Tree structure') args = parser.parse_args() return args def main(): s = Solution() args = parse_args() if args.tree is not None: t = TreeGenerator(args.tree) if args.tree1 is not None: t1 = TreeGenerator(args.tree1) if args.tree2 is not None: t2 = TreeGenerator(args.tree2) print <<!paste your method name here!>> if __name__ == "__main__": main()
cef4c09d59bb5666565cf6d7e7453fc6eb87316d
circuits/app/dropprivileges.py
circuits/app/dropprivileges.py
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
Allow to set umask in DropPrivileges
Allow to set umask in DropPrivileges
Python
mit
eriol/circuits,nizox/circuits,eriol/circuits,eriol/circuits
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister() Allow to set umask in DropPrivileges
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
<commit_before>from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister() <commit_msg>Allow to set umask in DropPrivileges<commit_after>
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister() Allow to set umask in DropPrivilegesfrom pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
<commit_before>from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister() <commit_msg>Allow to set umask in DropPrivileges<commit_after>from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
897dd874a34ddfc164ea7dbd4bfd5eaffd02aabd
tests/QtUiTools/bug_376.py
tests/QtUiTools/bug_376.py
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assertEqual(type(result.child_object), QtGui.QFrame) if __name__ == '__main__': unittest.main()
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.child_object, QtGui.QFrame)) if __name__ == '__main__': unittest.main()
Replace type() comparison with isinstance.
Replace type() comparison with isinstance. type() comparison won't work due to weakproxy. Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org> Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org> Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbossa.org>
Python
lgpl-2.1
gbaty/pyside2,enthought/pyside,RobinD42/pyside,pankajp/pyside,M4rtinK/pyside-android,PySide/PySide,BadSingleton/pyside2,M4rtinK/pyside-bb10,IronManMark20/pyside2,M4rtinK/pyside-android,BadSingleton/pyside2,pankajp/pyside,PySide/PySide,pankajp/pyside,IronManMark20/pyside2,gbaty/pyside2,enthought/pyside,RobinD42/pyside,BadSingleton/pyside2,enthought/pyside,M4rtinK/pyside-bb10,qtproject/pyside-pyside,gbaty/pyside2,M4rtinK/pyside-bb10,PySide/PySide,PySide/PySide,IronManMark20/pyside2,BadSingleton/pyside2,qtproject/pyside-pyside,qtproject/pyside-pyside,RobinD42/pyside,M4rtinK/pyside-bb10,qtproject/pyside-pyside,IronManMark20/pyside2,pankajp/pyside,gbaty/pyside2,enthought/pyside,RobinD42/pyside,enthought/pyside,RobinD42/pyside,enthought/pyside,M4rtinK/pyside-android,M4rtinK/pyside-android,pankajp/pyside,PySide/PySide,M4rtinK/pyside-bb10,M4rtinK/pyside-android,IronManMark20/pyside2,BadSingleton/pyside2,M4rtinK/pyside-android,M4rtinK/pyside-bb10,gbaty/pyside2,qtproject/pyside-pyside,enthought/pyside,RobinD42/pyside,RobinD42/pyside
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assertEqual(type(result.child_object), QtGui.QFrame) if __name__ == '__main__': unittest.main() Replace type() comparison with isinstance. type() comparison won't work due to weakproxy. Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org> Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org> Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbossa.org>
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.child_object, QtGui.QFrame)) if __name__ == '__main__': unittest.main()
<commit_before>import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assertEqual(type(result.child_object), QtGui.QFrame) if __name__ == '__main__': unittest.main() <commit_msg>Replace type() comparison with isinstance. type() comparison won't work due to weakproxy. Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org> Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org> Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbossa.org><commit_after>
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.child_object, QtGui.QFrame)) if __name__ == '__main__': unittest.main()
import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assertEqual(type(result.child_object), QtGui.QFrame) if __name__ == '__main__': unittest.main() Replace type() comparison with isinstance. type() comparison won't work due to weakproxy. Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org> Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org> Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbossa.org>import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.child_object, QtGui.QFrame)) if __name__ == '__main__': unittest.main()
<commit_before>import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assertEqual(type(result.child_object), QtGui.QFrame) if __name__ == '__main__': unittest.main() <commit_msg>Replace type() comparison with isinstance. type() comparison won't work due to weakproxy. Reviewer: Luciano Wolf <c353ae890f0e6de8473e43011f009ccd38a3c452@openbossa.org> Reviewer: Hugo Lima <e250cbdf6b5a11059e9d944a6e5e9282be80d14c@openbossa.org> Reviewer: Renato Filho <16af9705e5a16d85aed275f2f9e8171326ec17f6@openbossa.org><commit_after>import unittest import os from helper import UsesQApplication from PySide import QtCore, QtGui from PySide.QtUiTools import QUiLoader class BugTest(UsesQApplication): def testCase(self): w = QtGui.QWidget() loader = QUiLoader() filePath = os.path.join(os.path.dirname(__file__), 'test.ui') result = loader.load(filePath, w) self.assert_(isinstance(result.child_object, QtGui.QFrame)) if __name__ == '__main__': unittest.main()
adddfdb946ab45a186535ab4dcfc8848cf914dc0
allmychanges/validators.py
allmychanges/validators.py
import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value)
import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value)
Allow feed, rss, and atom prefixes in URL validator.
Allow feed, rss, and atom prefixes in URL validator.
Python
bsd-2-clause
AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com,AllMyChanges/allmychanges.com
import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value) Allow feed, rss, and atom prefixes in URL validator.
import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value)
<commit_before>import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value) <commit_msg>Allow feed, rss, and atom prefixes in URL validator.<commit_after>
import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value)
import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value) Allow feed, rss, and atom prefixes in URL validator.import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value)
<commit_before>import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value) <commit_msg>Allow feed, rss, and atom prefixes in URL validator.<commit_after>import re from django.core import validators class URLValidator(validators.URLValidator): """Custom url validator to include git urls and urls with http+ like prefixes """ regex = re.compile( r'^(?:(?:(?:(?:http|git|hg|rechttp|feed|rss|atom)\+)?' # optional http+ or git+ or hg+ r'(?:http|ftp|)s?|git)://|git@)' # http:// or https:// or git:// or git@ r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|' # ...or ipv4 r'\[?[A-F0-9]*:[A-F0-9:]+\]?)' # ...or ipv6 r'(?::\d+)?' # optional port r'(?:/?|[/?:]\S+)' # slash or question mark or just : followed by uri r'$', re.IGNORECASE) def __call__(self, value): super(URLValidator, self).__call__(value)
11e158cae1e6c5d910f640303abc181550fb2127
members/models.py
members/models.py
from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.count()
from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.all()
Make attended_meetings return lists of meetings
Make attended_meetings return lists of meetings
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.count() Make attended_meetings return lists of meetings
from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.all()
<commit_before>from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.count() <commit_msg>Make attended_meetings return lists of meetings<commit_after>
from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.all()
from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.count() Make attended_meetings return lists of meetingsfrom django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.all()
<commit_before>from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.count() <commit_msg>Make attended_meetings return lists of meetings<commit_after>from django.db import models from django.contrib.auth.models import AbstractUser class Member(AbstractUser): faculty_number = models.CharField(max_length=8) def __unicode__(self): return self.username def attended_meetings(self): return self.protocols.all()
d13c08315eb24194ff845fbbe8a801dbb1b680cb
chrome/test/nacl_test_injection/buildbot_nacl_integration.py
chrome/test/nacl_test_injection/buildbot_nacl_integration.py
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on some linux trybots. if (sys.platform in ['linux', 'linux2'] and 'hardy64-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
Revert 85807 - Enabled nacl_integration tests on the Linux bots.
Revert 85807 - Enabled nacl_integration tests on the Linux bots. BUG= none TEST= none Review URL: http://codereview.chromium.org/7038025 TBR=ncbray@google.com Review URL: http://codereview.chromium.org/7042025 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@85846 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,littlstar/chromium.src,rogerwang/chromium,littlstar/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,dushu1203/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,keishi/chromium,keishi/chromium,markYoungH/chromium.src,patrickm/chromium.src,keishi/chromium,hgl888/chromium-crosswalk-efl,dednal/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,dushu1203/chromium.src,Just-D/chromium-1,timopulkkinen/BubbleFish,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,robclark/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,chuan9/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,rogerwang/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,robclark/chromium,Just-D/chromium-1,dednal/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,keishi/chromium,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,Jonekee/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,keishi/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,anirudhSK/chromium,M4sse/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,Chilledheart/chromium,hujiajie/pa-chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,dednal/chromium.src,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,dednal/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,patrickm/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,zcbenz/cefode-chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,rogerwang/chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,zcbenz/cefode-chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,Jonekee/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,dushu1203/chromium.src,dednal/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,ltilve/chromium,nacl-webkit/chrome_deps,dushu1203/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,keishi/chromium,Fireblend/chromium-crosswalk,rogerwang/chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,robclark/chromium,ltilve/chromium,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,anirudhSK/chromium,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,dednal/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,robclark/chromium,jaruba/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,M4sse/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,robclark/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,M4sse/chromium.src,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,keishi/chromium,rogerwang/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Jonekee/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,rogerwang/chromium,ltilve/chromium,dednal/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,jaruba/chromium.src,hujiajie/pa-chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,keishi/chromium,rogerwang/chromium,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,ltilve/chromium,patrickm/chromium.src,rogerwang/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,robclark/chromium,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,Jonekee/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,keishi/chromium,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,robclark/chromium,rogerwang/chromium,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,anirudhSK/chromium,ondra-novak/chromium.src,patrickm/chromium.src,anirudhSK/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,keishi/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main() Revert 85807 - Enabled nacl_integration tests on the Linux bots. BUG= none TEST= none Review URL: http://codereview.chromium.org/7038025 TBR=ncbray@google.com Review URL: http://codereview.chromium.org/7042025 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@85846 0039d316-1c4b-4281-b951-d872f2087c98
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on some linux trybots. if (sys.platform in ['linux', 'linux2'] and 'hardy64-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
<commit_before>#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main() <commit_msg>Revert 85807 - Enabled nacl_integration tests on the Linux bots. BUG= none TEST= none Review URL: http://codereview.chromium.org/7038025 TBR=ncbray@google.com Review URL: http://codereview.chromium.org/7042025 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@85846 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on some linux trybots. if (sys.platform in ['linux', 'linux2'] and 'hardy64-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main() Revert 85807 - Enabled nacl_integration tests on the Linux bots. BUG= none TEST= none Review URL: http://codereview.chromium.org/7038025 TBR=ncbray@google.com Review URL: http://codereview.chromium.org/7042025 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@85846 0039d316-1c4b-4281-b951-d872f2087c98#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on some linux trybots. if (sys.platform in ['linux', 'linux2'] and 'hardy64-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
<commit_before>#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main() <commit_msg>Revert 85807 - Enabled nacl_integration tests on the Linux bots. BUG= none TEST= none Review URL: http://codereview.chromium.org/7038025 TBR=ncbray@google.com Review URL: http://codereview.chromium.org/7042025 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@85846 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import subprocess import sys def Main(): pwd = os.environ.get('PWD', '') # TODO(ncbray): figure out why this is failing on windows and enable. if (sys.platform in ['win32', 'cygwin'] and 'xp-nacl-chrome' not in pwd and 'win64-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on mac and re-enable. if (sys.platform == 'darwin' and 'mac-nacl-chrome' not in pwd): return # TODO(ncbray): figure out why this is failing on some linux trybots. if (sys.platform in ['linux', 'linux2'] and 'hardy64-nacl-chrome' not in pwd): return script_dir = os.path.dirname(os.path.abspath(__file__)) test_dir = os.path.dirname(script_dir) chrome_dir = os.path.dirname(test_dir) src_dir = os.path.dirname(chrome_dir) nacl_integration_script = os.path.join( src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py') cmd = [sys.executable, nacl_integration_script] + sys.argv[1:] print cmd subprocess.check_call(cmd) if __name__ == '__main__': Main()
7e5240967e926c47301318df4833dd9af1fe9c7c
tests/test_address_book.py
tests/test_address_book.py
from unittest import TestCase class AddressBookTestCase(TestCase): def test_add_person(self): person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) self.address_book.add_person(person) self.assertIn(person, self.address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
from unittest import TestCase from address_book import AddressBook, Person class AddressBookTestCase(TestCase): def test_add_person(self): address_book = AddressBook() person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) address_book.add_person(person) self.assertIn(person, address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
Update person addition test to create address book inside test func + import needed classes from the package
Update person addition test to create address book inside test func + import needed classes from the package
Python
mit
dizpers/python-address-book-assignment
from unittest import TestCase class AddressBookTestCase(TestCase): def test_add_person(self): person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) self.address_book.add_person(person) self.assertIn(person, self.address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjjUpdate person addition test to create address book inside test func + import needed classes from the package
from unittest import TestCase from address_book import AddressBook, Person class AddressBookTestCase(TestCase): def test_add_person(self): address_book = AddressBook() person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) address_book.add_person(person) self.assertIn(person, address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
<commit_before>from unittest import TestCase class AddressBookTestCase(TestCase): def test_add_person(self): person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) self.address_book.add_person(person) self.assertIn(person, self.address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj<commit_msg>Update person addition test to create address book inside test func + import needed classes from the package<commit_after>
from unittest import TestCase from address_book import AddressBook, Person class AddressBookTestCase(TestCase): def test_add_person(self): address_book = AddressBook() person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) address_book.add_person(person) self.assertIn(person, address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
from unittest import TestCase class AddressBookTestCase(TestCase): def test_add_person(self): person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) self.address_book.add_person(person) self.assertIn(person, self.address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjjUpdate person addition test to create address book inside test func + import needed classes from the packagefrom unittest import TestCase from address_book import AddressBook, Person class AddressBookTestCase(TestCase): def test_add_person(self): address_book = AddressBook() person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) address_book.add_person(person) self.assertIn(person, address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
<commit_before>from unittest import TestCase class AddressBookTestCase(TestCase): def test_add_person(self): person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) self.address_book.add_person(person) self.assertIn(person, self.address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj<commit_msg>Update person addition test to create address book inside test func + import needed classes from the package<commit_after>from unittest import TestCase from address_book import AddressBook, Person class AddressBookTestCase(TestCase): def test_add_person(self): address_book = AddressBook() person = Person( 'John', 'Doe', ['Russian Federation, Kemerovo region, Kemerovo, Kirova street 23, apt. 42'], ['+79834772053'] ) address_book.add_person(person) self.assertIn(person, address_book) def test_add_group(self): pass def test_find_person_by_first_name(self): pass def test_find_person_by_last_name(self): pass def test_find_person_by_email(self): passjjj
03d695a5ed30dcdfb3941a105318a059b9bd9768
sorting/insertion_sort.py
sorting/insertion_sort.py
#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort(d) e = [3, 2] print insertion_sort(e)
#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a def insertion_sort2(a): for i in range(0, len(a)): for j in reversed(range(1, i+1)): if a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] else: break return a def insertion_sort3(a): for i in range(0, len(a)): j = i while j > 0 and a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] j-=1 return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort3(d) e = [2, 3] print insertion_sort3(e)
Add two other implement of insertion sort
Add two other implement of insertion sort
Python
mit
hongta/practice-python,hongta/practice-python
#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort(d) e = [3, 2] print insertion_sort(e) Add two other implement of insertion sort
#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a def insertion_sort2(a): for i in range(0, len(a)): for j in reversed(range(1, i+1)): if a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] else: break return a def insertion_sort3(a): for i in range(0, len(a)): j = i while j > 0 and a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] j-=1 return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort3(d) e = [2, 3] print insertion_sort3(e)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort(d) e = [3, 2] print insertion_sort(e) <commit_msg>Add two other implement of insertion sort<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a def insertion_sort2(a): for i in range(0, len(a)): for j in reversed(range(1, i+1)): if a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] else: break return a def insertion_sort3(a): for i in range(0, len(a)): j = i while j > 0 and a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] j-=1 return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort3(d) e = [2, 3] print insertion_sort3(e)
#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort(d) e = [3, 2] print insertion_sort(e) Add two other implement of insertion sort#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a def insertion_sort2(a): for i in range(0, len(a)): for j in reversed(range(1, i+1)): if a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] else: break return a def insertion_sort3(a): for i in range(0, len(a)): j = i while j > 0 and a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] j-=1 return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort3(d) e = [2, 3] print insertion_sort3(e)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort(d) e = [3, 2] print insertion_sort(e) <commit_msg>Add two other implement of insertion sort<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- def insertion_sort(a): for i in range(1, len(a)): current_val = a[i] j = i while j > 0 and a[j-1] > current_val: a[j] = a[j-1] j -= 1 a[j] = current_val return a def insertion_sort2(a): for i in range(0, len(a)): for j in reversed(range(1, i+1)): if a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] else: break return a def insertion_sort3(a): for i in range(0, len(a)): j = i while j > 0 and a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] j-=1 return a if __name__ == '__main__': d = [34,2,24,12, 45,33,9,99] print insertion_sort3(d) e = [2, 3] print insertion_sort3(e)
7a651446413b2391284fd13f7df9b9c6ae1b78a7
InvenTree/key.py
InvenTree/key.py
# Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50)) if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as key: key.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
# Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
Use random.choice instead of random.choices
Use random.choice instead of random.choices - Allows compatibility with python3.5
Python
mit
SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree
# Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50)) if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as key: key.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))Use random.choice instead of random.choices - Allows compatibility with python3.5
# Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
<commit_before># Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50)) if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as key: key.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))<commit_msg>Use random.choice instead of random.choices - Allows compatibility with python3.5<commit_after>
# Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
# Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50)) if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as key: key.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))Use random.choice instead of random.choices - Allows compatibility with python3.5# Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
<commit_before># Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): return ''.join(random.choices(string.digits + string.ascii_letters + string.punctuation, k=50)) if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as key: key.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))<commit_msg>Use random.choice instead of random.choices - Allows compatibility with python3.5<commit_after># Generate a SECRET_KEY file import random import string import os fn = 'secret_key.txt' def generate_key(): options = string.digits + string.ascii_letters + string.punctuation key = ''.join([random.choice(options) for i in range(50)]) return key if __name__ == '__main__': # Ensure key file is placed in same directory as this script path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(path, fn) with open(key_file, 'w') as kf: kf.write(generate_key()) print('Generated SECRET_KEY to {f}'.format(f=key_file))
9b9e1872bf3281249a318c69b18e60cd6995ad2d
elmo/elmo/urls.py
elmo/elmo/urls.py
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ]
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
Add support for Django debug sidebar.
Add support for Django debug sidebar.
Python
mit
StephenSwat/eve_lunar_mining_organiser,StephenSwat/eve_lunar_mining_organiser
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] Add support for Django debug sidebar.
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
<commit_before>"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] <commit_msg>Add support for Django debug sidebar.<commit_after>
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] Add support for Django debug sidebar."""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
<commit_before>"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] <commit_msg>Add support for Django debug sidebar.<commit_after>"""elmo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.views.generic import TemplateView from django.contrib.auth.views import logout urlpatterns = [ url(r'^landing/$', TemplateView.as_view(template_name='landing.html'), name='landing'), url(r'^admin/', admin.site.urls), url(r'^auth/logout/$', logout, {'next_page': '/'}, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^', include('moon_tracker.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns
3965aa953fb8a68140531c1f3ab112082b75f343
netconsole.py
netconsole.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = ('localhost', 6666) max_size = 4096 print "Liscen to port 6666" server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread HOST = '' # Symbolic name meaning all available interfaces PORT = 6666 # Default netconsole client IN Port def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = (HOST, PORT) max_size = 4096 print "Liscen to port %d" % PORT server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close()
Set Netconsole default listen port to 6666
Set Netconsole default listen port to 6666 according to linux/Documentation/networking/netconsole.txt
Python
mit
danielk1031/netconsole
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = ('localhost', 6666) max_size = 4096 print "Liscen to port 6666" server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close() Set Netconsole default listen port to 6666 according to linux/Documentation/networking/netconsole.txt
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread HOST = '' # Symbolic name meaning all available interfaces PORT = 6666 # Default netconsole client IN Port def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = (HOST, PORT) max_size = 4096 print "Liscen to port %d" % PORT server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = ('localhost', 6666) max_size = 4096 print "Liscen to port 6666" server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close() <commit_msg>Set Netconsole default listen port to 6666 according to linux/Documentation/networking/netconsole.txt<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread HOST = '' # Symbolic name meaning all available interfaces PORT = 6666 # Default netconsole client IN Port def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = (HOST, PORT) max_size = 4096 print "Liscen to port %d" % PORT server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = ('localhost', 6666) max_size = 4096 print "Liscen to port 6666" server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close() Set Netconsole default listen port to 6666 according to linux/Documentation/networking/netconsole.txt#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread HOST = '' # Symbolic name meaning all available interfaces PORT = 6666 # Default netconsole client IN Port def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = (HOST, PORT) max_size = 4096 print "Liscen to port %d" % PORT server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close()
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = ('localhost', 6666) max_size = 4096 print "Liscen to port 6666" server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close() <commit_msg>Set Netconsole default listen port to 6666 according to linux/Documentation/networking/netconsole.txt<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import socket, sys from datetime import datetime from threading import Thread HOST = '' # Symbolic name meaning all available interfaces PORT = 6666 # Default netconsole client IN Port def recv(): global client while True: data, client = server.recvfrom(max_size) sys.stdout.write(data) def send(): while True : server_input = sys.stdin.readline() if server_input == "quit\n" : server.sendto("Leave Netconsole Client.\n", client) break if server_input is not None : server.sendto(server_input, client) if __name__ == "__main__" : server_address = (HOST, PORT) max_size = 4096 print "Liscen to port %d" % PORT server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(server_address) th_recv = Thread(target = recv) th_send = Thread(target = send) th_recv.setDaemon(True) th_send.setDaemon(True) th_recv.start() th_send.start() th_send.join() server.close()
481c57e552b5d52051a6ce34a836f2db1c41d13f
InstagramAPI/src/http/Response/ReelsTrayFeedResponse.py
InstagramAPI/src/http/Response/ReelsTrayFeedResponse.py
from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and len(response['tray']): for tray in response['tray']: items = [] if 'items' in tray and len(tray['items']): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays
from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and isinstance(response['tray'], list): for tray in response['tray']: items = [] if 'items' in tray and isinstance(tray['items'], list): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays
Make sure that tray items is a list This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray'].
Make sure that tray items is a list This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray'].
Python
mit
danleyb2/Instagram-API
from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and len(response['tray']): for tray in response['tray']: items = [] if 'items' in tray and len(tray['items']): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays Make sure that tray items is a list This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray'].
from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and isinstance(response['tray'], list): for tray in response['tray']: items = [] if 'items' in tray and isinstance(tray['items'], list): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays
<commit_before>from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and len(response['tray']): for tray in response['tray']: items = [] if 'items' in tray and len(tray['items']): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays <commit_msg>Make sure that tray items is a list This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray'].<commit_after>
from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and isinstance(response['tray'], list): for tray in response['tray']: items = [] if 'items' in tray and isinstance(tray['items'], list): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays
from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and len(response['tray']): for tray in response['tray']: items = [] if 'items' in tray and len(tray['items']): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays Make sure that tray items is a list This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray'].from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and isinstance(response['tray'], list): for tray in response['tray']: items = [] if 'items' in tray and isinstance(tray['items'], list): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays
<commit_before>from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and len(response['tray']): for tray in response['tray']: items = [] if 'items' in tray and len(tray['items']): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays <commit_msg>Make sure that tray items is a list This fixes an exception when tray['items'] is None. The same conditional check is added for response['tray'].<commit_after>from InstagramAPI.src.http.Response.Objects.Item import Item from InstagramAPI.src.http.Response.Objects.Tray import Tray from .Response import Response class ReelsTrayFeedResponse(Response): def __init__(self, response): self.trays = None if self.STATUS_OK == response['status']: trays = [] if 'tray' in response and isinstance(response['tray'], list): for tray in response['tray']: items = [] if 'items' in tray and isinstance(tray['items'], list): for item in tray['items']: items.append(Item(item)) trays.append(Tray(items, tray['user'], tray['can_reply'], tray['expiring_at'])) self.trays = trays else: self.setMessage(response['message']) self.setStatus(response['status']) def getTrays(self): return self.trays
6e1befa9021494f5a63ccf2943570765d5b4c6e6
SessionManager.py
SessionManager.py
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data())
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if self.is_saveable(window): return True return False @staticmethod def is_saveable(window): return bool(window.views()) or bool(window.project_data())
Make "is_saveable" a staticmethod of SaveSession
Make "is_saveable" a staticmethod of SaveSession
Python
mit
Zeeker/sublime-SessionManager
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data()) Make "is_saveable" a staticmethod of SaveSession
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if self.is_saveable(window): return True return False @staticmethod def is_saveable(window): return bool(window.views()) or bool(window.project_data())
<commit_before>import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data()) <commit_msg>Make "is_saveable" a staticmethod of SaveSession<commit_after>
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if self.is_saveable(window): return True return False @staticmethod def is_saveable(window): return bool(window.views()) or bool(window.project_data())
import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data()) Make "is_saveable" a staticmethod of SaveSessionimport sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if self.is_saveable(window): return True return False @staticmethod def is_saveable(window): return bool(window.views()) or bool(window.project_data())
<commit_before>import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if is_saveable(window): return True return False def is_saveable(window): return bool(window.views()) or bool(window.project_data()) <commit_msg>Make "is_saveable" a staticmethod of SaveSession<commit_after>import sublime import sublime_plugin from datetime import datetime from .modules import messages from .modules import serialize from .modules import settings from .modules.session import Session def plugin_loaded(): settings.load() def error_message(errno): sublime.error_message(messages.error(errno)) class SaveSession(sublime_plugin.ApplicationCommand): def run(self): sublime.active_window().show_input_panel( messages.dialog("session_name"), self.generate_name(), on_done=self.save_session, on_change=None, on_cancel=None ) def generate_name(self): nameformat = settings.get('session_name_dateformat') return datetime.now().strftime(nameformat) def save_session(self, session_name): session = Session.save(session_name, sublime.windows()) try: serialize.dump(session_name, session) except OSError as e: error_message(e.errno) def is_enabled(self): windows = sublime.windows() for window in windows: if self.is_saveable(window): return True return False @staticmethod def is_saveable(window): return bool(window.views()) or bool(window.project_data())
6659fdebbc383d22c3abd303c41dbb0f326c12b1
distarray/tests/test_utils.py
distarray/tests/test_utils.py
import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEquals(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2)
import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEqual(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2)
Replace assertEquals with assertEquals for Py3.
Replace assertEquals with assertEquals for Py3.
Python
bsd-3-clause
RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray
import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEquals(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2) Replace assertEquals with assertEquals for Py3.
import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEqual(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2)
<commit_before>import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEquals(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2) <commit_msg>Replace assertEquals with assertEquals for Py3.<commit_after>
import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEqual(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2)
import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEquals(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2) Replace assertEquals with assertEquals for Py3.import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEqual(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2)
<commit_before>import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEquals(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2) <commit_msg>Replace assertEquals with assertEquals for Py3.<commit_after>import unittest from distarray import utils class TestMultPartitions(unittest.TestCase): """ Test the multiplicative parition code. """ def test_both_methods(self): """ Do the two methods of computing the multiplicative partitions agree? """ for s in [2, 3]: for n in range(2, 512): self.assertEqual(utils.mult_partitions(n, s), utils.create_factors(n, s)) if __name__ == '__main__': unittest.main(verbosity=2)
e90c10093a9948e87008c2cd9411f3abfda00a20
priorityq.py
priorityq.py
from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal."""
from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority=None): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal."""
Set default priority level to None
Set default priority level to None
Python
mit
jonathanstallings/data-structures,jay-tyler/data-structures
from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal.""" Set default priority level to None
from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority=None): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal."""
<commit_before>from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal.""" <commit_msg>Set default priority level to None<commit_after>
from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority=None): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal."""
from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal.""" Set default priority level to Nonefrom __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority=None): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal."""
<commit_before>from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal.""" <commit_msg>Set default priority level to None<commit_after>from __future__ import unicode_literals from functools import total_ordering from binary_heap import BinaryHeap @total_ordering # Will build out the remaining comparison methods class QNode(object): """A class for a queue node.""" def __init__(self, val, priority=None): super(QNode, self).__init__() self.val = val self.priority = priority def __repr__(self): """Print representation of node.""" return "{val}".format(val=self.val) def __eq__(self, other): """Implement this and following two methods with logic to compare priority and value appropiately. """ pass def __lt__(self, other): """Implement in tandem with __eq__.""" pass class PriorityQ(object): """A class for a priority queue. Compose this from BinaryHeap.""" def __init__(self, iterable=()): pass def insert(item): """Insert an item into the queue.""" pass def pop(): """Remove the most importan item from the queue.""" pass def peek(): """Returns the most important item from queue without removal."""
6b4b51a7f8e89e023c933f99aaa3a8329c05e750
salt/runners/ssh.py
salt/runners/ssh.py
# utf-8 ''' A Runner module interface on top of the salt-ssh Python API This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
# -*- coding: utf-8 -*- ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
Fix pylint errors that snuck into 2015.2
Fix pylint errors that snuck into 2015.2
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
# utf-8 ''' A Runner module interface on top of the salt-ssh Python API This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg) Fix pylint errors that snuck into 2015.2
# -*- coding: utf-8 -*- ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
<commit_before># utf-8 ''' A Runner module interface on top of the salt-ssh Python API This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg) <commit_msg>Fix pylint errors that snuck into 2015.2<commit_after>
# -*- coding: utf-8 -*- ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
# utf-8 ''' A Runner module interface on top of the salt-ssh Python API This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg) Fix pylint errors that snuck into 2015.2# -*- coding: utf-8 -*- ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
<commit_before># utf-8 ''' A Runner module interface on top of the salt-ssh Python API This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg) <commit_msg>Fix pylint errors that snuck into 2015.2<commit_after># -*- coding: utf-8 -*- ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun, arg=(), timeout=None, expr_form='glob', kwarg=None): ''' Execute a single command via the salt-ssh subsystem and return all routines at once .. versionaddedd:: 2015.2 A wrapper around the :py:meth:`SSHClient.cmd <salt.client.ssh.client.SSHClient.cmd>` method. ''' client = salt.client.ssh.client.SSHClient(mopts=__opts__) return client.cmd( tgt, fun, arg, timeout, expr_form, kwarg)
82ff9fc32b472acf357166ea823f9e082288e818
scapy/asn1packet.py
scapy/asn1packet.py
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): if self.raw_packet_cache is not None: return self.raw_packet_cache return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
Add cache support for ASN1_Packet()
Add cache support for ASN1_Packet() --HG-- branch : fix-padding-after-pull-request-18
Python
apache-2.0
mytliulei/Scapy,mytliulei/Scapy
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x) Add cache support for ASN1_Packet() --HG-- branch : fix-padding-after-pull-request-18
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): if self.raw_packet_cache is not None: return self.raw_packet_cache return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
<commit_before>## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x) <commit_msg>Add cache support for ASN1_Packet() --HG-- branch : fix-padding-after-pull-request-18<commit_after>
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): if self.raw_packet_cache is not None: return self.raw_packet_cache return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x) Add cache support for ASN1_Packet() --HG-- branch : fix-padding-after-pull-request-18## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): if self.raw_packet_cache is not None: return self.raw_packet_cache return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
<commit_before>## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x) <commit_msg>Add cache support for ASN1_Packet() --HG-- branch : fix-padding-after-pull-request-18<commit_after>## This file is part of Scapy ## See http://www.secdev.org/projects/scapy for more informations ## Copyright (C) Philippe Biondi <phil@secdev.org> ## This program is published under a GPLv2 license """ Packet holding data in Abstract Syntax Notation (ASN.1). """ from packet import * class ASN1_Packet(Packet): ASN1_root = None ASN1_codec = None def init_fields(self): flist = self.ASN1_root.get_fields_list() self.do_init_fields(flist) self.fields_desc = flist def self_build(self): if self.raw_packet_cache is not None: return self.raw_packet_cache return self.ASN1_root.build(self) def do_dissect(self, x): return self.ASN1_root.dissect(self, x)
38be74ac4370ff0f1c30864b037eed3af8cc643f
packagename/__init__.py
packagename/__init__.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import *
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #import sys #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import *
Add missing import in incantation
Add missing import in incantation
Python
bsd-3-clause
alexrudy/Zeeko,alexrudy/Zeeko
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import * Add missing import in incantation
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #import sys #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import *
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import * <commit_msg>Add missing import in incantation<commit_after>
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #import sys #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import *
# Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import * Add missing import in incantation# Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #import sys #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import *
<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import * <commit_msg>Add missing import in incantation<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst # Packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- # Uncomment to enforce Python version check during package import. # This is the same check as the one at the top of setup.py #import sys #class UnsupportedPythonError(Exception): # pass #__minimum_python_version__ = '3.5' #if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))): # raise UnsupportedPythonError("{} does not support Python < {}".format(__package__, __minimum_python_version__)) if not _ASTROPY_SETUP_: # For egg_info test builds to pass, put package imports here. from .example_mod import *
8f5fdcb2d66d013a5f5e888344704d0a1fbfd881
flask_limiter/errors.py
flask_limiter/errors.py
""" errors and exceptions """ from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources if pkg_resources.get_distribution("werkzeug").version < "0.9": # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__()
""" errors and exceptions """ from distutils.version import LooseVersion from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources werkzeug_version = pkg_resources.get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__()
Fix version comparison of Werkzeug.
Fix version comparison of Werkzeug.
Python
mit
alisaifee/flask-limiter,alisaifee/flask-limiter,joshfriend/flask-limiter,joshfriend/flask-limiter
""" errors and exceptions """ from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources if pkg_resources.get_distribution("werkzeug").version < "0.9": # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__() Fix version comparison of Werkzeug.
""" errors and exceptions """ from distutils.version import LooseVersion from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources werkzeug_version = pkg_resources.get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__()
<commit_before>""" errors and exceptions """ from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources if pkg_resources.get_distribution("werkzeug").version < "0.9": # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__() <commit_msg>Fix version comparison of Werkzeug.<commit_after>
""" errors and exceptions """ from distutils.version import LooseVersion from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources werkzeug_version = pkg_resources.get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__()
""" errors and exceptions """ from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources if pkg_resources.get_distribution("werkzeug").version < "0.9": # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__() Fix version comparison of Werkzeug.""" errors and exceptions """ from distutils.version import LooseVersion from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources werkzeug_version = pkg_resources.get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__()
<commit_before>""" errors and exceptions """ from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources if pkg_resources.get_distribution("werkzeug").version < "0.9": # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__() <commit_msg>Fix version comparison of Werkzeug.<commit_after>""" errors and exceptions """ from distutils.version import LooseVersion from werkzeug.exceptions import HTTPException def _patch_werkzeug(): import pkg_resources werkzeug_version = pkg_resources.get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # sorry, for touching your internals :). import werkzeug._internal # pragma: no cover werkzeug._internal.HTTP_STATUS_CODES[429] = 'Too Many Requests' # pragma: no cover _patch_werkzeug() del _patch_werkzeug class RateLimitExceeded(HTTPException): """ exception raised when a rate limit is hit. The exception results in ``abort(429)`` being called. """ code = 429 def __init__(self, limit): self.description = str(limit) super(RateLimitExceeded, self).__init__()
4a597ff48f5fd22ab1c6317e8ab1e65a887da284
dosagelib/__pyinstaller/hook-dosagelib.py
dosagelib/__pyinstaller/hook-dosagelib.py
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib')
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib')
Make sure dosagelib.data is importable
PyInstaller: Make sure dosagelib.data is importable
Python
mit
webcomics/dosage,webcomics/dosage
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib') PyInstaller: Make sure dosagelib.data is importable
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib')
<commit_before># SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib') <commit_msg>PyInstaller: Make sure dosagelib.data is importable<commit_after>
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib')
# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib') PyInstaller: Make sure dosagelib.data is importable# SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib')
<commit_before># SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib') <commit_msg>PyInstaller: Make sure dosagelib.data is importable<commit_after># SPDX-License-Identifier: MIT # Copyright (C) 2016-2022 Tobias Gruetzmacher from PyInstaller.utils.hooks import collect_data_files, collect_submodules, copy_metadata hiddenimports = ['dosagelib.data'] + collect_submodules('dosagelib.plugins') datas = copy_metadata('dosage') + collect_data_files('dosagelib')
f84df81f060746567b611a2071ff1a161fcf3206
generic_links/models.py
generic_links/models.py
# -*- coding: UTF-8 -*- from django import VERSION from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ def get_user_model_fk_ref(): """Get user model depending on Django version.""" ver = VERSION if ver[0] >= 1 and ver[1] >= 5: return settings.AUTH_USER_MODEL else: return 'auth.User' class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model_fk_ref(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
# -*- coding: UTF-8 -*- from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
Make User model compatible with Django 2.x
Make User model compatible with Django 2.x
Python
bsd-3-clause
matagus/django-generic-links,matagus/django-generic-links
# -*- coding: UTF-8 -*- from django import VERSION from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ def get_user_model_fk_ref(): """Get user model depending on Django version.""" ver = VERSION if ver[0] >= 1 and ver[1] >= 5: return settings.AUTH_USER_MODEL else: return 'auth.User' class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model_fk_ref(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url Make User model compatible with Django 2.x
# -*- coding: UTF-8 -*- from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
<commit_before># -*- coding: UTF-8 -*- from django import VERSION from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ def get_user_model_fk_ref(): """Get user model depending on Django version.""" ver = VERSION if ver[0] >= 1 and ver[1] >= 5: return settings.AUTH_USER_MODEL else: return 'auth.User' class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model_fk_ref(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url <commit_msg>Make User model compatible with Django 2.x<commit_after>
# -*- coding: UTF-8 -*- from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
# -*- coding: UTF-8 -*- from django import VERSION from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ def get_user_model_fk_ref(): """Get user model depending on Django version.""" ver = VERSION if ver[0] >= 1 and ver[1] >= 5: return settings.AUTH_USER_MODEL else: return 'auth.User' class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model_fk_ref(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url Make User model compatible with Django 2.x# -*- coding: UTF-8 -*- from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
<commit_before># -*- coding: UTF-8 -*- from django import VERSION from django.conf import settings from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ def get_user_model_fk_ref(): """Get user model depending on Django version.""" ver = VERSION if ver[0] >= 1 and ver[1] >= 5: return settings.AUTH_USER_MODEL else: return 'auth.User' class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model_fk_ref(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url <commit_msg>Make User model compatible with Django 2.x<commit_after># -*- coding: UTF-8 -*- from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import ugettext_lazy as _ class GenericLink(models.Model): """ Relates an object with an url and its data """ content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField(db_index=True) content_object = GenericForeignKey() url = models.URLField() title = models.CharField(max_length=200) description = models.TextField(max_length=1000, null=True, blank=True) user = models.ForeignKey(get_user_model(), null=True, blank=True, on_delete=models.SET_NULL) created_at = models.DateTimeField(auto_now_add=True, db_index=True) is_external = models.BooleanField(default=True, db_index=True) class Meta: ordering = ("-created_at", ) verbose_name = _("Generic Link") verbose_name_plural = _("Generic Links") def __unicode__(self): return self.url
ace25952c3590f2b130b064815c90658f4495cb5
code/marv/marv/app/wsgi.py
code/marv/marv/app/wsgi.py
# -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ['MARV_APPLICATION_ROOT'] import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True)
# -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/' import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True)
Make fetching application root from env less error-prone
[marv] Make fetching application root from env less error-prone
Python
agpl-3.0
ternaris/marv-robotics,ternaris/marv-robotics
# -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ['MARV_APPLICATION_ROOT'] import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True) [marv] Make fetching application root from env less error-prone
# -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/' import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True)
<commit_before># -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ['MARV_APPLICATION_ROOT'] import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True) <commit_msg>[marv] Make fetching application root from env less error-prone<commit_after>
# -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/' import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True)
# -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ['MARV_APPLICATION_ROOT'] import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True) [marv] Make fetching application root from env less error-prone# -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/' import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True)
<commit_before># -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ['MARV_APPLICATION_ROOT'] import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True) <commit_msg>[marv] Make fetching application root from env less error-prone<commit_after># -*- coding: utf-8 -*- # # Copyright 2016 - 2018 Ternaris. # SPDX-License-Identifier: AGPL-3.0-only import os from marv_cli import setup_logging setup_logging(os.environ.get('MARV_LOGLEVEL', 'info')) config = os.environ['MARV_CONFIG'] app_root = os.environ.get('MARV_APPLICATION_ROOT') or '/' import marv.app import marv.site site = marv.site.Site(config) site.load_for_web() application = marv.app.create_app(site, app_root=app_root, checkdb=True)
94a944b01953ed75bfbefbd11ed62ca438cd9200
accounts/tests/test_models.py
accounts/tests/test_models.py
"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated)
"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_user_invalid_without_email(self): """Should raise if the user model requires an email. """ with self.assertRaises(ValidationError): user = USER() user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated)
Add test for unsupplied email for user model
Add test for unsupplied email for user model
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated) Add test for unsupplied email for user model
"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_user_invalid_without_email(self): """Should raise if the user model requires an email. """ with self.assertRaises(ValidationError): user = USER() user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated)
<commit_before>"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated) <commit_msg>Add test for unsupplied email for user model<commit_after>
"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_user_invalid_without_email(self): """Should raise if the user model requires an email. """ with self.assertRaises(ValidationError): user = USER() user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated)
"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated) Add test for unsupplied email for user model"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_user_invalid_without_email(self): """Should raise if the user model requires an email. """ with self.assertRaises(ValidationError): user = USER() user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated)
<commit_before>"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated) <commit_msg>Add test for unsupplied email for user model<commit_after>"""accounts app unittests for models """ from django.test import TestCase from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError USER = get_user_model() TEST_EMAIL = 'newvisitor@example.com' class UserModelTest(TestCase): """Tests for passwordless user model. """ def test_user_valid_with_only_email(self): """Should not raise if the user model is happy with email only. """ user = USER(email=TEST_EMAIL) user.full_clean() def test_user_invalid_without_email(self): """Should raise if the user model requires an email. """ with self.assertRaises(ValidationError): user = USER() user.full_clean() def test_users_are_authenticated(self): """User objects should be authenticated for views/templates. """ user = USER() self.assertTrue(user.is_authenticated)
e52b134704951f4ff66a24e348bd20c5a3e85391
adhocracy4/filters/filters.py
adhocracy4/filters/filters.py
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, query_data, *args, **kwargs): data = query_data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, data, *args, **kwargs): data = data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
Make constructor of DefaultFilterSet compatible
Make constructor of DefaultFilterSet compatible - arguments had different names than FilterSet before
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, query_data, *args, **kwargs): data = query_data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs) Make constructor of DefaultFilterSet compatible - arguments had different names than FilterSet before
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, data, *args, **kwargs): data = data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
<commit_before>import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, query_data, *args, **kwargs): data = query_data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs) <commit_msg>Make constructor of DefaultFilterSet compatible - arguments had different names than FilterSet before<commit_after>
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, data, *args, **kwargs): data = data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, query_data, *args, **kwargs): data = query_data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs) Make constructor of DefaultFilterSet compatible - arguments had different names than FilterSet beforeimport django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, data, *args, **kwargs): data = data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
<commit_before>import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, query_data, *args, **kwargs): data = query_data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs) <commit_msg>Make constructor of DefaultFilterSet compatible - arguments had different names than FilterSet before<commit_after>import django_filters class PagedFilterSet(django_filters.FilterSet): """Removes page parameters from the query when applying filters.""" page_kwarg = 'page' def __init__(self, data, *args, **kwargs): if self.page_kwarg in data: # Create a mutable copy data = data.copy() del data[self.page_kwarg] return super().__init__(data=data, *args, **kwargs) class DefaultsFilterSet(PagedFilterSet): """Extend to define default filter values. Set the defaults attribute. E.g.: defaults = { 'is_archived': 'false' } """ defaults = None def __init__(self, data, *args, **kwargs): data = data.copy() # Set the defaults if they are not manually set yet for key, value in self.defaults.items(): if key not in data: data[key] = value super().__init__(data, *args, **kwargs)
a450d2ead6a8174fe47fdec5557b85cddef759e8
analysis/plot-single-trial.py
analysis/plot-single-trial.py
import climate import lmj.plot import source def main(subject): subj = source.Subject(subject) trial = subj.blocks[0].trials[0] trial.load() ax = lmj.plot.axes(111, projection='3d', aspect='equal') x, y, z = trial.marker('r-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-knee') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-knee') ax.plot(x, z, zs=y) lmj.plot.show() if __name__ == '__main__': climate.call(main)
import climate import lmj.plot import source import plots @climate.annotate( subjects='plot data from these subjects', marker=('plot data for this mocap marker', 'option'), trial_num=('plot data for this trial', 'option', None, int), ) def main(marker='r-fing-index', trial_num=0, *subjects): with plots.space() as ax: for i, subject in enumerate(subjects): subj = source.Subject(subject) for b in subj.blocks: trial = b.trials[trial_num] trial.load() x, y, z = trial.marker(marker) ax.plot(x, z, zs=y, color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
Expand single-trial plot to include multiple subjects.
Expand single-trial plot to include multiple subjects.
Python
mit
lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment
import climate import lmj.plot import source def main(subject): subj = source.Subject(subject) trial = subj.blocks[0].trials[0] trial.load() ax = lmj.plot.axes(111, projection='3d', aspect='equal') x, y, z = trial.marker('r-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-knee') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-knee') ax.plot(x, z, zs=y) lmj.plot.show() if __name__ == '__main__': climate.call(main) Expand single-trial plot to include multiple subjects.
import climate import lmj.plot import source import plots @climate.annotate( subjects='plot data from these subjects', marker=('plot data for this mocap marker', 'option'), trial_num=('plot data for this trial', 'option', None, int), ) def main(marker='r-fing-index', trial_num=0, *subjects): with plots.space() as ax: for i, subject in enumerate(subjects): subj = source.Subject(subject) for b in subj.blocks: trial = b.trials[trial_num] trial.load() x, y, z = trial.marker(marker) ax.plot(x, z, zs=y, color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
<commit_before>import climate import lmj.plot import source def main(subject): subj = source.Subject(subject) trial = subj.blocks[0].trials[0] trial.load() ax = lmj.plot.axes(111, projection='3d', aspect='equal') x, y, z = trial.marker('r-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-knee') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-knee') ax.plot(x, z, zs=y) lmj.plot.show() if __name__ == '__main__': climate.call(main) <commit_msg>Expand single-trial plot to include multiple subjects.<commit_after>
import climate import lmj.plot import source import plots @climate.annotate( subjects='plot data from these subjects', marker=('plot data for this mocap marker', 'option'), trial_num=('plot data for this trial', 'option', None, int), ) def main(marker='r-fing-index', trial_num=0, *subjects): with plots.space() as ax: for i, subject in enumerate(subjects): subj = source.Subject(subject) for b in subj.blocks: trial = b.trials[trial_num] trial.load() x, y, z = trial.marker(marker) ax.plot(x, z, zs=y, color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
import climate import lmj.plot import source def main(subject): subj = source.Subject(subject) trial = subj.blocks[0].trials[0] trial.load() ax = lmj.plot.axes(111, projection='3d', aspect='equal') x, y, z = trial.marker('r-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-knee') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-knee') ax.plot(x, z, zs=y) lmj.plot.show() if __name__ == '__main__': climate.call(main) Expand single-trial plot to include multiple subjects.import climate import lmj.plot import source import plots @climate.annotate( subjects='plot data from these subjects', marker=('plot data for this mocap marker', 'option'), trial_num=('plot data for this trial', 'option', None, int), ) def main(marker='r-fing-index', trial_num=0, *subjects): with plots.space() as ax: for i, subject in enumerate(subjects): subj = source.Subject(subject) for b in subj.blocks: trial = b.trials[trial_num] trial.load() x, y, z = trial.marker(marker) ax.plot(x, z, zs=y, color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
<commit_before>import climate import lmj.plot import source def main(subject): subj = source.Subject(subject) trial = subj.blocks[0].trials[0] trial.load() ax = lmj.plot.axes(111, projection='3d', aspect='equal') x, y, z = trial.marker('r-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-fing-index') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-heel') ax.plot(x, z, zs=y) x, y, z = trial.marker('r-knee') ax.plot(x, z, zs=y) x, y, z = trial.marker('l-knee') ax.plot(x, z, zs=y) lmj.plot.show() if __name__ == '__main__': climate.call(main) <commit_msg>Expand single-trial plot to include multiple subjects.<commit_after>import climate import lmj.plot import source import plots @climate.annotate( subjects='plot data from these subjects', marker=('plot data for this mocap marker', 'option'), trial_num=('plot data for this trial', 'option', None, int), ) def main(marker='r-fing-index', trial_num=0, *subjects): with plots.space() as ax: for i, subject in enumerate(subjects): subj = source.Subject(subject) for b in subj.blocks: trial = b.trials[trial_num] trial.load() x, y, z = trial.marker(marker) ax.plot(x, z, zs=y, color=lmj.plot.COLOR11[i], alpha=0.7) if __name__ == '__main__': climate.call(main)
2b4323c0b19fbdac4efc5735b6c09bcdfa8a83b1
starminder/main/templatetags/url_format.py
starminder/main/templatetags/url_format.py
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link)
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) # nosec
Mark mark_safe as safe :)
Mark mark_safe as safe :)
Python
mit
nkantar/Starminder
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) Mark mark_safe as safe :)
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) # nosec
<commit_before>from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) <commit_msg>Mark mark_safe as safe :)<commit_after>
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) # nosec
from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) Mark mark_safe as safe :)from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) # nosec
<commit_before>from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) <commit_msg>Mark mark_safe as safe :)<commit_after>from django import template from django.utils.safestring import mark_safe register = template.Library() @register.simple_tag def url_format(link_format, url, text, title): if link_format == "markdown": link = f"[{text}]({url} '{title}')" if link_format == "html": link = f"<a href='{url}' title='{title}'>{text}</a>" elif link_format == "text": link = url return mark_safe(link) # nosec
691f2f8c1bf9a5e13c66913dcbb205dfdbba8fa8
tests/core/test_runner/test_yaml_runner.py
tests/core/test_runner/test_yaml_runner.py
from openfisca_core.tools.test_runner import _run_test from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable"
from openfisca_core.tools.test_runner import _run_test, _get_tax_benefit_system from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} def apply_reform(self, path): return Reform(self) class Reform(TaxBenefitSystem): def __init__(self, baseline): self.baseline = baseline class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" class reform_ab(Reform): def apply(self): self.key = self.__class__.__name__ class reform_ba(Reform): def apply(self): self.key = self.__class__.__name__ def test_tax_benefit_systems_with_reform_cache(): baseline = TaxBenefitSystem() extensions = [] ab_tax_benefit_system = _get_tax_benefit_system(baseline, 'ab', extensions) ba_tax_benefit_system = _get_tax_benefit_system(baseline, 'ba', extensions) assert ab_tax_benefit_system != ba_tax_benefit_system
Add unit test for test_runner _get_tax_benefit_system
Add unit test for test_runner _get_tax_benefit_system
Python
agpl-3.0
openfisca/openfisca-core,openfisca/openfisca-core
from openfisca_core.tools.test_runner import _run_test from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" Add unit test for test_runner _get_tax_benefit_system
from openfisca_core.tools.test_runner import _run_test, _get_tax_benefit_system from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} def apply_reform(self, path): return Reform(self) class Reform(TaxBenefitSystem): def __init__(self, baseline): self.baseline = baseline class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" class reform_ab(Reform): def apply(self): self.key = self.__class__.__name__ class reform_ba(Reform): def apply(self): self.key = self.__class__.__name__ def test_tax_benefit_systems_with_reform_cache(): baseline = TaxBenefitSystem() extensions = [] ab_tax_benefit_system = _get_tax_benefit_system(baseline, 'ab', extensions) ba_tax_benefit_system = _get_tax_benefit_system(baseline, 'ba', extensions) assert ab_tax_benefit_system != ba_tax_benefit_system
<commit_before>from openfisca_core.tools.test_runner import _run_test from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" <commit_msg>Add unit test for test_runner _get_tax_benefit_system<commit_after>
from openfisca_core.tools.test_runner import _run_test, _get_tax_benefit_system from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} def apply_reform(self, path): return Reform(self) class Reform(TaxBenefitSystem): def __init__(self, baseline): self.baseline = baseline class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" class reform_ab(Reform): def apply(self): self.key = self.__class__.__name__ class reform_ba(Reform): def apply(self): self.key = self.__class__.__name__ def test_tax_benefit_systems_with_reform_cache(): baseline = TaxBenefitSystem() extensions = [] ab_tax_benefit_system = _get_tax_benefit_system(baseline, 'ab', extensions) ba_tax_benefit_system = _get_tax_benefit_system(baseline, 'ba', extensions) assert ab_tax_benefit_system != ba_tax_benefit_system
from openfisca_core.tools.test_runner import _run_test from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" Add unit test for test_runner _get_tax_benefit_systemfrom openfisca_core.tools.test_runner import _run_test, _get_tax_benefit_system from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} def apply_reform(self, path): return Reform(self) class Reform(TaxBenefitSystem): def __init__(self, baseline): self.baseline = baseline class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" class reform_ab(Reform): def apply(self): self.key = self.__class__.__name__ class reform_ba(Reform): def apply(self): self.key = self.__class__.__name__ def test_tax_benefit_systems_with_reform_cache(): baseline = TaxBenefitSystem() extensions = [] ab_tax_benefit_system = _get_tax_benefit_system(baseline, 'ab', extensions) ba_tax_benefit_system = _get_tax_benefit_system(baseline, 'ba', extensions) assert ab_tax_benefit_system != ba_tax_benefit_system
<commit_before>from openfisca_core.tools.test_runner import _run_test from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" <commit_msg>Add unit test for test_runner _get_tax_benefit_system<commit_after>from openfisca_core.tools.test_runner import _run_test, _get_tax_benefit_system from openfisca_core.errors import VariableNotFound import pytest class TaxBenefitSystem: def __init__(self): self.variables = {} def get_package_metadata(self): return {"name": "Test", "version": "Test"} def apply_reform(self, path): return Reform(self) class Reform(TaxBenefitSystem): def __init__(self, baseline): self.baseline = baseline class Simulation: def __init__(self): self.tax_benefit_system = TaxBenefitSystem() self.entities = {} def get_entity(self, plural = None): return None def test_variable_not_found(): test = {"output": {"unknown_variable": 0}} with pytest.raises(VariableNotFound) as excinfo: _run_test(Simulation(), test) assert excinfo.value.variable_name == "unknown_variable" class reform_ab(Reform): def apply(self): self.key = self.__class__.__name__ class reform_ba(Reform): def apply(self): self.key = self.__class__.__name__ def test_tax_benefit_systems_with_reform_cache(): baseline = TaxBenefitSystem() extensions = [] ab_tax_benefit_system = _get_tax_benefit_system(baseline, 'ab', extensions) ba_tax_benefit_system = _get_tax_benefit_system(baseline, 'ba', extensions) assert ab_tax_benefit_system != ba_tax_benefit_system
b700cc013be2236c50937876b974891355842782
esis/__init__.py
esis/__init__.py
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0' from esis.es import Client
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" from esis.es import Client __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0'
Move import to the top of the file
Move import to the top of the file
Python
mit
jcollado/esis
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0' from esis.es import Client Move import to the top of the file
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" from esis.es import Client __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0'
<commit_before># -*- coding: utf-8 -*- """Elastic Search Index & Search.""" __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0' from esis.es import Client <commit_msg>Move import to the top of the file<commit_after>
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" from esis.es import Client __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0'
# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0' from esis.es import Client Move import to the top of the file# -*- coding: utf-8 -*- """Elastic Search Index & Search.""" from esis.es import Client __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0'
<commit_before># -*- coding: utf-8 -*- """Elastic Search Index & Search.""" __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0' from esis.es import Client <commit_msg>Move import to the top of the file<commit_after># -*- coding: utf-8 -*- """Elastic Search Index & Search.""" from esis.es import Client __author__ = 'Javier Collado' __email__ = 'jcollado@nowsecure.com' __version__ = '0.2.0'
128f6f722f14ac1a202559ffe373304928f7c842
patients/tests/test_views.py
patients/tests/test_views.py
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): from patients.views import search_patient from patients.models import Paciente #Tentando contar quantos objetos o QuerySet contem. p = Paciente.objects.using('test_hub').all() p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self):
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet from patients.views import search_patient from patients.models import Paciente class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): #Deixei o teste "passando", pq estava atrapalhando #na visualização do log dos outros testes self.assertEquals("anato","anato") #Tentando contar quantos objetos o QuerySet contem. ##p = Paciente.objects.using('test_hub').all() ##p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self):
Create assert true in teste_view
Create assert true in teste_view
Python
mit
msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub,msfernandes/anato-hub
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): from patients.views import search_patient from patients.models import Paciente #Tentando contar quantos objetos o QuerySet contem. p = Paciente.objects.using('test_hub').all() p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self): Create assert true in teste_view
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet from patients.views import search_patient from patients.models import Paciente class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): #Deixei o teste "passando", pq estava atrapalhando #na visualização do log dos outros testes self.assertEquals("anato","anato") #Tentando contar quantos objetos o QuerySet contem. ##p = Paciente.objects.using('test_hub').all() ##p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self):
<commit_before>from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): from patients.views import search_patient from patients.models import Paciente #Tentando contar quantos objetos o QuerySet contem. p = Paciente.objects.using('test_hub').all() p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self): <commit_msg>Create assert true in teste_view<commit_after>
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet from patients.views import search_patient from patients.models import Paciente class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): #Deixei o teste "passando", pq estava atrapalhando #na visualização do log dos outros testes self.assertEquals("anato","anato") #Tentando contar quantos objetos o QuerySet contem. ##p = Paciente.objects.using('test_hub').all() ##p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self):
from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): from patients.views import search_patient from patients.models import Paciente #Tentando contar quantos objetos o QuerySet contem. p = Paciente.objects.using('test_hub').all() p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self): Create assert true in teste_viewfrom django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet from patients.views import search_patient from patients.models import Paciente class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): #Deixei o teste "passando", pq estava atrapalhando #na visualização do log dos outros testes self.assertEquals("anato","anato") #Tentando contar quantos objetos o QuerySet contem. ##p = Paciente.objects.using('test_hub').all() ##p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self):
<commit_before>from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): from patients.views import search_patient from patients.models import Paciente #Tentando contar quantos objetos o QuerySet contem. p = Paciente.objects.using('test_hub').all() p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self): <commit_msg>Create assert true in teste_view<commit_after>from django.test import TestCase, Client from should_dsl import should, should_not from django.db.models.query import QuerySet from patients.views import search_patient from patients.models import Paciente class TestVies(TestCase): def setUp(self): self.client = Client() #Valores de testes: #Testar para 1 Paciente retornado. #Testar para mais de 1 Paciente retornado. #Testar para nenhum Paciente retornado. def test_search_patients(self): #Deixei o teste "passando", pq estava atrapalhando #na visualização do log dos outros testes self.assertEquals("anato","anato") #Tentando contar quantos objetos o QuerySet contem. ##p = Paciente.objects.using('test_hub').all() ##p['patients'].count() #string = p['patients'][0].nome #p['patients'] |should| have(1).elements #len(p['patients']) |should| have(1).elements #p = search_patient("", "", "", "Idelia") #p['patients'] |should| have(4).elements #def test_search_results(self):
9cfc5c5acf568b56f4f150e3040827e5856b52c2
insertion_sort.py
insertion_sort.py
def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': pass
def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': BEST_CASE = range(1000) WORST_CASE = BEST_CASE[::-1] from timeit import Timer best = Timer( 'insertion_sort({})'.format(BEST_CASE), 'from __main__ import BEST_CASE, insertion_sort').timeit(1000) worst = Timer( 'insertion_sort({})'.format(WORST_CASE), 'from __main__ import WORST_CASE, insertion_sort').timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
Update module with timeit testing for best and worst case scenarios.
Update module with timeit testing for best and worst case scenarios.
Python
mit
jonathanstallings/data-structures
def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': pass Update module with timeit testing for best and worst case scenarios.
def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': BEST_CASE = range(1000) WORST_CASE = BEST_CASE[::-1] from timeit import Timer best = Timer( 'insertion_sort({})'.format(BEST_CASE), 'from __main__ import BEST_CASE, insertion_sort').timeit(1000) worst = Timer( 'insertion_sort({})'.format(WORST_CASE), 'from __main__ import WORST_CASE, insertion_sort').timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
<commit_before>def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': pass <commit_msg>Update module with timeit testing for best and worst case scenarios.<commit_after>
def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': BEST_CASE = range(1000) WORST_CASE = BEST_CASE[::-1] from timeit import Timer best = Timer( 'insertion_sort({})'.format(BEST_CASE), 'from __main__ import BEST_CASE, insertion_sort').timeit(1000) worst = Timer( 'insertion_sort({})'.format(WORST_CASE), 'from __main__ import WORST_CASE, insertion_sort').timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': pass Update module with timeit testing for best and worst case scenarios.def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': BEST_CASE = range(1000) WORST_CASE = BEST_CASE[::-1] from timeit import Timer best = Timer( 'insertion_sort({})'.format(BEST_CASE), 'from __main__ import BEST_CASE, insertion_sort').timeit(1000) worst = Timer( 'insertion_sort({})'.format(WORST_CASE), 'from __main__ import WORST_CASE, insertion_sort').timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
<commit_before>def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': pass <commit_msg>Update module with timeit testing for best and worst case scenarios.<commit_after>def insertion_sort(un_list): for idx in range(1, len(un_list)): current = un_list[idx] position = idx while position > 0 and un_list[position-1] > current: un_list[position] = un_list[position-1] position = position - 1 un_list[position] = current if __name__ == '__main__': BEST_CASE = range(1000) WORST_CASE = BEST_CASE[::-1] from timeit import Timer best = Timer( 'insertion_sort({})'.format(BEST_CASE), 'from __main__ import BEST_CASE, insertion_sort').timeit(1000) worst = Timer( 'insertion_sort({})'.format(WORST_CASE), 'from __main__ import WORST_CASE, insertion_sort').timeit(1000) print("""Best case represented as a list that is already sorted\n Worst case represented as a list that is absolute reverse of sorted""") print('Best Case: {}'.format(best)) print('Worst Case: {}'.format(worst))
ce7e025607cbd871bc4840f7ebf3c3af8b8e1881
flycam.py
flycam.py
import capture from picamera import PiCamera import time def image_cap_loop(camera): """Set image parameters, capture image, set wait time, repeat""" images = 18 status = None resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 1000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
import capture from picamera import PiCamera import time def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 100000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera, status) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
Adjust day size to 100k. Change status flag placement.
Adjust day size to 100k. Change status flag placement.
Python
mit
gnfrazier/YardCam
import capture from picamera import PiCamera import time def image_cap_loop(camera): """Set image parameters, capture image, set wait time, repeat""" images = 18 status = None resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 1000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main() Adjust day size to 100k. Change status flag placement.
import capture from picamera import PiCamera import time def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 100000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera, status) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
<commit_before>import capture from picamera import PiCamera import time def image_cap_loop(camera): """Set image parameters, capture image, set wait time, repeat""" images = 18 status = None resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 1000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main() <commit_msg>Adjust day size to 100k. Change status flag placement.<commit_after>
import capture from picamera import PiCamera import time def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 100000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera, status) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
import capture from picamera import PiCamera import time def image_cap_loop(camera): """Set image parameters, capture image, set wait time, repeat""" images = 18 status = None resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 1000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main() Adjust day size to 100k. Change status flag placement.import capture from picamera import PiCamera import time def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 100000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera, status) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
<commit_before>import capture from picamera import PiCamera import time def image_cap_loop(camera): """Set image parameters, capture image, set wait time, repeat""" images = 18 status = None resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 1000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main() <commit_msg>Adjust day size to 100k. Change status flag placement.<commit_after>import capture from picamera import PiCamera import time def image_cap_loop(camera, status=None): """Set image parameters, capture image, set wait time, repeat""" resolution = (854, 480) latest = capture.cap(camera, resolution, status) status = latest[0] size = capture.image_size(latest[1]) capture.copy_latest(latest[1]) day = 100000 # image size when light is good if size > day: wait = 60 else: wait = 600 status = capture.shutdown(camera) print('Next capture begins in {} seconds.'.format(wait)) time.sleep(wait) # status = capture.shutdown(camera) image_cap_loop(camera, status) def main(): camera = PiCamera() image_cap_loop(camera) print("Images captured") if __name__ == '__main__': main()
c7785ff4367de929392b85f73a396e987cfe4606
apps/chats/models.py
apps/chats/models.py
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def as_html(self, tag='div'): """ Return an HTML representation of this chat, including tags marking the author and text selection accordingly. Use the tag argument to customize the tag that wraps each line in a chat. """ html = u'' for line in self.text.splitlines(): line_sections = line.split(': ', 1) if len(line_sections) > 1: html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( author=line_sections[0], tag=tag, text=line_sections[1], ) else: html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( tag=tag, text=line_sections[0], ) return html def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
Add HTML representation of chat
Add HTML representation of chat
Python
mit
tofumatt/quotes,tofumatt/quotes
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6) Add HTML representation of chat
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def as_html(self, tag='div'): """ Return an HTML representation of this chat, including tags marking the author and text selection accordingly. Use the tag argument to customize the tag that wraps each line in a chat. """ html = u'' for line in self.text.splitlines(): line_sections = line.split(': ', 1) if len(line_sections) > 1: html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( author=line_sections[0], tag=tag, text=line_sections[1], ) else: html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( tag=tag, text=line_sections[0], ) return html def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
<commit_before>from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6) <commit_msg>Add HTML representation of chat<commit_after>
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def as_html(self, tag='div'): """ Return an HTML representation of this chat, including tags marking the author and text selection accordingly. Use the tag argument to customize the tag that wraps each line in a chat. """ html = u'' for line in self.text.splitlines(): line_sections = line.split(': ', 1) if len(line_sections) > 1: html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( author=line_sections[0], tag=tag, text=line_sections[1], ) else: html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( tag=tag, text=line_sections[0], ) return html def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6) Add HTML representation of chatfrom django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def as_html(self, tag='div'): """ Return an HTML representation of this chat, including tags marking the author and text selection accordingly. Use the tag argument to customize the tag that wraps each line in a chat. """ html = u'' for line in self.text.splitlines(): line_sections = line.split(': ', 1) if len(line_sections) > 1: html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( author=line_sections[0], tag=tag, text=line_sections[1], ) else: html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( tag=tag, text=line_sections[0], ) return html def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
<commit_before>from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6) <commit_msg>Add HTML representation of chat<commit_after>from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A chat is a single or multi-line text excerpt from a chat (usually purposefully out of context) posted by a user. It is often view-restricted to specific groups. """ # A chat without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) posted_by = models.ForeignKey(User) text = models.TextField() def as_html(self, tag='div'): """ Return an HTML representation of this chat, including tags marking the author and text selection accordingly. Use the tag argument to customize the tag that wraps each line in a chat. """ html = u'' for line in self.text.splitlines(): line_sections = line.split(': ', 1) if len(line_sections) > 1: html += u'<{tag} class="line"><span class="author">{author}</span>: <span class="text">{text}</span></{tag}>'.format( author=line_sections[0], tag=tag, text=line_sections[1], ) else: html += u'<{tag} class="no-author line"><span class="text">{text}</span></{tag}>'.format( tag=tag, text=line_sections[0], ) return html def __unicode__(self): """Return the first six words from this chat's text field.""" return truncate_words(self.text, 6)
2c74cc83f2060cf0ea6198a955fbbe2f07e2dd05
apps/chats/models.py
apps/chats/models.py
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Chat relationships are nullable; most Quotes likely don't have a related # Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the text found inside this quote. """ return u"{name}: {text_excerpt}".format( name=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
Clean up Quote model code
Clean up Quote model code
Python
mit
tofumatt/quotes,tofumatt/quotes
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Chat relationships are nullable; most Quotes likely don't have a related # Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the text found inside this quote. """ return u"{name}: {text_excerpt}".format( name=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) ) Clean up Quote model code
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
<commit_before>from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Chat relationships are nullable; most Quotes likely don't have a related # Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the text found inside this quote. """ return u"{name}: {text_excerpt}".format( name=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) ) <commit_msg>Clean up Quote model code<commit_after>
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Chat relationships are nullable; most Quotes likely don't have a related # Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the text found inside this quote. """ return u"{name}: {text_excerpt}".format( name=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) ) Clean up Quote model codefrom django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
<commit_before>from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Chat relationships are nullable; most Quotes likely don't have a related # Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the text found inside this quote. """ return u"{name}: {text_excerpt}".format( name=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) ) <commit_msg>Clean up Quote model code<commit_after>from django.db import models from django.contrib.auth.models import User from django.utils.text import truncate_words from automatic_timestamps.models import TimestampModel class Chat(TimestampModel): """ A collection of chat items (quotes), ordered by their created_at values, grouped together like a chat history. All quotes that belong to a Chat are not displayable on an individual basis. """ title = models.CharField(max_length=200) class Quote(TimestampModel): """ A quote is a single-line text excerpt from a chat (usually purposefully out of context) belonging to a certain user. It is often view-restricted to specific groups. """ # Most Quotes likely don't have a related Chat object. chat = models.ForeignKey(Chat, blank=True, null=True) # A quote without any associated Friend Groups is considered public and will # be viewable to the entire world! friend_groups = models.ManyToManyField('profiles.FriendGroup', blank=True) text = models.CharField(max_length=1000) user = models.ForeignKey(User) def __unicode__(self): """ Return the name of the quote's authoor and text found inside this quote. """ return u"{author}: {text_excerpt}".format( author=self.user.username, text_excerpt=self.text# truncate_words(self.text, 5) )
f36baf09fbbe62ff2fef97528f2d00df43797b43
flow/__init__.py
flow/__init__.py
from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings
from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData, NumpyFeature from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings
Add NumpyFeature to top-level exports
Add NumpyFeature to top-level exports
Python
mit
JohnVinyard/featureflow,JohnVinyard/featureflow
from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings Add NumpyFeature to top-level exports
from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData, NumpyFeature from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings
<commit_before>from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings <commit_msg>Add NumpyFeature to top-level exports<commit_after>
from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData, NumpyFeature from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings
from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings Add NumpyFeature to top-level exportsfrom model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData, NumpyFeature from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings
<commit_before>from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings <commit_msg>Add NumpyFeature to top-level exports<commit_after>from model import BaseModel from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \ PickleFeature from extractor import Node, Graph, Aggregator, NotEnoughData from bytestream import ByteStream, ByteStreamFeature from data import \ IdProvider, UuidProvider, UserSpecifiedIdProvider, KeyBuilder \ , StringDelimitedKeyBuilder, Database \ , FileSystemDatabase, InMemoryDatabase from datawriter import DataWriter from nmpy import StreamingNumpyDecoder, NumpyMetaData, NumpyFeature from database_iterator import DatabaseIterator from encoder import IdentityEncoder from decoder import Decoder from lmdbstore import LmdbDatabase from persistence import PersistenceSettings
41a04ca380dca8d2b358f84bd7982f0ea01ac7f2
camoco/Config.py
camoco/Config.py
#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf'))
#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] force = True refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf'))
Add force option for testing.
Add force option for testing.
Python
mit
schae234/Camoco,schae234/Camoco
#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf')) Add force option for testing.
#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] force = True refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf'))
<commit_before>#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf')) <commit_msg>Add force option for testing.<commit_after>
#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] force = True refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf'))
#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf')) Add force option for testing.#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] force = True refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf'))
<commit_before>#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf')) <commit_msg>Add force option for testing.<commit_after>#!/usr/env/python3 import os import configparser global cf cf = configparser.ConfigParser() cf._interpolation = configparser.ExtendedInterpolation() cf_file = os.path.expanduser('~/.camoco.conf') default_config = ''' [options] basedir = ~/.camoco/ testdir = ~/.camoco/ [logging] log_level = verbose [test] force = True refgen = Zm5bFGS cob = NewRoot ontology = ZmIonome term = Fe57 gene = GRMZM2G000014 ''' # Check to see if if not os.path.isfile(cf_file): with open(cf_file, 'w') as CF: print(default_config,file=CF) cf.read(os.path.expanduser('~/.camoco.conf'))
b9a752c8f6ea7fd9ada1ec283b7aaaa2eaf4b271
src/gui/loggers_ui/urls.py
src/gui/loggers_ui/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ]
Move global map url before session url.
gui: Move global map url before session url.
Python
mit
alberand/tserver,alberand/tserver,alberand/tserver,alberand/tserver
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ] gui: Move global map url before session url.
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ]
<commit_before>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ] <commit_msg>gui: Move global map url before session url.<commit_after>
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ] gui: Move global map url before session url.from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ]
<commit_before>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ] <commit_msg>gui: Move global map url before session url.<commit_after>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.MainPage.as_view(), name='index'), url(r'^GlobalMap/$', views.GlobalMap.as_view(), name='GlobalMap'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/$', views.SessionPage.as_view(), name='Session'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/Map$', views.MapPage.as_view(), name='Map'), url(r'^(?P<ses_id>[a-zA-Z0-9]+)/download$', views.download_file, name='ses_down'), ]
586d031ce6b9f5b62122ca1970c9cef36fa6625f
client_libraries-DEPRECATED/python/src/setup.py
client_libraries-DEPRECATED/python/src/setup.py
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Consumer Surveys", author_email="gcs-api-trusted-testers@googlegroups.com", keywords="google consumer surveys api client", url="https://github.com/google/consumer-surveys", license="Apache License 2.0", description=("Client API for Google Consumer Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Surveys", author_email="surveys-api@googlegroups.com", keywords="google surveys api client", url="https://developers.google.com/surveys", license="Apache License 2.0", description=("Client API for Google Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
Update PyPi package information to reflect rebranding.
Update PyPi package information to reflect rebranding.
Python
apache-2.0
googlearchive/surveys,googlearchive/surveys,googlearchive/surveys
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Consumer Surveys", author_email="gcs-api-trusted-testers@googlegroups.com", keywords="google consumer surveys api client", url="https://github.com/google/consumer-surveys", license="Apache License 2.0", description=("Client API for Google Consumer Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, ) Update PyPi package information to reflect rebranding.
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Surveys", author_email="surveys-api@googlegroups.com", keywords="google surveys api client", url="https://developers.google.com/surveys", license="Apache License 2.0", description=("Client API for Google Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
<commit_before>#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Consumer Surveys", author_email="gcs-api-trusted-testers@googlegroups.com", keywords="google consumer surveys api client", url="https://github.com/google/consumer-surveys", license="Apache License 2.0", description=("Client API for Google Consumer Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, ) <commit_msg>Update PyPi package information to reflect rebranding.<commit_after>
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Surveys", author_email="surveys-api@googlegroups.com", keywords="google surveys api client", url="https://developers.google.com/surveys", license="Apache License 2.0", description=("Client API for Google Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Consumer Surveys", author_email="gcs-api-trusted-testers@googlegroups.com", keywords="google consumer surveys api client", url="https://github.com/google/consumer-surveys", license="Apache License 2.0", description=("Client API for Google Consumer Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, ) Update PyPi package information to reflect rebranding.#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Surveys", author_email="surveys-api@googlegroups.com", keywords="google surveys api client", url="https://developers.google.com/surveys", license="Apache License 2.0", description=("Client API for Google Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
<commit_before>#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Consumer Surveys", author_email="gcs-api-trusted-testers@googlegroups.com", keywords="google consumer surveys api client", url="https://github.com/google/consumer-surveys", license="Apache License 2.0", description=("Client API for Google Consumer Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, ) <commit_msg>Update PyPi package information to reflect rebranding.<commit_after>#!/usr/bin/env python """Packaging, distributing, and installing the ConsumerSurveys lib.""" import setuptools # To debug, set DISTUTILS_DEBUG env var to anything. setuptools.setup( name="GoogleConsumerSurveys", version="0.0.0.4", packages=setuptools.find_packages(), author="Google Surveys", author_email="surveys-api@googlegroups.com", keywords="google surveys api client", url="https://developers.google.com/surveys", license="Apache License 2.0", description=("Client API for Google Surveys API"), zip_safe=True, include_package_data=True, # Exclude these files from installation. exclude_package_data={"": ["README"]}, install_requires=[ "google-api-python-client >= 1.4.2", ], extras_require={}, )
b9d1dcf614faa949975bc5296be451abd2594835
repository/presenter.py
repository/presenter.py
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
Fix small issue with `--top-n` command switch
Fix small issue with `--top-n` command switch
Python
mit
moacirosa/git-current-contributors,moacirosa/git-current-contributors
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed) Fix small issue with `--top-n` command switch
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
<commit_before>import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed) <commit_msg>Fix small issue with `--top-n` command switch<commit_after>
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed) Fix small issue with `--top-n` command switchimport logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
<commit_before>import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if argv.top_n > 0 else None sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed) <commit_msg>Fix small issue with `--top-n` command switch<commit_after>import logger import datetime def out(counter, argv, elapsed_time = None): sum_lines = sum(counter.values()) blue = '\033[94m' grey = '\033[0m' endcolor = '\033[0m' italic = '\x1B[3m' eitalic = '\x1B[23m' template = '{0:>7.2%} {3}{2}{4}' if argv.show_absolute > 0: template = '{0:>7.2%} {3}{2}{4} ({1})' top_n = argv.top_n if top_n < 0 or top_n > len(counter): top_n = len(counter) sorted_counter = counter.most_common(top_n) if argv.alphabetically: sorted_counter = sorted(sorted_counter) if argv.reverse: sorted_counter = reversed(sorted_counter) for author, contributions in sorted_counter: relative = float(contributions) / float(sum_lines) output = template.format(relative, contributions, author, blue, endcolor, italic, eitalic) print(output) n_contributors = 'Showing {}/{} contributors'.format(top_n, len(counter)) elapsed ='Elapsed time: {}'.format(datetime.timedelta(seconds=elapsed_time)) logger.instance.info(n_contributors) logger.instance.info(elapsed)
94d2fb9241874d7feb89aa6fee6bc14b76e3a441
grains/grains.py
grains/grains.py
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM board = [x for x in range(1, 65)] grains = [x*2 for x in range(1, 65)] def on_square(): for x in range(1, 65): board.append(x)
Add two lists with square and grain numbers
Add two lists with square and grain numbers
Python
mit
amalshehu/exercism-python
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM Add two lists with square and grain numbers
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM board = [x for x in range(1, 65)] grains = [x*2 for x in range(1, 65)] def on_square(): for x in range(1, 65): board.append(x)
<commit_before># File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM <commit_msg>Add two lists with square and grain numbers<commit_after>
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM board = [x for x in range(1, 65)] grains = [x*2 for x in range(1, 65)] def on_square(): for x in range(1, 65): board.append(x)
# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM Add two lists with square and grain numbers# File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM board = [x for x in range(1, 65)] grains = [x*2 for x in range(1, 65)] def on_square(): for x in range(1, 65): board.append(x)
<commit_before># File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM <commit_msg>Add two lists with square and grain numbers<commit_after># File: grains.py # Purpose: Write a program that calculates the number of grains of wheat # on a chessboard given that the number on each square doubles. # Programmer: Amal Shehu # Course: Exercism # Date: Sunday 18 September 2016, 05:25 PM board = [x for x in range(1, 65)] grains = [x*2 for x in range(1, 65)] def on_square(): for x in range(1, 65): board.append(x)
c833f55999f6fd9029626d1b794c86b2b5b11256
post_office/test_settings.py
post_office/test_settings.py
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com'
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
Use "DjangoTestSuiteRunner" to in Django 1.6.
Use "DjangoTestSuiteRunner" to in Django 1.6.
Python
mit
CasherWest/django-post_office,carrerasrodrigo/django-post_office,fapelhanz/django-post_office,RafRaf/django-post_office,ui/django-post_office,jrief/django-post_office,yprez/django-post_office,JostCrow/django-post_office,ui/django-post_office,LeGast00n/django-post_office,CasherWest/django-post_office,ekohl/django-post_office
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com'Use "DjangoTestSuiteRunner" to in Django 1.6.
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
<commit_before># -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com'<commit_msg>Use "DjangoTestSuiteRunner" to in Django 1.6.<commit_after>
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com'Use "DjangoTestSuiteRunner" to in Django 1.6.# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
<commit_before># -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com'<commit_msg>Use "DjangoTestSuiteRunner" to in Django 1.6.<commit_after># -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', }, } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', }, 'post_office': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'TIMEOUT': 36000, 'KEY_PREFIX': 'post-office', } } INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'post_office', ) SECRET_KEY = 'a' ROOT_URLCONF = 'post_office.test_urls' DEFAULT_FROM_EMAIL = 'webmaster@example.com' TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
d8ae8f7bccdbe8eace5bb67b94a75a8003cc30b6
github/models.py
github/models.py
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): return self.events()[:3]
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): try: return self.events()[:3] except (TypeError, KeyError): # not enough events return None
Fix github top_events if events empty
Fix github top_events if events empty
Python
agpl-3.0
terotic/devheldev,terotic/devheldev,City-of-Helsinki/devheldev,terotic/devheldev,City-of-Helsinki/devheldev,City-of-Helsinki/devheldev
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): return self.events()[:3] Fix github top_events if events empty
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): try: return self.events()[:3] except (TypeError, KeyError): # not enough events return None
<commit_before>import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): return self.events()[:3] <commit_msg>Fix github top_events if events empty<commit_after>
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): try: return self.events()[:3] except (TypeError, KeyError): # not enough events return None
import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): return self.events()[:3] Fix github top_events if events emptyimport json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): try: return self.events()[:3] except (TypeError, KeyError): # not enough events return None
<commit_before>import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): return self.events()[:3] <commit_msg>Fix github top_events if events empty<commit_after>import json, requests from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailcore.models import Page, Orderable import django.utils.dateparse as dateparse from django.db import models from django.core.cache import cache class GithubOrgIndexPage(Page): github_org_name = models.CharField(default='City-of-Helsinki', max_length=200) content_panels = Page.content_panels + [ FieldPanel('github_org_name'), ] def events(self): events = cache.get('github') if not events: response = requests.get('https://api.github.com/orgs/' + self.github_org_name + '/events?per_page=20') if response.status_code == 200: cache.add('github', response.json(), 60) events = cache.get('github') for index, event in enumerate(events): event['created_at'] = dateparse.parse_datetime(event['created_at']) # get html repo url event['repo']['url'] = event['repo']['url'].replace('https://api.github.com/repos/', 'https://github.com/') return events def top_events(self): try: return self.events()[:3] except (TypeError, KeyError): # not enough events return None
9f0e5c941c769c4d7c1cbdfcdcf98ddf643173d0
cea/interfaces/dashboard/server/__init__.py
cea/interfaces/dashboard/server/__init__.py
""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint from flask_restplus import Api from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams')
""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint, current_app from flask_restplus import Api, Resource from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') @api.route("/alive") class ServerAlive(Resource): def get(self): return {'success': True} @api.route("/shutdown") class ServerShutdown(Resource): def post(self): current_app.socketio.stop() return {'message': 'Shutting down...'}
Add server alive and shutdown api endpoints
Add server alive and shutdown api endpoints
Python
mit
architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst
""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint from flask_restplus import Api from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') Add server alive and shutdown api endpoints
""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint, current_app from flask_restplus import Api, Resource from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') @api.route("/alive") class ServerAlive(Resource): def get(self): return {'success': True} @api.route("/shutdown") class ServerShutdown(Resource): def post(self): current_app.socketio.stop() return {'message': 'Shutting down...'}
<commit_before>""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint from flask_restplus import Api from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') <commit_msg>Add server alive and shutdown api endpoints<commit_after>
""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint, current_app from flask_restplus import Api, Resource from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') @api.route("/alive") class ServerAlive(Resource): def get(self): return {'success': True} @api.route("/shutdown") class ServerShutdown(Resource): def post(self): current_app.socketio.stop() return {'message': 'Shutting down...'}
""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint from flask_restplus import Api from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') Add server alive and shutdown api endpoints""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint, current_app from flask_restplus import Api, Resource from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') @api.route("/alive") class ServerAlive(Resource): def get(self): return {'success': True} @api.route("/shutdown") class ServerShutdown(Resource): def post(self): current_app.socketio.stop() return {'message': 'Shutting down...'}
<commit_before>""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint from flask_restplus import Api from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') <commit_msg>Add server alive and shutdown api endpoints<commit_after>""" The /server api blueprint is used by cea-worker processes to manage jobs and files. """ from __future__ import print_function from __future__ import division from flask import Blueprint, current_app from flask_restplus import Api, Resource from .jobs import api as jobs from .streams import api as streams __author__ = "Daren Thomas" __copyright__ = "Copyright 2019, Architecture and Building Systems - ETH Zurich" __credits__ = ["Daren Thomas"] __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Daren Thomas" __email__ = "cea@arch.ethz.ch" __status__ = "Production" blueprint = Blueprint('server', __name__, url_prefix='/server') api = Api(blueprint) # there might potentially be more namespaces added in the future, e.g. a method for locating files etc. api.add_namespace(jobs, path='/jobs') api.add_namespace(streams, path='/streams') @api.route("/alive") class ServerAlive(Resource): def get(self): return {'success': True} @api.route("/shutdown") class ServerShutdown(Resource): def post(self): current_app.socketio.stop() return {'message': 'Shutting down...'}
92f98b24eb1718f200ea75874b932e8335dbb35c
frappe/patches/v14_0/set_document_expiry_default.py
frappe/patches/v14_0/set_document_expiry_default.py
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", "document_share_key_expiry", 30) frappe.db.set_value("System Settings", "System Settings", "allow_older_web_view_links", 1)
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", { "document_share_key_expiry": 30, "allow_older_web_view_links": 1 })
Set values in a single query
refactor: Set values in a single query
Python
mit
StrellaGroup/frappe,yashodhank/frappe,yashodhank/frappe,StrellaGroup/frappe,yashodhank/frappe,frappe/frappe,frappe/frappe,StrellaGroup/frappe,frappe/frappe,yashodhank/frappe
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", "document_share_key_expiry", 30) frappe.db.set_value("System Settings", "System Settings", "allow_older_web_view_links", 1) refactor: Set values in a single query
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", { "document_share_key_expiry": 30, "allow_older_web_view_links": 1 })
<commit_before>import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", "document_share_key_expiry", 30) frappe.db.set_value("System Settings", "System Settings", "allow_older_web_view_links", 1) <commit_msg>refactor: Set values in a single query<commit_after>
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", { "document_share_key_expiry": 30, "allow_older_web_view_links": 1 })
import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", "document_share_key_expiry", 30) frappe.db.set_value("System Settings", "System Settings", "allow_older_web_view_links", 1) refactor: Set values in a single queryimport frappe def execute(): frappe.db.set_value("System Settings", "System Settings", { "document_share_key_expiry": 30, "allow_older_web_view_links": 1 })
<commit_before>import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", "document_share_key_expiry", 30) frappe.db.set_value("System Settings", "System Settings", "allow_older_web_view_links", 1) <commit_msg>refactor: Set values in a single query<commit_after>import frappe def execute(): frappe.db.set_value("System Settings", "System Settings", { "document_share_key_expiry": 30, "allow_older_web_view_links": 1 })
c78fa20de52468ceb2cdbbee952f486ac2533902
helusers/apps.py
helusers/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin.AdminSite'
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin_site.AdminSite'
Fix wrong path for helusers AdminSite
Fix wrong path for helusers AdminSite
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin.AdminSite' Fix wrong path for helusers AdminSite
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin_site.AdminSite'
<commit_before>from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin.AdminSite' <commit_msg>Fix wrong path for helusers AdminSite<commit_after>
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin_site.AdminSite'
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin.AdminSite' Fix wrong path for helusers AdminSitefrom django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin_site.AdminSite'
<commit_before>from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin.AdminSite' <commit_msg>Fix wrong path for helusers AdminSite<commit_after>from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.contrib.admin.apps import AdminConfig class HelusersConfig(AppConfig): name = 'helusers' verbose_name = _("Helsinki Users") class HelusersAdminConfig(AdminConfig): default_site = 'helusers.admin_site.AdminSite'
8c7080e93f7966bb64d7ea531d9f19b4c75b5fd5
bucketeer/test/test_commit.py
bucketeer/test/test_commit.py
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): # Constants - TODO move to config file global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
Add comment about constant values
Add comment about constant values
Python
mit
mgarbacz/bucketeer
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main() Add comment about constant values
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): # Constants - TODO move to config file global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
<commit_before>import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main() <commit_msg>Add comment about constant values<commit_after>
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): # Constants - TODO move to config file global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main() Add comment about constant valuesimport unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): # Constants - TODO move to config file global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
<commit_before>import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main() <commit_msg>Add comment about constant values<commit_after>import unittest, boto, os from bucketeer import commit class BuckeeterTest(unittest.TestCase): # Constants - TODO move to config file global existing_bucket, test_dir, test_file existing_bucket = 'bucket.exists' test_dir = 'bucketeer_test_dir' test_file = 'bucketeer_test_file' def setUp(self): # Create a bucket to test on existing bucket connection = boto.connect_s3() bucket = connection.create_bucket(existing_bucket) # Create directory to house test files os.makedirs(test_dir) # Create test file open(test_dir + '/' + test_file, 'w').close() return def tearDown(self): # Remove bucket created to test on existing bucket connection = boto.connect_s3() bucket = connection.delete_bucket(existing_bucket) # Remove test file os.remove(test_dir + '/' + test_file) # Remove directory created to house test files os.rmdir(test_dir) return def testMain(self): self.assertTrue(commit) if __name__ == '__main__': unittest.main()
de6a7ab74b2a826aee8cb0ef18d595c04281a50c
froide/publicbody/law_urls.py
froide/publicbody/law_urls.py
from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), )
from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)/$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), )
Add a slash to law urls
Add a slash to law urls
Python
mit
stefanw/froide,CodeforHawaii/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/froide,catcosmo/froide,ryankanno/froide,okfse/froide,ryankanno/froide,fin/froide,CodeforHawaii/froide,stefanw/froide,LilithWittmann/froide,catcosmo/froide,ryankanno/froide,stefanw/froide,ryankanno/froide,CodeforHawaii/froide,okfse/froide,catcosmo/froide,fin/froide,LilithWittmann/froide,LilithWittmann/froide,stefanw/froide,stefanw/froide,okfse/froide,okfse/froide,okfse/froide,LilithWittmann/froide,LilithWittmann/froide,catcosmo/froide,fin/froide,ryankanno/froide,fin/froide
from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), ) Add a slash to law urls
from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)/$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), )
<commit_before>from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), ) <commit_msg>Add a slash to law urls<commit_after>
from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)/$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), )
from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), ) Add a slash to law urlsfrom django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)/$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), )
<commit_before>from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), ) <commit_msg>Add a slash to law urls<commit_after>from django.conf.urls.defaults import patterns, url urlpatterns = patterns("", url(r"^(?P<slug>[-\w]+)/$", 'publicbody.views.show_foilaw', name="publicbody-foilaw-show"), )
e9964a0f96777c5aae83349ccde3d14fbd04353b
contrib/generate-gresource-xml.py
contrib/generate-gresource-xml.py
#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) sys.exit(0)
#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: try: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) except TypeError: f.write(ET.tostring(root, "utf-8")) sys.exit(0)
Fix compile when using python 3.7 or older
trivial: Fix compile when using python 3.7 or older Signed-off-by: Richard Hughes <320bca71fc381a4a025636043ca86e734e31cf8b@hughsie.com>
Python
lgpl-2.1
fwupd/fwupd,fwupd/fwupd,fwupd/fwupd,fwupd/fwupd
#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) sys.exit(0) trivial: Fix compile when using python 3.7 or older Signed-off-by: Richard Hughes <320bca71fc381a4a025636043ca86e734e31cf8b@hughsie.com>
#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: try: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) except TypeError: f.write(ET.tostring(root, "utf-8")) sys.exit(0)
<commit_before>#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) sys.exit(0) <commit_msg>trivial: Fix compile when using python 3.7 or older Signed-off-by: Richard Hughes <320bca71fc381a4a025636043ca86e734e31cf8b@hughsie.com><commit_after>
#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: try: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) except TypeError: f.write(ET.tostring(root, "utf-8")) sys.exit(0)
#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) sys.exit(0) trivial: Fix compile when using python 3.7 or older Signed-off-by: Richard Hughes <320bca71fc381a4a025636043ca86e734e31cf8b@hughsie.com>#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: try: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) except TypeError: f.write(ET.tostring(root, "utf-8")) sys.exit(0)
<commit_before>#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) sys.exit(0) <commit_msg>trivial: Fix compile when using python 3.7 or older Signed-off-by: Richard Hughes <320bca71fc381a4a025636043ca86e734e31cf8b@hughsie.com><commit_after>#!/usr/bin/python3 # pylint: disable=invalid-name,missing-docstring # # Copyright (C) 2022 Richard Hughes <richard@hughsie.com> # # SPDX-License-Identifier: LGPL-2.1+ import sys import os import xml.etree.ElementTree as ET if len(sys.argv) < 2: print("not enough arguments") sys.exit(1) root = ET.Element("gresources") n_gresource = ET.SubElement(root, "gresource", {"prefix": "/org/freedesktop/fwupd"}) for fn in sorted(sys.argv[2:]): n_file = ET.SubElement(n_gresource, "file", {"compressed": "true"}) n_file.text = fn if fn.endswith(".xml"): n_file.set("preprocess", "xml-stripblanks") n_file.set("alias", os.path.basename(fn)) with open(sys.argv[1], "wb") as f: try: f.write(ET.tostring(root, "utf-8", xml_declaration=True)) except TypeError: f.write(ET.tostring(root, "utf-8")) sys.exit(0)
cc9aa5c8e612cf4fcd79cbe8f4c1ff64c94b0b0e
saleor/product/views.py
saleor/product/views.py
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form }) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category })
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return redirect('product:details', slug=slug, product_id=product_id) return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form}) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category})
Add missing redirect after POST in product details
Add missing redirect after POST in product details
Python
bsd-3-clause
itbabu/saleor,dashmug/saleor,jreigel/saleor,hongquan/saleor,avorio/saleor,UITools/saleor,hongquan/saleor,arth-co/saleor,rchav/vinerack,mociepka/saleor,avorio/saleor,paweltin/saleor,laosunhust/saleor,spartonia/saleor,taedori81/saleor,UITools/saleor,arth-co/saleor,maferelo/saleor,laosunhust/saleor,KenMutemi/saleor,avorio/saleor,tfroehlich82/saleor,rodrigozn/CW-Shop,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,car3oon/saleor,laosunhust/saleor,mociepka/saleor,KenMutemi/saleor,laosunhust/saleor,josesanch/saleor,UITools/saleor,paweltin/saleor,dashmug/saleor,rodrigozn/CW-Shop,tfroehlich82/saleor,jreigel/saleor,UITools/saleor,paweltin/saleor,itbabu/saleor,jreigel/saleor,Drekscott/Motlaesaleor,Drekscott/Motlaesaleor,dashmug/saleor,Drekscott/Motlaesaleor,paweltin/saleor,taedori81/saleor,spartonia/saleor,rodrigozn/CW-Shop,KenMutemi/saleor,taedori81/saleor,hongquan/saleor,spartonia/saleor,car3oon/saleor,arth-co/saleor,josesanch/saleor,josesanch/saleor,spartonia/saleor,itbabu/saleor,taedori81/saleor,maferelo/saleor,avorio/saleor,car3oon/saleor,maferelo/saleor,mociepka/saleor,Drekscott/Motlaesaleor,HyperManTT/ECommerceSaleor,rchav/vinerack,rchav/vinerack,HyperManTT/ECommerceSaleor,arth-co/saleor,UITools/saleor
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form }) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category }) Add missing redirect after POST in product details
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return redirect('product:details', slug=slug, product_id=product_id) return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form}) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category})
<commit_before>from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form }) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category }) <commit_msg>Add missing redirect after POST in product details<commit_after>
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return redirect('product:details', slug=slug, product_id=product_id) return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form}) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category})
from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form }) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category }) Add missing redirect after POST in product detailsfrom __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return redirect('product:details', slug=slug, product_id=product_id) return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form}) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category})
<commit_before>from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form }) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category }) <commit_msg>Add missing redirect after POST in product details<commit_after>from __future__ import unicode_literals from django.http import HttpResponsePermanentRedirect from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.utils.translation import ugettext as _ from .forms import ProductForm from .models import Product, Category def product_details(request, slug, product_id): product = get_object_or_404(Product, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) form = ProductForm(cart=request.cart, product=product, data=request.POST or None) if form.is_valid(): if form.cleaned_data['quantity']: msg = _('Added %(product)s to your cart.') % { 'product': product} messages.success(request, msg) form.save() return redirect('product:details', slug=slug, product_id=product_id) return TemplateResponse(request, 'product/details.html', { 'product': product, 'form': form}) def category_index(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.all() return TemplateResponse(request, 'category/index.html', { 'products': products, 'category': category})
ace1500bde0f4680ad71b51395fd72c4306f8c4b
feature_extraction/measurements/edge_intensity_ratio.py
feature_extraction/measurements/edge_intensity_ratio.py
import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean([inner_mask]) measurements.append(intensity_ratio) return measurements
import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean(image[inner_mask]) measurements.append(intensity_ratio) return measurements
Fix a massive bug in EdgeIntensityRatio
Fix a massive bug in EdgeIntensityRatio Due to a typo, the code was dividing by the mean of a mask, not the mean of the image sliced by the mask
Python
apache-2.0
widoptimization-willett/feature-extraction
import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean([inner_mask]) measurements.append(intensity_ratio) return measurements Fix a massive bug in EdgeIntensityRatio Due to a typo, the code was dividing by the mean of a mask, not the mean of the image sliced by the mask
import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean(image[inner_mask]) measurements.append(intensity_ratio) return measurements
<commit_before>import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean([inner_mask]) measurements.append(intensity_ratio) return measurements <commit_msg>Fix a massive bug in EdgeIntensityRatio Due to a typo, the code was dividing by the mean of a mask, not the mean of the image sliced by the mask<commit_after>
import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean(image[inner_mask]) measurements.append(intensity_ratio) return measurements
import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean([inner_mask]) measurements.append(intensity_ratio) return measurements Fix a massive bug in EdgeIntensityRatio Due to a typo, the code was dividing by the mean of a mask, not the mean of the image sliced by the maskimport numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean(image[inner_mask]) measurements.append(intensity_ratio) return measurements
<commit_before>import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean([inner_mask]) measurements.append(intensity_ratio) return measurements <commit_msg>Fix a massive bug in EdgeIntensityRatio Due to a typo, the code was dividing by the mean of a mask, not the mean of the image sliced by the mask<commit_after>import numpy as np from . import Measurement from ..util.cleanup import cell_boundary_mask import skimage.morphology as morph import matplotlib.pyplot as plt class EdgeIntensityRatio(Measurement): default_options = { 'border_width': 10 # pixels } def compute(self, image): measurements = [] for width in np.hstack([self.options.border_width]): # -- find the outer boundary of the cell cellmask = cell_boundary_mask(image) # -- erode the boundary in by ``width`` inner_mask = morph.binary_erosion(cellmask, morph.disk(width)) # -- compute a mask of the border strip between the inner part and outer boundary of the cell border_mask = cellmask & ~inner_mask # -- find the ratio of the average intensities between the border and interior of the cell intensity_ratio = np.mean(image[border_mask])/np.mean(image[inner_mask]) measurements.append(intensity_ratio) return measurements
c961fbf4be3152efc10d2d67d2f62fdae047ccab
datapipe/targets/filesystem.py
datapipe/targets/filesystem.py
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() self._timestamp = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def is_damaged(self): stored = self.stored() if stored is None: return True if self.exists(): return os.path.getmtime(self._path) > stored['timestamp'] else: return True
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def is_damaged(self): mem = self.stored() if mem is None or not 'timestamp' in mem: return True return self._memory['timestamp'] > mem['timestamp']
Fix unnecessary recomputation of file targets
Fix unnecessary recomputation of file targets
Python
mit
ibab/datapipe
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() self._timestamp = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def is_damaged(self): stored = self.stored() if stored is None: return True if self.exists(): return os.path.getmtime(self._path) > stored['timestamp'] else: return True Fix unnecessary recomputation of file targets
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def is_damaged(self): mem = self.stored() if mem is None or not 'timestamp' in mem: return True return self._memory['timestamp'] > mem['timestamp']
<commit_before>import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() self._timestamp = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def is_damaged(self): stored = self.stored() if stored is None: return True if self.exists(): return os.path.getmtime(self._path) > stored['timestamp'] else: return True <commit_msg>Fix unnecessary recomputation of file targets<commit_after>
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def is_damaged(self): mem = self.stored() if mem is None or not 'timestamp' in mem: return True return self._memory['timestamp'] > mem['timestamp']
import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() self._timestamp = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def is_damaged(self): stored = self.stored() if stored is None: return True if self.exists(): return os.path.getmtime(self._path) > stored['timestamp'] else: return True Fix unnecessary recomputation of file targetsimport os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def is_damaged(self): mem = self.stored() if mem is None or not 'timestamp' in mem: return True return self._memory['timestamp'] > mem['timestamp']
<commit_before>import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() self._timestamp = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def is_damaged(self): stored = self.stored() if stored is None: return True if self.exists(): return os.path.getmtime(self._path) > stored['timestamp'] else: return True <commit_msg>Fix unnecessary recomputation of file targets<commit_after>import os from ..target import Target class LocalFile(Target): def __init__(self, path): self._path = path super(LocalFile, self).__init__() if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 def identifier(self): return self._path def exists(self): return os.path.exists(self._path) def path(self): return self._path def store(self, batch=None): if self.exists(): self._memory['timestamp'] = os.path.getmtime(self._path) else: self._memory['timestamp'] = 0 super(LocalFile, self).store(batch) def open(self, *args, **kwargs): return open(self._path, *args, **kwargs) def is_damaged(self): mem = self.stored() if mem is None or not 'timestamp' in mem: return True return self._memory['timestamp'] > mem['timestamp']
9ae5b882b987cd56fe20996733a828171b18aa3a
polygraph/types/tests/test_object_type.py
polygraph/types/tests/test_object_type.py
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual))
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta")
Add tests around ObjectType Meta
Add tests around ObjectType Meta
Python
mit
polygraph-python/polygraph
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) Add tests around ObjectType Meta
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta")
<commit_before>from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) <commit_msg>Add tests around ObjectType Meta<commit_after>
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta")
from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) Add tests around ObjectType Metafrom collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta")
<commit_before>from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") class ObjectTypeTest(TestCase): def test_simple_object_type(self): hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) <commit_msg>Add tests around ObjectType Meta<commit_after>from collections import OrderedDict from unittest import TestCase from graphql.type.definition import GraphQLField, GraphQLObjectType from graphql.type.scalars import GraphQLString from polygraph.types.definitions import PolygraphNonNull from polygraph.types.fields import String, Int from polygraph.types.object_type import ObjectType from polygraph.types.tests.helpers import graphql_objects_equal class ObjectTypeTest(TestCase): def test_simple_object_type(self): class HelloWorldObject(ObjectType): """ This is a test object """ first = String(description="First violin", nullable=True) second = String(description="Second fiddle", nullable=False) third = String(deprecation_reason="Third is dead") hello_world = HelloWorldObject() expected = GraphQLObjectType( name="HelloWorldObject", description="This is a test object", fields=OrderedDict({ "first": GraphQLField(GraphQLString, None, None, None, "First violin"), "second": GraphQLField( PolygraphNonNull(GraphQLString), None, None, None, "Second fiddle"), "third": GraphQLField( PolygraphNonNull(GraphQLString), None, None, "Third is dead", None), }) ) actual = hello_world.build_definition() self.assertTrue(graphql_objects_equal(expected, actual)) def test_object_type_meta(self): class MetaObject(ObjectType): """ This docstring is _not_ the description """ count = Int() class Meta: name = "Meta" description = "Actual meta description is here" meta = MetaObject() self.assertEqual(meta.description, "Actual meta description is here") self.assertEqual(meta.name, "Meta")
9cb2bf5d1432bf45666f939356bfe7057d8e5960
server/mod_auth/auth.py
server/mod_auth/auth.py
from flask import Response from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id): """Returns a user from the database based on their id""" return User.query.filter_by(id=user_id).first() def handle_basic_auth(request): auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request): """Handle a login request from a user.""" user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
import flask from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id: int) -> User: """Returns a user from the database based on their id :param user_id: a users unique id :return: User object with corresponding id, or none if user does not exist """ return User.query.filter_by(id=user_id).first() def handle_basic_auth(request: flask.Request) -> User: """Verifies a request using BASIC auth :param request: flask request object :return: User object corresponding to login information, or none if user does not exist """ auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request: flask.Request) -> flask.Response: """Handle a login request from a user :param request: incoming request object :return: flask response object """ user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return flask.Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
Add type declartions and docstrings
Add type declartions and docstrings
Python
mit
ganemone/ontheside,ganemone/ontheside,ganemone/ontheside
from flask import Response from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id): """Returns a user from the database based on their id""" return User.query.filter_by(id=user_id).first() def handle_basic_auth(request): auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request): """Handle a login request from a user.""" user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) Add type declartions and docstrings
import flask from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id: int) -> User: """Returns a user from the database based on their id :param user_id: a users unique id :return: User object with corresponding id, or none if user does not exist """ return User.query.filter_by(id=user_id).first() def handle_basic_auth(request: flask.Request) -> User: """Verifies a request using BASIC auth :param request: flask request object :return: User object corresponding to login information, or none if user does not exist """ auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request: flask.Request) -> flask.Response: """Handle a login request from a user :param request: incoming request object :return: flask response object """ user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return flask.Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
<commit_before>from flask import Response from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id): """Returns a user from the database based on their id""" return User.query.filter_by(id=user_id).first() def handle_basic_auth(request): auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request): """Handle a login request from a user.""" user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) <commit_msg>Add type declartions and docstrings<commit_after>
import flask from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id: int) -> User: """Returns a user from the database based on their id :param user_id: a users unique id :return: User object with corresponding id, or none if user does not exist """ return User.query.filter_by(id=user_id).first() def handle_basic_auth(request: flask.Request) -> User: """Verifies a request using BASIC auth :param request: flask request object :return: User object corresponding to login information, or none if user does not exist """ auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request: flask.Request) -> flask.Response: """Handle a login request from a user :param request: incoming request object :return: flask response object """ user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return flask.Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
from flask import Response from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id): """Returns a user from the database based on their id""" return User.query.filter_by(id=user_id).first() def handle_basic_auth(request): auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request): """Handle a login request from a user.""" user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) Add type declartions and docstringsimport flask from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id: int) -> User: """Returns a user from the database based on their id :param user_id: a users unique id :return: User object with corresponding id, or none if user does not exist """ return User.query.filter_by(id=user_id).first() def handle_basic_auth(request: flask.Request) -> User: """Verifies a request using BASIC auth :param request: flask request object :return: User object corresponding to login information, or none if user does not exist """ auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request: flask.Request) -> flask.Response: """Handle a login request from a user :param request: incoming request object :return: flask response object """ user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return flask.Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
<commit_before>from flask import Response from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id): """Returns a user from the database based on their id""" return User.query.filter_by(id=user_id).first() def handle_basic_auth(request): auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request): """Handle a login request from a user.""" user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'}) <commit_msg>Add type declartions and docstrings<commit_after>import flask from flask_login import login_user from server.models import User from server.login_manager import login_manager @login_manager.user_loader def load_user(user_id: int) -> User: """Returns a user from the database based on their id :param user_id: a users unique id :return: User object with corresponding id, or none if user does not exist """ return User.query.filter_by(id=user_id).first() def handle_basic_auth(request: flask.Request) -> User: """Verifies a request using BASIC auth :param request: flask request object :return: User object corresponding to login information, or none if user does not exist """ auth = request.authorization if not auth: return None return User.query.filter_by( username=auth.username, password=auth.password ).first() def login(request: flask.Request) -> flask.Response: """Handle a login request from a user :param request: incoming request object :return: flask response object """ user = handle_basic_auth(request) if user: login_user(user, remember=True) return 'OK' return flask.Response( 'Could not verify your access level for that URL.\n' 'You have to login with proper credentials', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
f1b78e050a2b4e8e648e6570c1d2e8688f104899
bin/pylama/lint/extensions.py
bin/pylama/lint/extensions.py
"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611
"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611
Fix import Linter from pylam_pylint
Fix import Linter from pylam_pylint
Python
mit
AtomLinter/linter-pylama
"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611 Fix import Linter from pylam_pylint
"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611
<commit_before>"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611 <commit_msg>Fix import Linter from pylam_pylint<commit_after>
"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611
"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611 Fix import Linter from pylam_pylint"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611
<commit_before>"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611 <commit_msg>Fix import Linter from pylam_pylint<commit_after>"""Load extensions.""" import os import sys CURDIR = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(CURDIR, '..', '..', 'deps')) LINTERS = {} try: from pylama.lint.pylama_mccabe import Linter LINTERS['mccabe'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pydocstyle import Linter LINTERS['pep257'] = Linter() # for compatibility LINTERS['pydocstyle'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pycodestyle import Linter LINTERS['pycodestyle'] = Linter() # for compability LINTERS['pep8'] = Linter() # for compability except ImportError: pass try: from pylama.lint.pylama_pyflakes import Linter LINTERS['pyflakes'] = Linter() except ImportError: pass try: from pylama.lint.pylama_pylint import Linter LINTERS['pylint'] = Linter() except ImportError: pass from pkg_resources import iter_entry_points for entry in iter_entry_points('pylama.linter'): if entry.name not in LINTERS: try: LINTERS[entry.name] = entry.load()() except ImportError: pass # pylama:ignore=E0611
9f93a420842b1ee9e761e3d5a08fc3669c3f6ef7
django_classified/forms.py
django_classified/forms.py
# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', )
# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class PhoneWidget(forms.TextInput): input_type = 'phone' class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) widgets = { 'phone': PhoneWidget }
Set input type to phone for phone.
Set input type to phone for phone.
Python
mit
inoks/dcf,inoks/dcf
# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) Set input type to phone for phone.
# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class PhoneWidget(forms.TextInput): input_type = 'phone' class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) widgets = { 'phone': PhoneWidget }
<commit_before># -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) <commit_msg>Set input type to phone for phone.<commit_after>
# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class PhoneWidget(forms.TextInput): input_type = 'phone' class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) widgets = { 'phone': PhoneWidget }
# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) Set input type to phone for phone.# -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class PhoneWidget(forms.TextInput): input_type = 'phone' class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) widgets = { 'phone': PhoneWidget }
<commit_before># -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) <commit_msg>Set input type to phone for phone.<commit_after># -*- coding:utf-8 -*- from django import forms from django.utils.translation import ugettext as _ from .models import Item, Group, Profile, Area class SearchForm(forms.Form): area = forms.ModelChoiceField(label=_('Area'), queryset=Area.objects.all(), required=False) group = forms.ModelChoiceField(label=_('Group'), queryset=Group.objects.all(), required=False) q = forms.CharField(required=False, label=_('Query'),) def filter_by(self): # TODO search using more than one field # TODO split query string and make seaprate search by words filters = {} if self.cleaned_data['group']: filters['group'] = self.cleaned_data['group'] if self.cleaned_data['area']: filters['area'] = self.cleaned_data['area'] filters['description__icontains'] = self.cleaned_data['q'] return filters class ItemForm(forms.ModelForm): class Meta: model = Item fields = ( 'area', 'group', 'title', 'description', 'price', 'is_active' ) class PhoneWidget(forms.TextInput): input_type = 'phone' class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ( 'phone', ) widgets = { 'phone': PhoneWidget }
66d13005993553a849449539e6daf6551a616c4b
indra/sources/isi/__init__.py
indra/sources/isi/__init__.py
""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. For processing nxml files, install the nxml2txt utility (https://github.com/spyysalo/nxml2txt) and set the configuration variable NXML2TXT_PATH to its location. In addition, since the reader works with Python 2 only, make sure PYTHON2_PATH is set in your config file or environment and points to a Python 2 executable. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file
""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file
Remove deprecated comment about nxml2text
Remove deprecated comment about nxml2text
Python
bsd-2-clause
sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/indra,bgyori/indra,bgyori/indra,johnbachman/belpy,johnbachman/indra
""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. For processing nxml files, install the nxml2txt utility (https://github.com/spyysalo/nxml2txt) and set the configuration variable NXML2TXT_PATH to its location. In addition, since the reader works with Python 2 only, make sure PYTHON2_PATH is set in your config file or environment and points to a Python 2 executable. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file Remove deprecated comment about nxml2text
""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file
<commit_before>""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. For processing nxml files, install the nxml2txt utility (https://github.com/spyysalo/nxml2txt) and set the configuration variable NXML2TXT_PATH to its location. In addition, since the reader works with Python 2 only, make sure PYTHON2_PATH is set in your config file or environment and points to a Python 2 executable. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file <commit_msg>Remove deprecated comment about nxml2text<commit_after>
""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file
""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. For processing nxml files, install the nxml2txt utility (https://github.com/spyysalo/nxml2txt) and set the configuration variable NXML2TXT_PATH to its location. In addition, since the reader works with Python 2 only, make sure PYTHON2_PATH is set in your config file or environment and points to a Python 2 executable. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file Remove deprecated comment about nxml2text""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file
<commit_before>""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. For processing nxml files, install the nxml2txt utility (https://github.com/spyysalo/nxml2txt) and set the configuration variable NXML2TXT_PATH to its location. In addition, since the reader works with Python 2 only, make sure PYTHON2_PATH is set in your config file or environment and points to a Python 2 executable. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file <commit_msg>Remove deprecated comment about nxml2text<commit_after>""" This module provides an input interface and processor to the ISI reading system. The reader is set up to run within a Docker container. For the ISI reader to run, set the Docker memory and swap space to the maximum. """ from .api import process_text, process_nxml, process_preprocessed, \ process_output_folder, process_json_file
dadc13021684976599bed4c949d28d9ebd296eb8
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" from SublimeLinter.lint import RubyLinter class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' )
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" import os from SublimeLinter.lint import RubyLinter, util class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) def build_args(self, settings): """ Return a list of args to add to cls.cmd. We hook into this method to find the rubocop config and set it as an environment variable for the rubocop linter to pick up. """ if self.filename: config = util.find_file( os.path.dirname(self.filename), '.rubocop.yml', aux_dirs='~' ) if config: os.environ["RUBOCOP_CONFIG"] = config return super().build_args(settings)
Add functionality to find rubocop config
Add functionality to find rubocop config Once it's found, we set it as an environment variable for the rubocop linter to pick up.
Python
mit
elstgav/SublimeLinter-slim-lint
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" from SublimeLinter.lint import RubyLinter class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) Add functionality to find rubocop config Once it's found, we set it as an environment variable for the rubocop linter to pick up.
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" import os from SublimeLinter.lint import RubyLinter, util class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) def build_args(self, settings): """ Return a list of args to add to cls.cmd. We hook into this method to find the rubocop config and set it as an environment variable for the rubocop linter to pick up. """ if self.filename: config = util.find_file( os.path.dirname(self.filename), '.rubocop.yml', aux_dirs='~' ) if config: os.environ["RUBOCOP_CONFIG"] = config return super().build_args(settings)
<commit_before># # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" from SublimeLinter.lint import RubyLinter class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) <commit_msg>Add functionality to find rubocop config Once it's found, we set it as an environment variable for the rubocop linter to pick up.<commit_after>
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" import os from SublimeLinter.lint import RubyLinter, util class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) def build_args(self, settings): """ Return a list of args to add to cls.cmd. We hook into this method to find the rubocop config and set it as an environment variable for the rubocop linter to pick up. """ if self.filename: config = util.find_file( os.path.dirname(self.filename), '.rubocop.yml', aux_dirs='~' ) if config: os.environ["RUBOCOP_CONFIG"] = config return super().build_args(settings)
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" from SublimeLinter.lint import RubyLinter class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) Add functionality to find rubocop config Once it's found, we set it as an environment variable for the rubocop linter to pick up.# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" import os from SublimeLinter.lint import RubyLinter, util class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) def build_args(self, settings): """ Return a list of args to add to cls.cmd. We hook into this method to find the rubocop config and set it as an environment variable for the rubocop linter to pick up. """ if self.filename: config = util.find_file( os.path.dirname(self.filename), '.rubocop.yml', aux_dirs='~' ) if config: os.environ["RUBOCOP_CONFIG"] = config return super().build_args(settings)
<commit_before># # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" from SublimeLinter.lint import RubyLinter class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) <commit_msg>Add functionality to find rubocop config Once it's found, we set it as an environment variable for the rubocop linter to pick up.<commit_after># # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Gavin Elster # Copyright (c) 2015 Gavin Elster # # License: MIT # """This module exports the SlimLint plugin class.""" import os from SublimeLinter.lint import RubyLinter, util class SlimLint(RubyLinter): """Provides an interface to slim-lint.""" syntax = 'ruby slim' cmd = 'slim-lint' tempfile_suffix = '-' config_file = ('--config', '.slim-lint.yml', '~') version_args = '--version' version_re = r'(?P<version>\d+\.\d+\.\d+)' version_requirement = ' >= 0.4.0' regex = ( r'^.+?:(?P<line>\d+) ' r'(?:(?P<error>\[E\])|(?P<warning>\[W\])) ' r'(?P<message>[^`]*(?:`(?P<near>.+?)`)?.*)' ) def build_args(self, settings): """ Return a list of args to add to cls.cmd. We hook into this method to find the rubocop config and set it as an environment variable for the rubocop linter to pick up. """ if self.filename: config = util.find_file( os.path.dirname(self.filename), '.rubocop.yml', aux_dirs='~' ) if config: os.environ["RUBOCOP_CONFIG"] = config return super().build_args(settings)
74667c044f703355811fb8dd38c0b2c29056c943
metashare/sync/management/commands/get_resource_list.py
metashare/sync/management/commands/get_resource_list.py
from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published: print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return
from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published(): print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return
Fix to correctly check for publication status
Fix to correctly check for publication status
Python
bsd-3-clause
zeehio/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,JuliBakagianni/CEF-ELRC,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEF-ELRC,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,zeehio/META-SHARE,zeehio/META-SHARE,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEFELRC,MiltosD/CEFELRC,MiltosD/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,MiltosD/CEFELRC,MiltosD/CEFELRC
from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published: print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return Fix to correctly check for publication status
from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published(): print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return
<commit_before> from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published: print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return <commit_msg>Fix to correctly check for publication status<commit_after>
from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published(): print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return
from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published: print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return Fix to correctly check for publication status from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published(): print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return
<commit_before> from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published: print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return <commit_msg>Fix to correctly check for publication status<commit_after> from django.core.management.base import BaseCommand from metashare.repository.models import resourceInfoType_model class Command(BaseCommand): def handle(self, *args, **options): for res in resourceInfoType_model.objects.all(): sto_obj = res.storage_object if sto_obj._get_published(): print "{1}:{2}".format(res.id, sto_obj.identifier, sto_obj.digest_checksum) return
d0f67d9ac8236e83a77b84e33ba7217c7e8f67b9
bird/utils.py
bird/utils.py
def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined")
import numpy as np import os import sys import subprocess import wave import wave from scipy import signal from scipy import fft from matplotlib import pyplot as plt MLSP_DATA_PATH="/home/darksoox/gits/bird-species-classification/mlsp_contest_dataset/" def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") def play_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") else: if (sys.platform == "linux" or sys.playform == "linux2"): subprocess.call(["aplay", filename]) else: print("Platform not supported") def read_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") s = wave.open(filename, 'rb') if (s.getnchannels() != 1): raise ValueError("Wave file should be mono") if (s.getframerate() != 16000): raise ValueError("Sampling rate of wave file should be 16000") strsig = s.readframes(s.getnframes()) x = np.fromstring(strsig, np.short) fs = s.getframerate() s.close() return fs, x def wave_to_spectrogram(wave=np.array([]), fs=None, window=signal.hanning(512), nperseg=512, noverlap=256): """Given a wave form returns the spectrogram of the wave form. Keyword arguments: wave -- the wave form (default np.array([])) fs -- the rate at which the wave form has been sampled """ return signal.spectrogram(wave, fs, window, nperseg, noverlap, mode='magnitude') def wave_to_spectrogram2(S): Spectrogram = [] N = 160000 K = 512 Step = 4 wind = 0.5*(1 -np.cos(np.array(range(K))*2*np.pi/(K-1) )) for j in range(int(Step*N/K)-Step): vec = S[j * K/Step : (j+Step) * K/Step] * wind Spectrogram.append(abs(fft(vec, K)[:K/2])) return np.array(Spectrogram) def show_spectrogram(Sxx): plt.pcolor(Sxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [s]') plt.show()
Add draft of spectrogram computions.
Add draft of spectrogram computions.
Python
mit
johnmartinsson/bird-species-classification,johnmartinsson/bird-species-classification
def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") Add draft of spectrogram computions.
import numpy as np import os import sys import subprocess import wave import wave from scipy import signal from scipy import fft from matplotlib import pyplot as plt MLSP_DATA_PATH="/home/darksoox/gits/bird-species-classification/mlsp_contest_dataset/" def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") def play_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") else: if (sys.platform == "linux" or sys.playform == "linux2"): subprocess.call(["aplay", filename]) else: print("Platform not supported") def read_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") s = wave.open(filename, 'rb') if (s.getnchannels() != 1): raise ValueError("Wave file should be mono") if (s.getframerate() != 16000): raise ValueError("Sampling rate of wave file should be 16000") strsig = s.readframes(s.getnframes()) x = np.fromstring(strsig, np.short) fs = s.getframerate() s.close() return fs, x def wave_to_spectrogram(wave=np.array([]), fs=None, window=signal.hanning(512), nperseg=512, noverlap=256): """Given a wave form returns the spectrogram of the wave form. Keyword arguments: wave -- the wave form (default np.array([])) fs -- the rate at which the wave form has been sampled """ return signal.spectrogram(wave, fs, window, nperseg, noverlap, mode='magnitude') def wave_to_spectrogram2(S): Spectrogram = [] N = 160000 K = 512 Step = 4 wind = 0.5*(1 -np.cos(np.array(range(K))*2*np.pi/(K-1) )) for j in range(int(Step*N/K)-Step): vec = S[j * K/Step : (j+Step) * K/Step] * wind Spectrogram.append(abs(fft(vec, K)[:K/2])) return np.array(Spectrogram) def show_spectrogram(Sxx): plt.pcolor(Sxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [s]') plt.show()
<commit_before>def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") <commit_msg>Add draft of spectrogram computions.<commit_after>
import numpy as np import os import sys import subprocess import wave import wave from scipy import signal from scipy import fft from matplotlib import pyplot as plt MLSP_DATA_PATH="/home/darksoox/gits/bird-species-classification/mlsp_contest_dataset/" def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") def play_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") else: if (sys.platform == "linux" or sys.playform == "linux2"): subprocess.call(["aplay", filename]) else: print("Platform not supported") def read_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") s = wave.open(filename, 'rb') if (s.getnchannels() != 1): raise ValueError("Wave file should be mono") if (s.getframerate() != 16000): raise ValueError("Sampling rate of wave file should be 16000") strsig = s.readframes(s.getnframes()) x = np.fromstring(strsig, np.short) fs = s.getframerate() s.close() return fs, x def wave_to_spectrogram(wave=np.array([]), fs=None, window=signal.hanning(512), nperseg=512, noverlap=256): """Given a wave form returns the spectrogram of the wave form. Keyword arguments: wave -- the wave form (default np.array([])) fs -- the rate at which the wave form has been sampled """ return signal.spectrogram(wave, fs, window, nperseg, noverlap, mode='magnitude') def wave_to_spectrogram2(S): Spectrogram = [] N = 160000 K = 512 Step = 4 wind = 0.5*(1 -np.cos(np.array(range(K))*2*np.pi/(K-1) )) for j in range(int(Step*N/K)-Step): vec = S[j * K/Step : (j+Step) * K/Step] * wind Spectrogram.append(abs(fft(vec, K)[:K/2])) return np.array(Spectrogram) def show_spectrogram(Sxx): plt.pcolor(Sxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [s]') plt.show()
def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") Add draft of spectrogram computions.import numpy as np import os import sys import subprocess import wave import wave from scipy import signal from scipy import fft from matplotlib import pyplot as plt MLSP_DATA_PATH="/home/darksoox/gits/bird-species-classification/mlsp_contest_dataset/" def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") def play_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") else: if (sys.platform == "linux" or sys.playform == "linux2"): subprocess.call(["aplay", filename]) else: print("Platform not supported") def read_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") s = wave.open(filename, 'rb') if (s.getnchannels() != 1): raise ValueError("Wave file should be mono") if (s.getframerate() != 16000): raise ValueError("Sampling rate of wave file should be 16000") strsig = s.readframes(s.getnframes()) x = np.fromstring(strsig, np.short) fs = s.getframerate() s.close() return fs, x def wave_to_spectrogram(wave=np.array([]), fs=None, window=signal.hanning(512), nperseg=512, noverlap=256): """Given a wave form returns the spectrogram of the wave form. Keyword arguments: wave -- the wave form (default np.array([])) fs -- the rate at which the wave form has been sampled """ return signal.spectrogram(wave, fs, window, nperseg, noverlap, mode='magnitude') def wave_to_spectrogram2(S): Spectrogram = [] N = 160000 K = 512 Step = 4 wind = 0.5*(1 -np.cos(np.array(range(K))*2*np.pi/(K-1) )) for j in range(int(Step*N/K)-Step): vec = S[j * K/Step : (j+Step) * K/Step] * wind Spectrogram.append(abs(fft(vec, K)[:K/2])) return np.array(Spectrogram) def show_spectrogram(Sxx): plt.pcolor(Sxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [s]') plt.show()
<commit_before>def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") <commit_msg>Add draft of spectrogram computions.<commit_after>import numpy as np import os import sys import subprocess import wave import wave from scipy import signal from scipy import fft from matplotlib import pyplot as plt MLSP_DATA_PATH="/home/darksoox/gits/bird-species-classification/mlsp_contest_dataset/" def noise_mask(spectrogram): print("noise_mask is undefined") def structure_mask(spectrogram): print("structure_mask is undefined") def extract_signal(mask, spectrogram): print("extract_signal is undefined") def play_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") else: if (sys.platform == "linux" or sys.playform == "linux2"): subprocess.call(["aplay", filename]) else: print("Platform not supported") def read_wave_file(filename): if (not os.path.isfile(filename)): raise ValueError("File does not exist") s = wave.open(filename, 'rb') if (s.getnchannels() != 1): raise ValueError("Wave file should be mono") if (s.getframerate() != 16000): raise ValueError("Sampling rate of wave file should be 16000") strsig = s.readframes(s.getnframes()) x = np.fromstring(strsig, np.short) fs = s.getframerate() s.close() return fs, x def wave_to_spectrogram(wave=np.array([]), fs=None, window=signal.hanning(512), nperseg=512, noverlap=256): """Given a wave form returns the spectrogram of the wave form. Keyword arguments: wave -- the wave form (default np.array([])) fs -- the rate at which the wave form has been sampled """ return signal.spectrogram(wave, fs, window, nperseg, noverlap, mode='magnitude') def wave_to_spectrogram2(S): Spectrogram = [] N = 160000 K = 512 Step = 4 wind = 0.5*(1 -np.cos(np.array(range(K))*2*np.pi/(K-1) )) for j in range(int(Step*N/K)-Step): vec = S[j * K/Step : (j+Step) * K/Step] * wind Spectrogram.append(abs(fft(vec, K)[:K/2])) return np.array(Spectrogram) def show_spectrogram(Sxx): plt.pcolor(Sxx) plt.ylabel('Frequency [Hz]') plt.xlabel('Time [s]') plt.show()
09b5a3f531a3d0498aae21f2c8014b77df5f8d41
version.py
version.py
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/dist_build/manifest.json', 'src/chrome/app/dev_build/manifest.json', 'src/chrome/extension/dist_build/manifest.json', 'src/chrome/extension/dev_build/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/manifest.json', 'src/chrome/extension/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
Update manifest files being bumped.
Update manifest files being bumped.
Python
apache-2.0
itplanes/uproxy,chinarustin/uproxy,uProxy/uproxy,dhkong88/uproxy,dhkong88/uproxy,MinFu/uproxy,itplanes/uproxy,jpevarnek/uproxy,dhkong88/uproxy,jpevarnek/uproxy,chinarustin/uproxy,roceys/uproxy,roceys/uproxy,dhkong88/uproxy,uProxy/uproxy,uProxy/uproxy,qida/uproxy,chinarustin/uproxy,roceys/uproxy,chinarustin/uproxy,MinFu/uproxy,itplanes/uproxy,uProxy/uproxy,qida/uproxy,uProxy/uproxy,jpevarnek/uproxy,itplanes/uproxy,dhkong88/uproxy,MinFu/uproxy,chinarustin/uproxy,qida/uproxy,roceys/uproxy,MinFu/uproxy,qida/uproxy,jpevarnek/uproxy,roceys/uproxy,jpevarnek/uproxy,itplanes/uproxy,MinFu/uproxy,qida/uproxy
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/dist_build/manifest.json', 'src/chrome/app/dev_build/manifest.json', 'src/chrome/extension/dist_build/manifest.json', 'src/chrome/extension/dev_build/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n'); Update manifest files being bumped.
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/manifest.json', 'src/chrome/extension/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
<commit_before># Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/dist_build/manifest.json', 'src/chrome/app/dev_build/manifest.json', 'src/chrome/extension/dist_build/manifest.json', 'src/chrome/extension/dev_build/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n'); <commit_msg>Update manifest files being bumped.<commit_after>
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/manifest.json', 'src/chrome/extension/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/dist_build/manifest.json', 'src/chrome/app/dev_build/manifest.json', 'src/chrome/extension/dist_build/manifest.json', 'src/chrome/extension/dev_build/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n'); Update manifest files being bumped.# Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/manifest.json', 'src/chrome/extension/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
<commit_before># Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/dist_build/manifest.json', 'src/chrome/app/dev_build/manifest.json', 'src/chrome/extension/dist_build/manifest.json', 'src/chrome/extension/dev_build/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n'); <commit_msg>Update manifest files being bumped.<commit_after># Update uProxy version in all relevant places. # # Run with: # python version.py <new version> # e.g. python version.py 0.8.10 import json import collections import sys import re manifest_files = [ 'src/chrome/app/manifest.json', 'src/chrome/extension/manifest.json', 'src/firefox/package.json', 'package.json', 'bower.json', ] validVersion = re.match('[0-9]+\.[0-9]+\.[0-9]+', sys.argv[1]) if validVersion == None: print 'Please enter a valid version number.' sys.exit() for filename in manifest_files: print filename with open(filename) as manifest: manifest_data = json.load(manifest, object_pairs_hook=collections.OrderedDict) manifest_data['version'] = sys.argv[1] with open(filename, 'w') as dist_manifest: json.dump(manifest_data, dist_manifest, indent=2, separators=(',', ': ')) dist_manifest.write('\n');
b022b2f017ed102d8e194427b92dce8cdc8918f9
manage.py
manage.py
#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run()
#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() To start Varda server: manage.py celeryd manage.py runserver """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run()
Add note on Varda server start
Add note on Varda server start
Python
mit
varda/varda,sndrtj/varda
#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run() Add note on Varda server start
#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() To start Varda server: manage.py celeryd manage.py runserver """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run() <commit_msg>Add note on Varda server start<commit_after>
#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() To start Varda server: manage.py celeryd manage.py runserver """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run()
#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run() Add note on Varda server start#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() To start Varda server: manage.py celeryd manage.py runserver """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run()
<commit_before>#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run() <commit_msg>Add note on Varda server start<commit_after>#!/usr/bin/env python """ Run the Varda REST server. To setup the database: create database varda; create database vardacelery; create database vardaresults; grant all privileges on varda.* to varda@localhost identified by 'varda'; grant all privileges on vardacelery.* to varda@localhost identified by 'varda'; grant all privileges on vardaresults.* to varda@localhost identified by 'varda'; To reset the database: from varda import db db.drop_all() db.create_all() To start Varda server: manage.py celeryd manage.py runserver """ from flaskext.script import Manager from flaskext.celery import install_commands as install_celery_commands from varda import app, db manager = Manager(app) install_celery_commands(manager) @manager.command def createdb(): """ Create the SQLAlchemy database. """ db.drop_all() db.create_all() if __name__ == '__main__': manager.run()
50130fa011104806cc66331fe5a6ebc3f98c9d5c
vistrails/packages/tej/widgets.py
vistrails/packages/tej/widgets.py
from __future__ import division from PyQt4 import QtGui from vistrails.gui.modules.source_configure import SourceConfigurationWidget class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, QtGui.QTextEdit, has_inputs=False, has_outputs=False, parent=parent)
from __future__ import division from vistrails.gui.modules.source_configure import SourceConfigurationWidget from vistrails.gui.modules.string_configure import TextEditor class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, TextEditor, has_inputs=False, has_outputs=False, parent=parent)
Use smart text editor in tej.SubmitShellJob
Use smart text editor in tej.SubmitShellJob
Python
bsd-3-clause
minesense/VisTrails,VisTrails/VisTrails,hjanime/VisTrails,hjanime/VisTrails,hjanime/VisTrails,minesense/VisTrails,VisTrails/VisTrails,hjanime/VisTrails,minesense/VisTrails,VisTrails/VisTrails,VisTrails/VisTrails,minesense/VisTrails,minesense/VisTrails,hjanime/VisTrails,VisTrails/VisTrails
from __future__ import division from PyQt4 import QtGui from vistrails.gui.modules.source_configure import SourceConfigurationWidget class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, QtGui.QTextEdit, has_inputs=False, has_outputs=False, parent=parent) Use smart text editor in tej.SubmitShellJob
from __future__ import division from vistrails.gui.modules.source_configure import SourceConfigurationWidget from vistrails.gui.modules.string_configure import TextEditor class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, TextEditor, has_inputs=False, has_outputs=False, parent=parent)
<commit_before>from __future__ import division from PyQt4 import QtGui from vistrails.gui.modules.source_configure import SourceConfigurationWidget class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, QtGui.QTextEdit, has_inputs=False, has_outputs=False, parent=parent) <commit_msg>Use smart text editor in tej.SubmitShellJob<commit_after>
from __future__ import division from vistrails.gui.modules.source_configure import SourceConfigurationWidget from vistrails.gui.modules.string_configure import TextEditor class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, TextEditor, has_inputs=False, has_outputs=False, parent=parent)
from __future__ import division from PyQt4 import QtGui from vistrails.gui.modules.source_configure import SourceConfigurationWidget class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, QtGui.QTextEdit, has_inputs=False, has_outputs=False, parent=parent) Use smart text editor in tej.SubmitShellJobfrom __future__ import division from vistrails.gui.modules.source_configure import SourceConfigurationWidget from vistrails.gui.modules.string_configure import TextEditor class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, TextEditor, has_inputs=False, has_outputs=False, parent=parent)
<commit_before>from __future__ import division from PyQt4 import QtGui from vistrails.gui.modules.source_configure import SourceConfigurationWidget class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, QtGui.QTextEdit, has_inputs=False, has_outputs=False, parent=parent) <commit_msg>Use smart text editor in tej.SubmitShellJob<commit_after>from __future__ import division from vistrails.gui.modules.source_configure import SourceConfigurationWidget from vistrails.gui.modules.string_configure import TextEditor class ShellSourceConfigurationWidget(SourceConfigurationWidget): """Configuration widget for SubmitShellJob. Allows the user to edit a shell script that will be run on the server. """ def __init__(self, module, controller, parent=None): SourceConfigurationWidget.__init__(self, module, controller, TextEditor, has_inputs=False, has_outputs=False, parent=parent)
09c24ac93b6e697b48c52b614fe92f7978fe2320
linter.py
linter.py
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", # @see https://iverilog.fandom.com/wiki/Iverilog_Flags "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
Add iverilog flags reference URL
Add iverilog flags reference URL Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
Python
mit
jfcherng/SublimeLinter-contrib-iverilog,jfcherng/SublimeLinter-contrib-iverilog
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) ) Add iverilog flags reference URL Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com>
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", # @see https://iverilog.fandom.com/wiki/Iverilog_Flags "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
<commit_before># # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) ) <commit_msg>Add iverilog flags reference URL Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com><commit_after>
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", # @see https://iverilog.fandom.com/wiki/Iverilog_Flags "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
# # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) ) Add iverilog flags reference URL Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com># # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", # @see https://iverilog.fandom.com/wiki/Iverilog_Flags "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
<commit_before># # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) ) <commit_msg>Add iverilog flags reference URL Signed-off-by: Jack Cherng <159f0f32a62cc912ca55f89bb5e06807cf019bc7@gmail.com><commit_after># # linter.py # Linter for SublimeLinter4, a code checking framework for Sublime Text 3 # # Written by Jack Cherng # Copyright (c) 2017-2019 jfcherng # # License: MIT # from SublimeLinter.lint import Linter import sublime class Iverilog(Linter): # http://www.sublimelinter.com/en/stable/linter_attributes.html name = "iverilog" cmd = "iverilog ${args}" tempfile_suffix = "verilog" multiline = True on_stderr = None # fmt: off defaults = { "selector": "source.verilog | source.systemverilog", # @see https://iverilog.fandom.com/wiki/Iverilog_Flags "-t": "null", "-g": 2012, "-I +": [], "-y +": [], } # fmt: on # there is a ":" in the filepath under Windows like C:\DIR\FILE if sublime.platform() == "windows": filepath_regex = r"[^:]+:[^:]+" else: filepath_regex = r"[^:]+" # what kind of messages should be caught? regex = ( r"(?P<file>{0}):(?P<line>\d+):\s*" r"(?:(?:(?P<warning>warning)|(?P<error>error)):)?\s*" r"(?P<message>.*)".format(filepath_regex) )
db41b744b4fea9d16ad53cb7915ddee5ddcffed0
scheduler.py
scheduler.py
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
Revert "Re-raise even when capturing by Sentry"
Revert "Re-raise even when capturing by Sentry" This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.
Python
apache-2.0
randsleadershipslack/destalinator,royrapoport/destalinator,royrapoport/destalinator,randsleadershipslack/destalinator,TheConnMan/destalinator,TheConnMan/destalinator
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start() Revert "Re-raise even when capturing by Sentry" This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
<commit_before>import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start() <commit_msg>Revert "Re-raise even when capturing by Sentry" This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.<commit_after>
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start() Revert "Re-raise even when capturing by Sentry" This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
<commit_before>import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start() <commit_msg>Revert "Re-raise even when capturing by Sentry" This reverts commit 3fe290fe02390e79910e7ded87070d6e03a705a5.<commit_after>import logging import os from apscheduler.schedulers.blocking import BlockingScheduler from raven.base import Client as RavenClient import warner import archiver import announcer import flagger raven_client = RavenClient() logger = logging.getLogger(__name__) # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: schedule_kwargs = {"hour": 4} sched = BlockingScheduler() @sched.scheduled_job("cron", **schedule_kwargs) def destalinate_job(): logger.info("Destalinating") if "SB_TOKEN" not in os.environ or "API_TOKEN" not in os.environ: logger.error("Missing at least one Slack environment variable.") else: try: warner.Warner().warn() archiver.Archiver().archive() announcer.Announcer().announce() flagger.Flagger().flag() logger.info("OK: destalinated") except Exception as e: # pylint: disable=W0703 raven_client.captureException() if not os.getenv('SENTRY_DSN'): raise e logger.info("END: destalinate_job") if __name__ == "__main__": sched.start()
11f758dc6c4ee3b64d47ac133c4b7f57cd4fc25b
contrib/performance/report.py
contrib/performance/report.py
import sys, pickle def main(): statistics = pickle.load(file(sys.argv[1])) if len(sys.argv) == 2: print 'Available benchmarks' print '\t' + '\n\t'.join(statistics.keys()) return statistics = statistics[sys.argv[2]] if len(sys.argv) == 3: print 'Available parameters' print '\t' + '\n\t'.join(map(str, statistics.keys())) return statistics = statistics[int(sys.argv[3])] if len(sys.argv) == 4: print 'Available statistics' print '\t' + '\n\t'.join([s.name for s in statistics]) return for stat in statistics: if stat.name == sys.argv[4]: samples = statistics[stat] break if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) return getattr(stat, sys.argv[5])(samples)
import sys, pickle from benchlib import select def main(): if len(sys.argv) < 5: print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],) else: stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5]) if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) else: getattr(stat, sys.argv[5])(samples)
Use stats.select() instead of re-implementing all of this.
Use stats.select() instead of re-implementing all of this. This is preparation for being able to squash statistics in different ways. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6563 e27351fd-9f3e-4f54-a53b-843176b1656c
Python
apache-2.0
trevor/calendarserver,trevor/calendarserver,trevor/calendarserver
import sys, pickle def main(): statistics = pickle.load(file(sys.argv[1])) if len(sys.argv) == 2: print 'Available benchmarks' print '\t' + '\n\t'.join(statistics.keys()) return statistics = statistics[sys.argv[2]] if len(sys.argv) == 3: print 'Available parameters' print '\t' + '\n\t'.join(map(str, statistics.keys())) return statistics = statistics[int(sys.argv[3])] if len(sys.argv) == 4: print 'Available statistics' print '\t' + '\n\t'.join([s.name for s in statistics]) return for stat in statistics: if stat.name == sys.argv[4]: samples = statistics[stat] break if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) return getattr(stat, sys.argv[5])(samples) Use stats.select() instead of re-implementing all of this. This is preparation for being able to squash statistics in different ways. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6563 e27351fd-9f3e-4f54-a53b-843176b1656c
import sys, pickle from benchlib import select def main(): if len(sys.argv) < 5: print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],) else: stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5]) if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) else: getattr(stat, sys.argv[5])(samples)
<commit_before>import sys, pickle def main(): statistics = pickle.load(file(sys.argv[1])) if len(sys.argv) == 2: print 'Available benchmarks' print '\t' + '\n\t'.join(statistics.keys()) return statistics = statistics[sys.argv[2]] if len(sys.argv) == 3: print 'Available parameters' print '\t' + '\n\t'.join(map(str, statistics.keys())) return statistics = statistics[int(sys.argv[3])] if len(sys.argv) == 4: print 'Available statistics' print '\t' + '\n\t'.join([s.name for s in statistics]) return for stat in statistics: if stat.name == sys.argv[4]: samples = statistics[stat] break if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) return getattr(stat, sys.argv[5])(samples) <commit_msg>Use stats.select() instead of re-implementing all of this. This is preparation for being able to squash statistics in different ways. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6563 e27351fd-9f3e-4f54-a53b-843176b1656c<commit_after>
import sys, pickle from benchlib import select def main(): if len(sys.argv) < 5: print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],) else: stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5]) if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) else: getattr(stat, sys.argv[5])(samples)
import sys, pickle def main(): statistics = pickle.load(file(sys.argv[1])) if len(sys.argv) == 2: print 'Available benchmarks' print '\t' + '\n\t'.join(statistics.keys()) return statistics = statistics[sys.argv[2]] if len(sys.argv) == 3: print 'Available parameters' print '\t' + '\n\t'.join(map(str, statistics.keys())) return statistics = statistics[int(sys.argv[3])] if len(sys.argv) == 4: print 'Available statistics' print '\t' + '\n\t'.join([s.name for s in statistics]) return for stat in statistics: if stat.name == sys.argv[4]: samples = statistics[stat] break if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) return getattr(stat, sys.argv[5])(samples) Use stats.select() instead of re-implementing all of this. This is preparation for being able to squash statistics in different ways. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6563 e27351fd-9f3e-4f54-a53b-843176b1656cimport sys, pickle from benchlib import select def main(): if len(sys.argv) < 5: print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],) else: stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5]) if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) else: getattr(stat, sys.argv[5])(samples)
<commit_before>import sys, pickle def main(): statistics = pickle.load(file(sys.argv[1])) if len(sys.argv) == 2: print 'Available benchmarks' print '\t' + '\n\t'.join(statistics.keys()) return statistics = statistics[sys.argv[2]] if len(sys.argv) == 3: print 'Available parameters' print '\t' + '\n\t'.join(map(str, statistics.keys())) return statistics = statistics[int(sys.argv[3])] if len(sys.argv) == 4: print 'Available statistics' print '\t' + '\n\t'.join([s.name for s in statistics]) return for stat in statistics: if stat.name == sys.argv[4]: samples = statistics[stat] break if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) return getattr(stat, sys.argv[5])(samples) <commit_msg>Use stats.select() instead of re-implementing all of this. This is preparation for being able to squash statistics in different ways. git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6563 e27351fd-9f3e-4f54-a53b-843176b1656c<commit_after>import sys, pickle from benchlib import select def main(): if len(sys.argv) < 5: print 'Usage: %s <datafile> <benchmark name> <parameter value> <metric> [command]' % (sys.argv[0],) else: stat, samples = select(pickle.load(file(sys.argv[1])), *sys.argv[2:5]) if len(sys.argv) == 5: print 'Samples' print '\t' + '\n\t'.join(map(str, samples)) print 'Commands' print '\t' + '\n\t'.join(stat.commands) else: getattr(stat, sys.argv[5])(samples)
76f0e242341aba7ce57f50d3d13f2e0da1dcb750
cycli/buffer.py
cycli/buffer.py
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text == "quit", text == "exit" ] )
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text.endswith("\n"), text == "quit", text == "exit", ] )
Allow double return to execute query
Allow double return to execute query If there’s a double return the text will end with “\n”. Closes #5.
Python
mit
nicolewhite/cycli,nicolewhite/cycli,ikwattro/cycli
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text == "quit", text == "exit" ] )Allow double return to execute query If there’s a double return the text will end with “\n”. Closes #5.
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text.endswith("\n"), text == "quit", text == "exit", ] )
<commit_before>from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text == "quit", text == "exit" ] )<commit_msg>Allow double return to execute query If there’s a double return the text will end with “\n”. Closes #5.<commit_after>
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text.endswith("\n"), text == "quit", text == "exit", ] )
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text == "quit", text == "exit" ] )Allow double return to execute query If there’s a double return the text will end with “\n”. Closes #5.from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text.endswith("\n"), text == "quit", text == "exit", ] )
<commit_before>from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text == "quit", text == "exit" ] )<commit_msg>Allow double return to execute query If there’s a double return the text will end with “\n”. Closes #5.<commit_after>from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CypherBuffer(Buffer): def __init__(self, *args, **kwargs): @Condition def is_multiline(): text = self.document.text return not self.user_wants_out(text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, **kwargs) def user_wants_out(self, text): return any( [ text.endswith(";"), text.endswith("\n"), text == "quit", text == "exit", ] )
746c3a55b5935199a293f05d042c0029029d970a
planetstack/openstack_observer/steps/sync_images.py
planetstack/openstack_observer/steps/sync_images.py
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
Check the existence of the images_path
Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org>
Python
apache-2.0
open-cloud/xos,cboling/xos,opencord/xos,cboling/xos,zdw/xos,open-cloud/xos,opencord/xos,zdw/xos,cboling/xos,cboling/xos,cboling/xos,zdw/xos,open-cloud/xos,zdw/xos,opencord/xos
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org>
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
<commit_before>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() <commit_msg>Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org><commit_after>
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
<commit_before>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} for f in os.listdir(images_path): if os.path.isfile(os.path.join(images_path ,f)): available_images[f] = os.path.join(images_path ,f) images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save() <commit_msg>Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) File "/opt/xos/observer/openstacksyncstep.py", line 14, in __call__ return self.call(**args) File "/opt/xos/observer/syncstep.py", line 97, in call pending = self.fetch_pending(deletion) File "/opt/xos/observer/steps/sync_images.py", line 22, in fetch_pending for f in os.listdir(images_path): OSError: [Errno 2] No such file or directory: '/opt/xos/images' ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' END TRACEBACK Signed-off-by: S.Çağlar Onur <acf5ae661bb0a9f738c88a741b1d35ac69ab5408@10ur.org><commit_after>import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted): # Images come from the back end # You can't delete them if (deleted): return [] # get list of images on disk images_path = Config().observer_images_directory available_images = {} if os.path.exists(images_path): for f in os.listdir(images_path): filename = os.path.join(images_path, f) if os.path.isfile(filename): available_images[f] = filename images = Image.objects.all() image_names = [image.name for image in images] for image_name in available_images: #remove file extension clean_name = ".".join(image_name.split('.')[:-1]) if clean_name not in image_names: image = Image(name=clean_name, disk_format='raw', container_format='bare', path = available_images[image_name]) image.save() return Image.objects.filter(Q(enacted__lt=F('updated')) | Q(enacted=None)) def sync_record(self, image): image.save()
22de2eb4263de87f93f243af8200029e08da37db
tests/test_cli_bands.py
tests/test_cli_bands.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0, atol=1e-10)
Add absolute tolerance to allclose test
Add absolute tolerance to allclose test
Python
apache-2.0
Z2PackDev/TBmodels,Z2PackDev/TBmodels
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0) Add absolute tolerance to allclose test
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0, atol=1e-10)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0) <commit_msg>Add absolute tolerance to allclose test<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0, atol=1e-10)
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0) Add absolute tolerance to allclose test#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0, atol=1e-10)
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0) <commit_msg>Add absolute tolerance to allclose test<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Dominik Gresch <greschd@gmx.ch> import os import pytest import tempfile import numpy as np import bandstructure_utils as bs from click.testing import CliRunner import tbmodels from tbmodels._cli import cli from parameters import SAMPLES_DIR def test_cli_bands(): samples_dir = os.path.join(SAMPLES_DIR, 'cli_bands') runner = CliRunner() with tempfile.NamedTemporaryFile() as out_file: run = runner.invoke( cli, [ 'bands', '-o', out_file.name, '-k', os.path.join(samples_dir, 'kpoints.hdf5'), '-i', os.path.join(samples_dir, 'silicon_model.hdf5') ], catch_exceptions=False ) print(run.output) res = bs.io.load(out_file.name) reference = bs.io.load(os.path.join(samples_dir, 'silicon_bands.hdf5')) np.testing.assert_allclose(bs.compare.difference(res, reference), 0, atol=1e-10)
2c8077039573296ecbc31ba9b7c5d6463cf39124
cmakelists_parsing/parsing.py
cmakelists_parsing/parsing.py
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')' class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(str(tree).encode(ENCODING)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh, p.endl class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')', p.endl class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(compose(tree).encode(ENCODING)) if __name__ == '__main__': main()
Fix up output by including endls.
Fix up output by including endls.
Python
apache-2.0
wjwwood/parse_cmake,ijt/cmakelists_parsing
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')' class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(str(tree).encode(ENCODING)) if __name__ == '__main__': main() Fix up output by including endls.
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh, p.endl class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')', p.endl class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(compose(tree).encode(ENCODING)) if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')' class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(str(tree).encode(ENCODING)) if __name__ == '__main__': main() <commit_msg>Fix up output by including endls.<commit_after>
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh, p.endl class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')', p.endl class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(compose(tree).encode(ENCODING)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')' class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(str(tree).encode(ENCODING)) if __name__ == '__main__': main() Fix up output by including endls.# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh, p.endl class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')', p.endl class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(compose(tree).encode(ENCODING)) if __name__ == '__main__': main()
<commit_before># -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')' class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(str(tree).encode(ENCODING)) if __name__ == '__main__': main() <commit_msg>Fix up output by including endls.<commit_after># -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh, p.endl class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')', p.endl class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(compose(tree).encode(ENCODING)) if __name__ == '__main__': main()
050319a4a5257b8f98d5dfcb1651b6b6f50a5b98
pysqli/core/__init__.py
pysqli/core/__init__.py
#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'plugin', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ]
#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ]
Fix a regression inserted previously.
Fix a regression inserted previously.
Python
mit
sysdream/pysqli,sysdream/pysqli
#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'plugin', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ] Fix a regression inserted previously.
#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ]
<commit_before>#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'plugin', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ] <commit_msg>Fix a regression inserted previously.<commit_after>
#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ]
#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'plugin', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ] Fix a regression inserted previously.#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ]
<commit_before>#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'plugin', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ] <commit_msg>Fix a regression inserted previously.<commit_after>#-*- coding:utf-8 -*- ## @package Core # Core module contains everything required to SQLinject. # @author Damien "virtualabs" Cauquil <virtualabs@gmail.com> from context import Context, InbandContext, BlindContext from dbms import DBMS, allow, dbms from injector import GetInjector, PostInjector, CookieInjector, UserAgentInjector, CmdInjector, ContextBasedInjector from forge import SQLForge from wrappers import DatabaseWrapper, TableWrapper, FieldWrapper from triggers import StatusTrigger, RegexpTrigger, Trigger __all__ = [ 'InbandContext', 'BlindContext', 'Context', 'DBMS', 'allow', 'GetInjector', 'PostInjector', 'CookieInjector', 'UserAgentInjector', 'CmdInjector', 'SQLForge', 'DatabaseWrapper', 'TableWrapper', 'FieldWrapper', 'Trigger', 'RegexpTrigger', 'StatusTrigger', ]
5a531923246f15dc42d690fb6b2b4fa4322891e2
examples/status_watcher.py
examples/status_watcher.py
import logging from flist import account_login, start_chat, opcode import asyncio logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) logger.info("Starting chat.") chat = await start_chat(character) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) from sys import argv coroutine = connect(argv[1], argv[2], argv[3]) asyncio.get_event_loop().run_until_complete(coroutine)
import logging from flist import account_login, start_chat, opcode import asyncio from sys import argv logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) chat = await start_chat(character) return chat async def status_logger(): logger.info("Starting chat.") chat = await connect(argv[1], argv[2], argv[3]) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) asyncio.get_event_loop().run_until_complete(status_logger())
Simplify main method, wait until status logger completes
Simplify main method, wait until status logger completes Hint: It never will.
Python
bsd-2-clause
StormyDragon/python-flist
import logging from flist import account_login, start_chat, opcode import asyncio logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) logger.info("Starting chat.") chat = await start_chat(character) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) from sys import argv coroutine = connect(argv[1], argv[2], argv[3]) asyncio.get_event_loop().run_until_complete(coroutine) Simplify main method, wait until status logger completes Hint: It never will.
import logging from flist import account_login, start_chat, opcode import asyncio from sys import argv logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) chat = await start_chat(character) return chat async def status_logger(): logger.info("Starting chat.") chat = await connect(argv[1], argv[2], argv[3]) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) asyncio.get_event_loop().run_until_complete(status_logger())
<commit_before>import logging from flist import account_login, start_chat, opcode import asyncio logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) logger.info("Starting chat.") chat = await start_chat(character) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) from sys import argv coroutine = connect(argv[1], argv[2], argv[3]) asyncio.get_event_loop().run_until_complete(coroutine) <commit_msg>Simplify main method, wait until status logger completes Hint: It never will.<commit_after>
import logging from flist import account_login, start_chat, opcode import asyncio from sys import argv logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) chat = await start_chat(character) return chat async def status_logger(): logger.info("Starting chat.") chat = await connect(argv[1], argv[2], argv[3]) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) asyncio.get_event_loop().run_until_complete(status_logger())
import logging from flist import account_login, start_chat, opcode import asyncio logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) logger.info("Starting chat.") chat = await start_chat(character) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) from sys import argv coroutine = connect(argv[1], argv[2], argv[3]) asyncio.get_event_loop().run_until_complete(coroutine) Simplify main method, wait until status logger completes Hint: It never will.import logging from flist import account_login, start_chat, opcode import asyncio from sys import argv logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) chat = await start_chat(character) return chat async def status_logger(): logger.info("Starting chat.") chat = await connect(argv[1], argv[2], argv[3]) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) asyncio.get_event_loop().run_until_complete(status_logger())
<commit_before>import logging from flist import account_login, start_chat, opcode import asyncio logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) logger.info("Starting chat.") chat = await start_chat(character) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) from sys import argv coroutine = connect(argv[1], argv[2], argv[3]) asyncio.get_event_loop().run_until_complete(coroutine) <commit_msg>Simplify main method, wait until status logger completes Hint: It never will.<commit_after>import logging from flist import account_login, start_chat, opcode import asyncio from sys import argv logger = logging.getLogger('status_watcher') logging.getLogger('').setLevel('DEBUG') async def log_status_async(status_provider): async for message in status_provider: logger.info("%(character)s is %(status)s: %(statusmsg)s", message) async def connect(account, password, character_name): account = await account_login(account, password) character = account.get_character(character_name) chat = await start_chat(character) return chat async def status_logger(): logger.info("Starting chat.") chat = await connect(argv[1], argv[2], argv[3]) logger.info("Attaching log_status method.") status_provider = chat.watch(opcode.STATUS) await log_status_async(status_provider) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logger.setLevel(logging.INFO) asyncio.get_event_loop().run_until_complete(status_logger())
bb5f027fa6573c913d90fa91d9920b40d48fbe62
flask-app/nickITAPI/app.py
flask-app/nickITAPI/app.py
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/<id>') def example(id=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/search/<query>') def example(query=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
Add query capture in flask.
Add query capture in flask.
Python
mit
cthit/nickIT,cthit/nickIT,cthit/nickIT
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/<id>') def example(id=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp Add query capture in flask.
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/search/<query>') def example(query=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
<commit_before>from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/<id>') def example(id=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp <commit_msg>Add query capture in flask.<commit_after>
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/search/<query>') def example(query=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/<id>') def example(id=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp Add query capture in flask.from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/search/<query>') def example(query=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
<commit_before>from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/<id>') def example(id=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp <commit_msg>Add query capture in flask.<commit_after>from flask import Flask, Response app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' @app.route('/search/<query>') def example(query=None): resp = Response(id) resp.headers['Access-Control-Allow-Origin'] = 'http://localhost:3000' return resp
ed64d0611ccf047c1da8ae85d13c89c77dfe1930
packages/grid/backend/grid/tests/utils/auth.py
packages/grid/backend/grid/tests/utils/auth.py
# stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="info@openmined.org", password="changethis" )
# stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "info@openmined.org" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
ADD constant test variables OWNER_EMAIL / OWNER_PWD
ADD constant test variables OWNER_EMAIL / OWNER_PWD
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
# stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="info@openmined.org", password="changethis" ) ADD constant test variables OWNER_EMAIL / OWNER_PWD
# stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "info@openmined.org" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
<commit_before># stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="info@openmined.org", password="changethis" ) <commit_msg>ADD constant test variables OWNER_EMAIL / OWNER_PWD<commit_after>
# stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "info@openmined.org" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
# stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="info@openmined.org", password="changethis" ) ADD constant test variables OWNER_EMAIL / OWNER_PWD# stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "info@openmined.org" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
<commit_before># stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email="info@openmined.org", password="changethis" ) <commit_msg>ADD constant test variables OWNER_EMAIL / OWNER_PWD<commit_after># stdlib from typing import Dict # third party from fastapi import FastAPI from httpx import AsyncClient OWNER_EMAIL = "info@openmined.org" OWNER_PWD = "changethis" async def authenticate_user( app: FastAPI, client: AsyncClient, email: str, password: str ) -> Dict[str, str]: user_login = {"email": email, "password": password} res = await client.post(app.url_path_for("login"), json=user_login) res = res.json() auth_token = res["access_token"] return {"Authorization": f"Bearer {auth_token}"} async def authenticate_owner(app: FastAPI, client: AsyncClient) -> Dict[str, str]: return await authenticate_user( app, client, email=OWNER_EMAIL, password=OWNER_PWD, )
fb3a0db023161fbf5b08147dfac1b56989918bf6
tvseries/core/models.py
tvseries/core/models.py
from tvseries.ext import db class TVSerie(db.Model): __table_args__ = {'sqlite_autoincrement': True} id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number)
from tvseries.ext import db class TVSerie(db.Model): id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number)
Remove autoincrement sqlite paramether from model
Remove autoincrement sqlite paramether from model
Python
mit
rafaelhenrique/flask_tutorial,python-sorocaba/flask_tutorial,python-sorocaba/flask_tutorial,rafaelhenrique/flask_tutorial,python-sorocaba/flask_tutorial
from tvseries.ext import db class TVSerie(db.Model): __table_args__ = {'sqlite_autoincrement': True} id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number) Remove autoincrement sqlite paramether from model
from tvseries.ext import db class TVSerie(db.Model): id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number)
<commit_before>from tvseries.ext import db class TVSerie(db.Model): __table_args__ = {'sqlite_autoincrement': True} id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number) <commit_msg>Remove autoincrement sqlite paramether from model<commit_after>
from tvseries.ext import db class TVSerie(db.Model): id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number)
from tvseries.ext import db class TVSerie(db.Model): __table_args__ = {'sqlite_autoincrement': True} id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number) Remove autoincrement sqlite paramether from modelfrom tvseries.ext import db class TVSerie(db.Model): id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number)
<commit_before>from tvseries.ext import db class TVSerie(db.Model): __table_args__ = {'sqlite_autoincrement': True} id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number) <commit_msg>Remove autoincrement sqlite paramether from model<commit_after>from tvseries.ext import db class TVSerie(db.Model): id = db.Column(db.Integer(), nullable=False, unique=True, autoincrement=True, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text, nullable=True) episodies_number = db.Column(db.Integer, nullable=False, default=1) author = db.Column(db.String(50), nullable=False) def __repr__(self): if self.description: self.description = "{0}...".format(self.description[0:10]) return ("TVSerie(id={!r}, name={!r}, " "description={!r}, episodies_number={!r})").format( self.id, self.name, self.description, self.episodies_number)
72045f86b25b396160e1a4c9237e977ed575afb2
apps/catalogue/constants.py
apps/catalogue/constants.py
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } LICENSES['http://creativecommons.org/licenses/by-sa/3.0/deed.pl'] = \ LICENSES['http://creativecommons.org/licenses/by-sa/3.0/'] # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
Support for 'deed.pl' license URL.
Support for 'deed.pl' license URL.
Python
agpl-3.0
fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN Support for 'deed.pl' license URL.
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } LICENSES['http://creativecommons.org/licenses/by-sa/3.0/deed.pl'] = \ LICENSES['http://creativecommons.org/licenses/by-sa/3.0/'] # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
<commit_before># -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN <commit_msg>Support for 'deed.pl' license URL.<commit_after>
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } LICENSES['http://creativecommons.org/licenses/by-sa/3.0/deed.pl'] = \ LICENSES['http://creativecommons.org/licenses/by-sa/3.0/'] # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN Support for 'deed.pl' license URL.# -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } LICENSES['http://creativecommons.org/licenses/by-sa/3.0/deed.pl'] = \ LICENSES['http://creativecommons.org/licenses/by-sa/3.0/'] # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
<commit_before># -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN <commit_msg>Support for 'deed.pl' license URL.<commit_after># -*- coding: utf-8 -*- # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later. # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information. # from django.utils.translation import ugettext_lazy as _ LICENSES = { 'http://creativecommons.org/licenses/by-sa/3.0/': { 'icon': 'cc-by-sa', 'description': _('Creative Commons Attribution-ShareAlike 3.0 Unported'), }, } LICENSES['http://creativecommons.org/licenses/by-sa/3.0/deed.pl'] = \ LICENSES['http://creativecommons.org/licenses/by-sa/3.0/'] # Those will be generated only for books with own HTML. EBOOK_FORMATS_WITHOUT_CHILDREN = ['txt', 'fb2'] # Those will be generated for all books. EBOOK_FORMATS_WITH_CHILDREN = ['pdf', 'epub', 'mobi'] # Those will be generated when inherited cover changes. EBOOK_FORMATS_WITH_COVERS = ['pdf', 'epub', 'mobi'] EBOOK_FORMATS = EBOOK_FORMATS_WITHOUT_CHILDREN + EBOOK_FORMATS_WITH_CHILDREN
c830e66431dab010309b4ad92ef38c418ec7029b
models.py
models.py
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(required=True) option2votes = db.IntField(required=True) topscore = db.IntField(required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(default=0, required=True) option2votes = db.IntField(default=0, required=True) topscore = db.IntField(default=0, required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
Add default votes and topscores
Add default votes and topscores
Python
mit
dpuleri/simpoll_backend,dpuleri/simpoll_backend,dpuleri/simpoll_backend,dpuleri/simpoll_backend
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(required=True) option2votes = db.IntField(required=True) topscore = db.IntField(required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }Add default votes and topscores
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(default=0, required=True) option2votes = db.IntField(default=0, required=True) topscore = db.IntField(default=0, required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
<commit_before>import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(required=True) option2votes = db.IntField(required=True) topscore = db.IntField(required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }<commit_msg>Add default votes and topscores<commit_after>
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(default=0, required=True) option2votes = db.IntField(default=0, required=True) topscore = db.IntField(default=0, required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(required=True) option2votes = db.IntField(required=True) topscore = db.IntField(required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }Add default votes and topscoresimport datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(default=0, required=True) option2votes = db.IntField(default=0, required=True) topscore = db.IntField(default=0, required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
<commit_before>import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(required=True) option2votes = db.IntField(required=True) topscore = db.IntField(required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }<commit_msg>Add default votes and topscores<commit_after>import datetime from flask import url_for from Simpoll import db class Poll(db.Document): created_at = db.DateTimeField(default=datetime.datetime.now, required=True) question = db.StringField(max_length=255, required=True) option1 = db.StringField(max_length=255, required=True) option2 = db.StringField(max_length=255, required=True) option1votes = db.IntField(default=0, required=True) option2votes = db.IntField(default=0, required=True) topscore = db.IntField(default=0, required=True) def get_absolute_url(self): # it's okay to use the first 7 bytes for url # because first 4 bytes are time and next 3 are # a machine id return url_for('post', kwargs={"slug": self._id[0:6]}) def __unicode__(self): return self.question meta = { 'allow_inheritance': True, 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'] }
eb9a3bd81a09efec8646a2c1de3fac9271762d33
opps/__init__.py
opps/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 2) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 3) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
Upgrade VERSION 0.1.2 to 0.1.3 on @oppsproject Milestones 2 (github)
Upgrade VERSION 0.1.2 to 0.1.3 on @oppsproject Milestones 2 (github)
Python
mit
YACOWS/opps,williamroot/opps,opps/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 2) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" Upgrade VERSION 0.1.2 to 0.1.3 on @oppsproject Milestones 2 (github)
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 3) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 2) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" <commit_msg>Upgrade VERSION 0.1.2 to 0.1.3 on @oppsproject Milestones 2 (github)<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 3) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 2) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" Upgrade VERSION 0.1.2 to 0.1.3 on @oppsproject Milestones 2 (github)#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 3) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 2) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS" <commit_msg>Upgrade VERSION 0.1.2 to 0.1.3 on @oppsproject Milestones 2 (github)<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 3) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Opps CMS websites magazines and high-traffic" __author__ = u"Thiago Avelino" __credits__ = [] __email__ = u"opps-developers@googlegroups.com" __license__ = u"MIT License" __copyright__ = u"Copyright 2013, YACOWS"
041afe6cec2fadd37b8e18fb1ac8a01cf9050dbf
xpserver_api/urls.py
xpserver_api/urls.py
from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^activate_account/$', views.activate_account, name='activate') ]
from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^activate_account/$', views.activate_account, name='activate') ]
Add login/logout for DRF web interface
Add login/logout for DRF web interface
Python
mit
xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server
from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^activate_account/$', views.activate_account, name='activate') ] Add login/logout for DRF web interface
from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^activate_account/$', views.activate_account, name='activate') ]
<commit_before>from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^activate_account/$', views.activate_account, name='activate') ] <commit_msg>Add login/logout for DRF web interface<commit_after>
from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^activate_account/$', views.activate_account, name='activate') ]
from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^activate_account/$', views.activate_account, name='activate') ] Add login/logout for DRF web interfacefrom xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^activate_account/$', views.activate_account, name='activate') ]
<commit_before>from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^activate_account/$', views.activate_account, name='activate') ] <commit_msg>Add login/logout for DRF web interface<commit_after>from xpserver_api import views from django.conf.urls import url, include from rest_framework import routers from xpserver_api.serializers import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^activate_account/$', views.activate_account, name='activate') ]
c7f91d43fc833e43f20c3412ed1fe89c84a39704
forumuser/tests/test_views.py
forumuser/tests/test_views.py
from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302) def test_logged_in(self): self.login_user(self.user) response = self.GET(self.list_url) self.logout_user(self.user)
from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302)
Remove logged in user test from forumuser
Remove logged in user test from forumuser
Python
mit
hellsgate1001/thatforum_django,hellsgate1001/thatforum_django,hellsgate1001/thatforum_django
from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302) def test_logged_in(self): self.login_user(self.user) response = self.GET(self.list_url) self.logout_user(self.user) Remove logged in user test from forumuser
from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302)
<commit_before>from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302) def test_logged_in(self): self.login_user(self.user) response = self.GET(self.list_url) self.logout_user(self.user) <commit_msg>Remove logged in user test from forumuser<commit_after>
from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302)
from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302) def test_logged_in(self): self.login_user(self.user) response = self.GET(self.list_url) self.logout_user(self.user) Remove logged in user test from forumuserfrom django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302)
<commit_before>from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302) def test_logged_in(self): self.login_user(self.user) response = self.GET(self.list_url) self.logout_user(self.user) <commit_msg>Remove logged in user test from forumuser<commit_after>from django.core.urlresolvers import reverse from forumuser.tests.factories import UserFactory from thatforum.test_helpers import ThatForumTestCase class TestUserListView(ThatForumTestCase): def setUp(self): self.user = UserFactory() self.list_url = reverse('user:list') def test_non_logged_in(self): response = self.GET(self.list_url, 302)
2546bb13065f35f4ddbfee76c63717e0692beabf
rst2pdf/utils.py
rst2pdf/utils.py
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
Fix encoding (thanks to Yasushi Masuda)
Fix encoding (thanks to Yasushi Masuda)
Python
mit
rst2pdf/rst2pdf,pombreda/rst2pdf,rst2pdf/rst2pdf,liuyi1112/rst2pdf,liuyi1112/rst2pdf,pombreda/rst2pdf
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) Fix encoding (thanks to Yasushi Masuda)
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
<commit_before>#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) <commit_msg>Fix encoding (thanks to Yasushi Masuda)<commit_after>
# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) Fix encoding (thanks to Yasushi Masuda)# -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
<commit_before>#$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent) <commit_msg>Fix encoding (thanks to Yasushi Masuda)<commit_after># -*- coding: utf-8 -*- #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import sys from reportlab.platypus import PageBreak, Spacer from flowables import * import shlex from log import log def parseRaw (data): '''Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height ''' elements=[] lines=data.splitlines() for line in lines: lexer=shlex.shlex(line) lexer.whitespace+=',' tokens=list(lexer) command=tokens[0] if command == 'PageBreak': if len(tokens)==1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]),int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now #def depth (node): # if node.parent==None: # return 0 # else: # return 1+depth(node.parent)
e7a4402736518ae27cc87d4cdb22d411de2fc301
packages/mono.py
packages/mono.py
class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for((i=0;i<20;i++)); do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage ()
class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage ()
Fix shell syntax for non bash shells
Fix shell syntax for non bash shells The custom make command in mono.py is executed with the default shell, which on some systems doesn't support the fancy for loop syntax, like dash on Ubuntu.
Python
mit
mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,bl8/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,bl8/bockbuild,bl8/bockbuild
class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for((i=0;i<20;i++)); do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage () Fix shell syntax for non bash shells The custom make command in mono.py is executed with the default shell, which on some systems doesn't support the fancy for loop syntax, like dash on Ubuntu.
class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage ()
<commit_before>class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for((i=0;i<20;i++)); do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage () <commit_msg>Fix shell syntax for non bash shells The custom make command in mono.py is executed with the default shell, which on some systems doesn't support the fancy for loop syntax, like dash on Ubuntu.<commit_after>
class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage ()
class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for((i=0;i<20;i++)); do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage () Fix shell syntax for non bash shells The custom make command in mono.py is executed with the default shell, which on some systems doesn't support the fancy for loop syntax, like dash on Ubuntu.class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage ()
<commit_before>class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for((i=0;i<20;i++)); do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage () <commit_msg>Fix shell syntax for non bash shells The custom make command in mono.py is executed with the default shell, which on some systems doesn't support the fancy for loop syntax, like dash on Ubuntu.<commit_after>class MonoPackage (Package): def __init__ (self): Package.__init__ (self, 'mono', '2.10', sources = [ 'http://ftp.novell.com/pub/%{name}/sources/%{name}/%{name}-%{version}.tar.bz2', 'patches/mono-runtime-relocation.patch' ], configure_flags = [ '--with-jit=yes', '--with-ikvm=no', '--with-mcs-docs=no', '--with-moonlight=no', '--enable-quiet-build' ] ) # Mono (in libgc) likes to fail to build randomly self.make = 'for i in 1 2 3 4 5 6 7 8 9 10; do make && break; done' # def prep (self): # Package.prep (self) # self.sh ('patch -p1 < "%{sources[1]}"') def install (self): Package.install (self) if Package.profile.name == 'darwin': self.sh ('sed -ie "s/libcairo.so.2/libcairo.2.dylib/" "%{prefix}/etc/mono/config"') MonoPackage ()
99f53e007aac85aba162136dfa8ce131c965308b
pale/__init__.py
pale/__init__.py
import inspect import types import adapters import arguments import config import context from endpoint import Endpoint from resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
import inspect import types from . import adapters from . import arguments from . import config from . import context from .endpoint import Endpoint from .resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
Add dots to pale things
Add dots to pale things
Python
mit
Loudr/pale
import inspect import types import adapters import arguments import config import context from endpoint import Endpoint from resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances Add dots to pale things
import inspect import types from . import adapters from . import arguments from . import config from . import context from .endpoint import Endpoint from .resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
<commit_before>import inspect import types import adapters import arguments import config import context from endpoint import Endpoint from resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances <commit_msg>Add dots to pale things<commit_after>
import inspect import types from . import adapters from . import arguments from . import config from . import context from .endpoint import Endpoint from .resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
import inspect import types import adapters import arguments import config import context from endpoint import Endpoint from resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances Add dots to pale thingsimport inspect import types from . import adapters from . import arguments from . import config from . import context from .endpoint import Endpoint from .resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
<commit_before>import inspect import types import adapters import arguments import config import context from endpoint import Endpoint from resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances <commit_msg>Add dots to pale things<commit_after>import inspect import types from . import adapters from . import arguments from . import config from . import context from .endpoint import Endpoint from .resource import NoContentResource, Resource, ResourceList ImplementationModule = "_pale__api_implementation" def is_pale_module(obj): is_it = isinstance(obj, types.ModuleType) and \ hasattr(obj, '_module_type') and \ obj._module_type == ImplementationModule return is_it def extract_endpoints(api_module): """Iterates through an api implementation module to extract and instantiate endpoint objects to be passed to the HTTP-layer's router. """ if not hasattr(api_module, 'endpoints'): raise ValueError(("pale.extract_endpoints expected the passed in " "api_module to have an `endpoints` attribute, but it didn't!")) classes = [v for (k,v) in inspect.getmembers(api_module.endpoints, inspect.isclass)] instances = [] for cls in classes: if Endpoint in cls.__bases__: instances.append(cls()) return instances
22ecda2f6879a140783a4e0105fb215e8cb12536
passwd_change.py
passwd_change.py
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file')
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 5: keys_file = _args[1] target_file = _args[2] result_file = _args[3] log_file = _args[4] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open(log_file, 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file log_file')
Add log file name to command line.
Add log file name to command line.
Python
mit
maxsocl/oldmailer
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') Add log file name to command line.
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 5: keys_file = _args[1] target_file = _args[2] result_file = _args[3] log_file = _args[4] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open(log_file, 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file log_file')
<commit_before>#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') <commit_msg>Add log file name to command line.<commit_after>
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 5: keys_file = _args[1] target_file = _args[2] result_file = _args[3] log_file = _args[4] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open(log_file, 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file log_file')
#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') Add log file name to command line.#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 5: keys_file = _args[1] target_file = _args[2] result_file = _args[3] log_file = _args[4] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open(log_file, 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file log_file')
<commit_before>#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 4: keys_file = _args[1] target_file = _args[2] result_file = _args[3] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open('deletel.log', 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file') <commit_msg>Add log file name to command line.<commit_after>#!/usr/bin/env python3 import sys _args = sys.argv if __name__ == "__main__": if len(_args) == 5: keys_file = _args[1] target_file = _args[2] result_file = _args[3] log_file = _args[4] try: with open(keys_file, 'r') as k: keys = k.readlines() keys = [key.strip().split('@')[0] for key in keys] keys = [key for key in keys if key != ''] with open(target_file, 'r') as t: target_lines = t.readlines() log = open(log_file, 'w') with open(result_file, 'w') as r: for line in target_lines: if line.split(':')[0] in keys or line.split(':')[3] != '12': r.write(line) else: log.write(line) log.close() except Exception as e: print(str(e)) sys.exit() else: print('./passwd_change.py keys_file.txt passwd_file result_file log_file')
4271d2ce0fc1cd2db4dab30aa59fece48c83f0bf
go/base/models.py
go/base/models.py
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).
Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account) Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
<commit_before>from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account) <commit_msg>Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).<commit_after>
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account) Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
<commit_before>from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account) <commit_msg>Enable search whenever a user profile is saved (to allow easier recovery from accounts created incorrectly).<commit_after>from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.conf import settings from vumi.persist.riak_manager import RiakManager from go.vumitools.account import AccountStore from go.base.utils import vumi_api_for_user def get_account_store(): return AccountStore(RiakManager.from_config( settings.VUMI_API_CONFIG['riak_manager'])) def create_user_profile(sender, instance, created, **kwargs): if created: account = get_account_store().new_user(unicode(instance.username)) UserProfile.objects.create(user=instance, user_account=account.key) user_api = vumi_api_for_user(instance) # Enable search for the contact & group stores user_api.contact_store.contacts.enable_search() user_api.contact_store.groups.enable_search() post_save.connect(create_user_profile, sender=User, dispatch_uid='go.base.models.create_user_profile') class UserProfile(models.Model): """A profile for a user""" user = models.OneToOneField('auth.User') user_account = models.CharField(max_length=100) def __unicode__(self): return u' '.join([self.user.first_name, self.user.last_name]) def get_user_account(self): return get_account_store().get_user(self.user_account)
473e900fba1378e212a42c93624d1dd4f8acfb6e
fjord/alerts/migrations/0002_alertflavor_allowed_tokens.py
fjord/alerts/migrations/0002_alertflavor_allowed_tokens.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token'), preserve_default=True, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token', blank=True), preserve_default=True, ), ]
Fix migration for fixing AlertFlavor.allowed_tokens
Fix migration for fixing AlertFlavor.allowed_tokens Recently, I changed AlertFlavor.allowed_tokens so that you could create a flavor without specifying the tokens that go with it (i.e. I added blank=True). The resulting migration for that change does a bunch of SQL, but doesn't actually change the db. So I'm tweaking the last exsiting migration rather than creating a new migration that does a bunch of stuff to do nothing.
Python
bsd-3-clause
hoosteeno/fjord,mozilla/fjord,Ritsyy/fjord,rlr/fjord,mozilla/fjord,rlr/fjord,hoosteeno/fjord,staranjeet/fjord,Ritsyy/fjord,hoosteeno/fjord,staranjeet/fjord,lgp171188/fjord,lgp171188/fjord,rlr/fjord,lgp171188/fjord,mozilla/fjord,lgp171188/fjord,Ritsyy/fjord,rlr/fjord,hoosteeno/fjord,staranjeet/fjord,staranjeet/fjord,mozilla/fjord,Ritsyy/fjord
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token'), preserve_default=True, ), ] Fix migration for fixing AlertFlavor.allowed_tokens Recently, I changed AlertFlavor.allowed_tokens so that you could create a flavor without specifying the tokens that go with it (i.e. I added blank=True). The resulting migration for that change does a bunch of SQL, but doesn't actually change the db. So I'm tweaking the last exsiting migration rather than creating a new migration that does a bunch of stuff to do nothing.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token', blank=True), preserve_default=True, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token'), preserve_default=True, ), ] <commit_msg>Fix migration for fixing AlertFlavor.allowed_tokens Recently, I changed AlertFlavor.allowed_tokens so that you could create a flavor without specifying the tokens that go with it (i.e. I added blank=True). The resulting migration for that change does a bunch of SQL, but doesn't actually change the db. So I'm tweaking the last exsiting migration rather than creating a new migration that does a bunch of stuff to do nothing.<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token', blank=True), preserve_default=True, ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token'), preserve_default=True, ), ] Fix migration for fixing AlertFlavor.allowed_tokens Recently, I changed AlertFlavor.allowed_tokens so that you could create a flavor without specifying the tokens that go with it (i.e. I added blank=True). The resulting migration for that change does a bunch of SQL, but doesn't actually change the db. So I'm tweaking the last exsiting migration rather than creating a new migration that does a bunch of stuff to do nothing.# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token', blank=True), preserve_default=True, ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token'), preserve_default=True, ), ] <commit_msg>Fix migration for fixing AlertFlavor.allowed_tokens Recently, I changed AlertFlavor.allowed_tokens so that you could create a flavor without specifying the tokens that go with it (i.e. I added blank=True). The resulting migration for that change does a bunch of SQL, but doesn't actually change the db. So I'm tweaking the last exsiting migration rather than creating a new migration that does a bunch of stuff to do nothing.<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_auth', '0001_initial'), ('alerts', '0001_initial'), ] operations = [ migrations.AddField( model_name='alertflavor', name='allowed_tokens', field=models.ManyToManyField(help_text='Tokens that are permitted to emit this flavor', to='api_auth.Token', blank=True), preserve_default=True, ), ]
32320073263926ca6a36956e7cf2359254105d6c
hierarchical_auth/admin.py
hierarchical_auth/admin.py
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_MODEL.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_CLASS.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
Work with custom user models in django >= 1.5
Work with custom user models in django >= 1.5
Python
bsd-3-clause
digitalemagine/django-hierarchical-auth,zhangguiyu/django-hierarchical-auth
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_MODEL.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin) Work with custom user models in django >= 1.5
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_CLASS.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
<commit_before>from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_MODEL.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin) <commit_msg>Work with custom user models in django >= 1.5<commit_after>
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_CLASS.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_MODEL.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin) Work with custom user models in django >= 1.5from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_CLASS.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
<commit_before>from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_MODEL.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin) <commit_msg>Work with custom user models in django >= 1.5<commit_after>from django.contrib import admin from django.conf import settings from django.db.models import get_model from django.contrib.auth.models import Group from django.contrib.auth.admin import GroupAdmin from django.contrib.auth.forms import UserChangeForm try: from django.contrib.auth import get_user_model User = get_user_model() except: from django.contrib.auth.models import User try: module_name, class_name = settings.AUTH_USER_ADMIN_CLASS.rsplit('.', 1) mod = __import__(module_name, fromlist=[class_name]) UserAdmin = getattr(mod, class_name) except: from django.contrib.auth.admin import UserAdmin from mptt.forms import TreeNodeMultipleChoiceField if getattr(settings, 'MPTT_USE_FEINCMS', False): from mptt.admin import FeinCMSModelAdmin class GroupMPTTModelAdmin(GroupAdmin, FeinCMSModelAdmin): pass else: from mptt.admin import MPTTModelAdmin class GroupMPTTModelAdmin(GroupAdmin, MPTTModelAdmin): pass admin.site.unregister(Group) admin.site.register(Group, GroupMPTTModelAdmin) class UserWithMPTTChangeForm(UserChangeForm): groups = TreeNodeMultipleChoiceField(queryset=Group.tree.all()) class UserWithMPTTAdmin(UserAdmin): form = UserWithMPTTChangeForm admin.site.unregister(User) admin.site.register(User, UserWithMPTTAdmin)
471d9c2ab901a018ef7b64464f19898dfbc9dd12
ca_mb/__init__.py
ca_mb/__init__.py
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'Independent'}, ]
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10'
Fix for new divisions and parties
ca_mb: Fix for new divisions and parties
Python
mit
opencivicdata/scrapers-ca,opencivicdata/scrapers-ca
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'Independent'}, ] ca_mb: Fix for new divisions and parties
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10'
<commit_before>from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'Independent'}, ] <commit_msg>ca_mb: Fix for new divisions and parties<commit_after>
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10'
from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'Independent'}, ] ca_mb: Fix for new divisions and partiesfrom utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10'
<commit_before>from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'Independent'}, ] <commit_msg>ca_mb: Fix for new divisions and parties<commit_after>from utils import CanadianJurisdiction class Manitoba(CanadianJurisdiction): classification = 'legislature' division_id = 'ocd-division/country:ca/province:mb' division_name = 'Manitoba' name = 'Legislative Assembly of Manitoba' url = 'http://www.gov.mb.ca/legislature/' parties = [ {'name': 'Independent'}, {'name': 'Independent Liberal'}, {'name': 'Manitoba Liberal Party'}, {'name': 'Manitoba Party'}, {'name': 'New Democratic Party of Manitoba'}, {'name': 'Progressive Conservative Party of Manitoba'}, ] skip_null_valid_from = True valid_from = '2019-09-10'
f0ed3faa716c05315ca0108650c49ef4e83f1f59
deflect/views.py
deflect/views.py
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.copy() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.dict() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
Use a dict representation of the GET QueryDict
Use a dict representation of the GET QueryDict
Python
bsd-3-clause
jbittel/django-deflect
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.copy() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params)) Use a dict representation of the GET QueryDict
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.dict() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
<commit_before>from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.copy() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params)) <commit_msg>Use a dict representation of the GET QueryDict<commit_after>
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.dict() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.copy() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params)) Use a dict representation of the GET QueryDictfrom __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.dict() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
<commit_before>from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.copy() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params)) <commit_msg>Use a dict representation of the GET QueryDict<commit_after>from __future__ import unicode_literals import base32_crockford import logging from django.http import Http404 from django.http import HttpResponsePermanentRedirect from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from .models import ShortURL from .models import ShortURLAlias logger = logging.getLogger(__name__) def redirect(request, key): """ Given the short URL key, update the statistics and redirect the user to the destination URL. """ try: alias = ShortURLAlias.objects.get(alias=key.lower()) key_id = alias.redirect_id except ShortURLAlias.DoesNotExist: try: key_id = base32_crockford.decode(key) except ValueError as e: logger.warning("Error decoding redirect: %s" % e) raise Http404 redirect = get_object_or_404(ShortURL, pk=key_id) ShortURL.objects.increment_hits(redirect.pk) params = request.GET.dict() if redirect.is_tracking: return HttpResponsePermanentRedirect(redirect.target_url(params=params)) else: return HttpResponseRedirect(redirect.target_url(params=params))
0afdab2f6feced873c88ba1e73fdde0dad5f041e
skytap/Quotas.py
skytap/Quotas.py
"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object.""" def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:]))
"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object. Note: This code assumes that you have regional limits on your account. The return is different if you don't (see the /v2 API doc). We should get each piece of the return and sort it into type-and-region (whether you have regional limits or not) and can then access things uniformly. Doing so will also require smartly accessing the API on demand more, since accounts with regional limits may require multiple calls to get the info desired. """ def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:]))
Comment re: API usage to clarify quotas.
Comment re: API usage to clarify quotas.
Python
mit
mapledyne/skytap,FulcrumIT/skytap
"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object.""" def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:])) Comment re: API usage to clarify quotas.
"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object. Note: This code assumes that you have regional limits on your account. The return is different if you don't (see the /v2 API doc). We should get each piece of the return and sort it into type-and-region (whether you have regional limits or not) and can then access things uniformly. Doing so will also require smartly accessing the API on demand more, since accounts with regional limits may require multiple calls to get the info desired. """ def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:]))
<commit_before>"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object.""" def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:])) <commit_msg>Comment re: API usage to clarify quotas.<commit_after>
"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object. Note: This code assumes that you have regional limits on your account. The return is different if you don't (see the /v2 API doc). We should get each piece of the return and sort it into type-and-region (whether you have regional limits or not) and can then access things uniformly. Doing so will also require smartly accessing the API on demand more, since accounts with regional limits may require multiple calls to get the info desired. """ def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:]))
"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object.""" def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:])) Comment re: API usage to clarify quotas."""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object. Note: This code assumes that you have regional limits on your account. The return is different if you don't (see the /v2 API doc). We should get each piece of the return and sort it into type-and-region (whether you have regional limits or not) and can then access things uniformly. Doing so will also require smartly accessing the API on demand more, since accounts with regional limits may require multiple calls to get the info desired. """ def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:]))
<commit_before>"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object.""" def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:])) <commit_msg>Comment re: API usage to clarify quotas.<commit_after>"""Support for Skytap API access to the company quotas. If accessed via the command line (``python -m skytap.Quotas``) this will return the quotas from Skytap in a JSON format. """ import json import sys from skytap.models.Quota import Quota from skytap.models.SkytapGroup import SkytapGroup class Quotas(SkytapGroup): """Company/account quotas object. Note: This code assumes that you have regional limits on your account. The return is different if you don't (see the /v2 API doc). We should get each piece of the return and sort it into type-and-region (whether you have regional limits or not) and can then access things uniformly. Doing so will also require smartly accessing the API on demand more, since accounts with regional limits may require multiple calls to get the info desired. """ def __init__(self): """Load the quotas from Skytap.""" super(Quotas, self).__init__() quota_rest = self.rest('/v2/company/quotas') quota_json = json.loads(quota_rest) for qu in quota_json: self.data[qu] = Quota(quota_json[qu][0]) if __name__ == '__main__': print(Quotas().main(sys.argv[1:]))
829f71c488f2332d66362d7aea309a8b8958d522
jarviscli/tests/test_voice.py
jarviscli/tests/test_voice.py
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.run(voice.gtts) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.run(voice.disable_gtts) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.gtts(jarvis, self) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.disable_gtts(jarvis, self) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
Fix unit test of voice function
Fix unit test of voice function
Python
mit
sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.run(voice.gtts) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.run(voice.disable_gtts) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main() Fix unit test of voice function
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.gtts(jarvis, self) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.disable_gtts(jarvis, self) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.run(voice.gtts) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.run(voice.disable_gtts) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main() <commit_msg>Fix unit test of voice function<commit_after>
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.gtts(jarvis, self) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.disable_gtts(jarvis, self) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.run(voice.gtts) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.run(voice.disable_gtts) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main() Fix unit test of voice functionimport unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.gtts(jarvis, self) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.disable_gtts(jarvis, self) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
<commit_before>import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.run(voice.gtts) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.run(voice.disable_gtts) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main() <commit_msg>Fix unit test of voice function<commit_after>import unittest from tests import PluginTest from plugins import voice from CmdInterpreter import JarvisAPI from Jarvis import Jarvis # this test class contains test cases for the plugins "gtts" and "disable_gtts" # which are included in the "voice.py" file in the "plugins" folder class VoiceTest(PluginTest): # test "gtts" plugin def setUp(self): self.test_gtts = self.load_plugin(voice.gtts) def test_gtts(self): # run "gtts" plugin code self.test_gtts.gtts(jarvis, self) # verify that "gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), True) # test "disable_gtts" plugin def setUp(self): self.test_disable_gtts = self.load_plugin(voice.disable_gtts) def test_disable_gtts(self): # run "disable_gtts" plugin code self.test_disable_gtts.disable_gtts(jarvis, self) # verify that "disable_gtts" plugin code works self.assertEqual(self.jarvis_api.get_data('gtts_status'), False) if __name__ == '__main__': unittest.main()
d5e5ddbd1e1108f327a8d4c27cc18925cf7a3e1a
src/sentry/api/endpoints/project_stats.py
src/sentry/api/endpoints/project_stats.py
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): def get(self, request, project_id): project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data)
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint, DocSection from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): doc_section = DocSection.PROJECTS def get(self, request, project_id): """ Retrieve event counts for a project **Draft:** This endpoint may change in the future without notice. Return a set of points representing a normalized timestamp and the number of events seen in the period. {method} {path}?since=1421092384.822244&until=1434052399.443363 Query ranges are limited to Sentry's configured time-series resolutions. Parameters: - since: a timestamp to set the start of the query - until: a timestamp to set the end of the query - resolution: an explicit resolution to search for **Note:** resolution should not be used unless you're familiar with Sentry internals as it's restricted to pre-defined values. """ project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data)
Add project stats to docs
Add project stats to docs
Python
bsd-3-clause
looker/sentry,kevinlondon/sentry,pauloschilling/sentry,1tush/sentry,daevaorn/sentry,wong2/sentry,fuziontech/sentry,gencer/sentry,imankulov/sentry,felixbuenemann/sentry,ifduyue/sentry,gg7/sentry,1tush/sentry,camilonova/sentry,hongliang5623/sentry,boneyao/sentry,camilonova/sentry,songyi199111/sentry,llonchj/sentry,mvaled/sentry,jokey2k/sentry,imankulov/sentry,jokey2k/sentry,Natim/sentry,TedaLIEz/sentry,ifduyue/sentry,BayanGroup/sentry,daevaorn/sentry,beeftornado/sentry,jokey2k/sentry,JTCunning/sentry,gg7/sentry,kevinastone/sentry,mvaled/sentry,jean/sentry,drcapulet/sentry,daevaorn/sentry,hongliang5623/sentry,alexm92/sentry,songyi199111/sentry,BuildingLink/sentry,korealerts1/sentry,mvaled/sentry,JamesMura/sentry,wujuguang/sentry,pauloschilling/sentry,songyi199111/sentry,jean/sentry,gencer/sentry,ewdurbin/sentry,llonchj/sentry,fuziontech/sentry,kevinlondon/sentry,vperron/sentry,nicholasserra/sentry,jean/sentry,JTCunning/sentry,hongliang5623/sentry,kevinastone/sentry,alexm92/sentry,Natim/sentry,drcapulet/sentry,boneyao/sentry,ngonzalvez/sentry,looker/sentry,zenefits/sentry,wong2/sentry,BayanGroup/sentry,gencer/sentry,mvaled/sentry,fuziontech/sentry,JTCunning/sentry,1tush/sentry,BuildingLink/sentry,vperron/sentry,fotinakis/sentry,beeftornado/sentry,felixbuenemann/sentry,nicholasserra/sentry,gencer/sentry,korealerts1/sentry,Kryz/sentry,felixbuenemann/sentry,daevaorn/sentry,JamesMura/sentry,zenefits/sentry,JackDanger/sentry,BuildingLink/sentry,ifduyue/sentry,zenefits/sentry,mvaled/sentry,kevinastone/sentry,wujuguang/sentry,nicholasserra/sentry,JackDanger/sentry,Natim/sentry,argonemyth/sentry,TedaLIEz/sentry,gencer/sentry,alexm92/sentry,BayanGroup/sentry,korealerts1/sentry,BuildingLink/sentry,imankulov/sentry,JamesMura/sentry,looker/sentry,mitsuhiko/sentry,drcapulet/sentry,looker/sentry,TedaLIEz/sentry,fotinakis/sentry,beeftornado/sentry,mitsuhiko/sentry,ifduyue/sentry,wong2/sentry,boneyao/sentry,jean/sentry,kevinlondon/sentry,camilonova/sentry,jean/sentry,JamesMura/sentry,JamesMura/sentry,argonemyth/sentry,Kryz/sentry,zenefits/sentry,ewdurbin/sentry,argonemyth/sentry,BuildingLink/sentry,gg7/sentry,ewdurbin/sentry,wujuguang/sentry,JackDanger/sentry,looker/sentry,Kryz/sentry,mvaled/sentry,ngonzalvez/sentry,ngonzalvez/sentry,ifduyue/sentry,zenefits/sentry,fotinakis/sentry,pauloschilling/sentry,fotinakis/sentry,llonchj/sentry,vperron/sentry
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): def get(self, request, project_id): project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data) Add project stats to docs
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint, DocSection from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): doc_section = DocSection.PROJECTS def get(self, request, project_id): """ Retrieve event counts for a project **Draft:** This endpoint may change in the future without notice. Return a set of points representing a normalized timestamp and the number of events seen in the period. {method} {path}?since=1421092384.822244&until=1434052399.443363 Query ranges are limited to Sentry's configured time-series resolutions. Parameters: - since: a timestamp to set the start of the query - until: a timestamp to set the end of the query - resolution: an explicit resolution to search for **Note:** resolution should not be used unless you're familiar with Sentry internals as it's restricted to pre-defined values. """ project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data)
<commit_before>from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): def get(self, request, project_id): project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data) <commit_msg>Add project stats to docs<commit_after>
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint, DocSection from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): doc_section = DocSection.PROJECTS def get(self, request, project_id): """ Retrieve event counts for a project **Draft:** This endpoint may change in the future without notice. Return a set of points representing a normalized timestamp and the number of events seen in the period. {method} {path}?since=1421092384.822244&until=1434052399.443363 Query ranges are limited to Sentry's configured time-series resolutions. Parameters: - since: a timestamp to set the start of the query - until: a timestamp to set the end of the query - resolution: an explicit resolution to search for **Note:** resolution should not be used unless you're familiar with Sentry internals as it's restricted to pre-defined values. """ project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data)
from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): def get(self, request, project_id): project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data) Add project stats to docsfrom __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint, DocSection from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): doc_section = DocSection.PROJECTS def get(self, request, project_id): """ Retrieve event counts for a project **Draft:** This endpoint may change in the future without notice. Return a set of points representing a normalized timestamp and the number of events seen in the period. {method} {path}?since=1421092384.822244&until=1434052399.443363 Query ranges are limited to Sentry's configured time-series resolutions. Parameters: - since: a timestamp to set the start of the query - until: a timestamp to set the end of the query - resolution: an explicit resolution to search for **Note:** resolution should not be used unless you're familiar with Sentry internals as it's restricted to pre-defined values. """ project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data)
<commit_before>from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): def get(self, request, project_id): project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data) <commit_msg>Add project stats to docs<commit_after>from __future__ import absolute_import from rest_framework.response import Response from sentry.app import tsdb from sentry.api.base import BaseStatsEndpoint, DocSection from sentry.api.permissions import assert_perm from sentry.models import Project class ProjectStatsEndpoint(BaseStatsEndpoint): doc_section = DocSection.PROJECTS def get(self, request, project_id): """ Retrieve event counts for a project **Draft:** This endpoint may change in the future without notice. Return a set of points representing a normalized timestamp and the number of events seen in the period. {method} {path}?since=1421092384.822244&until=1434052399.443363 Query ranges are limited to Sentry's configured time-series resolutions. Parameters: - since: a timestamp to set the start of the query - until: a timestamp to set the end of the query - resolution: an explicit resolution to search for **Note:** resolution should not be used unless you're familiar with Sentry internals as it's restricted to pre-defined values. """ project = Project.objects.get_from_cache( id=project_id, ) assert_perm(project, request.user, request.auth) data = tsdb.get_range( model=tsdb.models.project, keys=[project.id], **self._parse_args(request) )[project.id] return Response(data)
2230832033df7f5d8511dc75f799a9cc738dc46f
games/managers.py
games/managers.py
from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True)
from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
Fix missing import and bad query for screenshots
Fix missing import and bad query for screenshots
Python
agpl-3.0
Turupawn/website,Turupawn/website,lutris/website,lutris/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website
from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True) Fix missing import and bad query for screenshots
from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
<commit_before>from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True) <commit_msg>Fix missing import and bad query for screenshots<commit_after>
from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True) Fix missing import and bad query for screenshotsfrom django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
<commit_before>from django.db.models import Manager class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(user=user)) else: return query.filter(published=True) <commit_msg>Fix missing import and bad query for screenshots<commit_after>from django.db.models import Manager from django.db.models import Q class ScreenshotManager(Manager): def published(self, user=None, is_staff=False): query = self.get_query_set() query = query.order_by('uploaded_at') if is_staff: return query elif user: return query.filter(Q(published=True) | Q(uploaded_by=user)) else: return query.filter(published=True)
ebba310de088d8d295e1fc94d368da4edc430756
user/admin.py
user/admin.py
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') search_fields = ('email',)
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',)
Set User Admin default ordering.
Ch23: Set User Admin default ordering.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') search_fields = ('email',) Ch23: Set User Admin default ordering.
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',)
<commit_before>from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') search_fields = ('email',) <commit_msg>Ch23: Set User Admin default ordering.<commit_after>
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',)
from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') search_fields = ('email',) Ch23: Set User Admin default ordering.from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',)
<commit_before>from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') search_fields = ('email',) <commit_msg>Ch23: Set User Admin default ordering.<commit_after>from django.contrib import admin from .models import User @admin.register(User) class UserAdmin(admin.ModelAdmin): # list view list_display = ( 'email', 'is_staff', 'is_superuser') list_filter = ( 'is_staff', 'is_superuser', 'profile__joined') ordering = ('email',) search_fields = ('email',)
988678cf6d0eb8459588e1067dd3a91468cbaa2d
numpy/numarray/setup.py
numpy/numarray/setup.py
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/*') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
Fix installation of numarray headers on Windows.
Fix installation of numarray headers on Windows.
Python
bsd-3-clause
WarrenWeckesser/numpy,GrimDerp/numpy,kirillzhuravlev/numpy,yiakwy/numpy,mortada/numpy,GaZ3ll3/numpy,maniteja123/numpy,abalkin/numpy,Yusa95/numpy,bmorris3/numpy,ajdawson/numpy,pyparallel/numpy,kiwifb/numpy,pelson/numpy,solarjoe/numpy,mhvk/numpy,jakirkham/numpy,grlee77/numpy,naritta/numpy,WarrenWeckesser/numpy,ajdawson/numpy,mhvk/numpy,Eric89GXL/numpy,SunghanKim/numpy,jonathanunderwood/numpy,simongibbons/numpy,ajdawson/numpy,sigma-random/numpy,ewmoore/numpy,madphysicist/numpy,argriffing/numpy,pizzathief/numpy,sigma-random/numpy,embray/numpy,ESSS/numpy,dato-code/numpy,ogrisel/numpy,joferkington/numpy,naritta/numpy,charris/numpy,astrofrog/numpy,SiccarPoint/numpy,chiffa/numpy,mwiebe/numpy,ahaldane/numpy,Linkid/numpy,matthew-brett/numpy,Srisai85/numpy,rhythmsosad/numpy,rherault-insa/numpy,dwillmer/numpy,pelson/numpy,Linkid/numpy,ahaldane/numpy,MSeifert04/numpy,madphysicist/numpy,skwbc/numpy,cjermain/numpy,tdsmith/numpy,pdebuyl/numpy,ajdawson/numpy,ogrisel/numpy,dwf/numpy,endolith/numpy,skymanaditya1/numpy,stuarteberg/numpy,astrofrog/numpy,rmcgibbo/numpy,KaelChen/numpy,mattip/numpy,AustereCuriosity/numpy,seberg/numpy,GaZ3ll3/numpy,trankmichael/numpy,bringingheavendown/numpy,cowlicks/numpy,NextThought/pypy-numpy,pbrod/numpy,jankoslavic/numpy,charris/numpy,leifdenby/numpy,kiwifb/numpy,numpy/numpy-refactor,moreati/numpy,BMJHayward/numpy,matthew-brett/numpy,moreati/numpy,madphysicist/numpy,WillieMaddox/numpy,Linkid/numpy,numpy/numpy-refactor,KaelChen/numpy,dwf/numpy,njase/numpy,nbeaver/numpy,ekalosak/numpy,ChristopherHogan/numpy,ViralLeadership/numpy,dch312/numpy,ddasilva/numpy,behzadnouri/numpy,chatcannon/numpy,seberg/numpy,Eric89GXL/numpy,immerrr/numpy,ChristopherHogan/numpy,moreati/numpy,simongibbons/numpy,ssanderson/numpy,leifdenby/numpy,Anwesh43/numpy,simongibbons/numpy,embray/numpy,rhythmsosad/numpy,grlee77/numpy,BabeNovelty/numpy,sinhrks/numpy,ekalosak/numpy,mhvk/numpy,WarrenWeckesser/numpy,pdebuyl/numpy,SiccarPoint/numpy,ViralLeadership/numpy,dimasad/numpy,mortada/numpy,sinhrks/numpy,nguyentu1602/numpy,jschueller/numpy,jorisvandenbossche/numpy,b-carter/numpy,brandon-rhodes/numpy,andsor/numpy,bmorris3/numpy,embray/numpy,charris/numpy,matthew-brett/numpy,bertrand-l/numpy,dimasad/numpy,CMartelLML/numpy,immerrr/numpy,mwiebe/numpy,larsmans/numpy,Yusa95/numpy,githubmlai/numpy,jonathanunderwood/numpy,rudimeier/numpy,pdebuyl/numpy,dimasad/numpy,hainm/numpy,CMartelLML/numpy,MSeifert04/numpy,cjermain/numpy,pyparallel/numpy,chiffa/numpy,pbrod/numpy,dimasad/numpy,stefanv/numpy,Linkid/numpy,BabeNovelty/numpy,mattip/numpy,mingwpy/numpy,ewmoore/numpy,ekalosak/numpy,shoyer/numpy,mhvk/numpy,ewmoore/numpy,skymanaditya1/numpy,simongibbons/numpy,musically-ut/numpy,nguyentu1602/numpy,rgommers/numpy,gfyoung/numpy,rmcgibbo/numpy,WarrenWeckesser/numpy,dato-code/numpy,jschueller/numpy,maniteja123/numpy,bertrand-l/numpy,rhythmsosad/numpy,endolith/numpy,ChanderG/numpy,pizzathief/numpy,numpy/numpy,rajathkumarmp/numpy,jonathanunderwood/numpy,mindw/numpy,kirillzhuravlev/numpy,mathdd/numpy,trankmichael/numpy,empeeu/numpy,dwillmer/numpy,mingwpy/numpy,embray/numpy,kirillzhuravlev/numpy,jorisvandenbossche/numpy,MaPePeR/numpy,GrimDerp/numpy,utke1/numpy,numpy/numpy-refactor,Anwesh43/numpy,jakirkham/numpy,jakirkham/numpy,MichaelAquilina/numpy,dwillmer/numpy,SiccarPoint/numpy,tacaswell/numpy,pizzathief/numpy,mindw/numpy,chatcannon/numpy,tdsmith/numpy,MSeifert04/numpy,jakirkham/numpy,pelson/numpy,endolith/numpy,bertrand-l/numpy,MSeifert04/numpy,njase/numpy,mathdd/numpy,ssanderson/numpy,drasmuss/numpy,empeeu/numpy,andsor/numpy,rherault-insa/numpy,skwbc/numpy,tacaswell/numpy,tdsmith/numpy,stefanv/numpy,pelson/numpy,brandon-rhodes/numpy,dch312/numpy,mattip/numpy,nguyentu1602/numpy,yiakwy/numpy,dch312/numpy,solarjoe/numpy,sonnyhu/numpy,matthew-brett/numpy,ContinuumIO/numpy,kirillzhuravlev/numpy,anntzer/numpy,solarjoe/numpy,NextThought/pypy-numpy,astrofrog/numpy,madphysicist/numpy,shoyer/numpy,numpy/numpy-refactor,WillieMaddox/numpy,bmorris3/numpy,AustereCuriosity/numpy,ogrisel/numpy,abalkin/numpy,BMJHayward/numpy,jankoslavic/numpy,mattip/numpy,ddasilva/numpy,ekalosak/numpy,shoyer/numpy,skymanaditya1/numpy,NextThought/pypy-numpy,BabeNovelty/numpy,numpy/numpy,kiwifb/numpy,rmcgibbo/numpy,sinhrks/numpy,grlee77/numpy,mathdd/numpy,hainm/numpy,empeeu/numpy,Eric89GXL/numpy,leifdenby/numpy,nbeaver/numpy,larsmans/numpy,AustereCuriosity/numpy,trankmichael/numpy,brandon-rhodes/numpy,pizzathief/numpy,njase/numpy,felipebetancur/numpy,yiakwy/numpy,tacaswell/numpy,mathdd/numpy,groutr/numpy,githubmlai/numpy,utke1/numpy,rajathkumarmp/numpy,ewmoore/numpy,jschueller/numpy,MichaelAquilina/numpy,pizzathief/numpy,immerrr/numpy,drasmuss/numpy,Srisai85/numpy,numpy/numpy,pbrod/numpy,joferkington/numpy,ContinuumIO/numpy,Yusa95/numpy,groutr/numpy,endolith/numpy,empeeu/numpy,rmcgibbo/numpy,tynn/numpy,naritta/numpy,Dapid/numpy,WillieMaddox/numpy,jorisvandenbossche/numpy,Anwesh43/numpy,seberg/numpy,pelson/numpy,maniteja123/numpy,matthew-brett/numpy,hainm/numpy,drasmuss/numpy,Dapid/numpy,gmcastil/numpy,immerrr/numpy,ViralLeadership/numpy,charris/numpy,rgommers/numpy,cowlicks/numpy,dato-code/numpy,jankoslavic/numpy,musically-ut/numpy,felipebetancur/numpy,MaPePeR/numpy,stefanv/numpy,MaPePeR/numpy,ESSS/numpy,MichaelAquilina/numpy,ahaldane/numpy,SiccarPoint/numpy,anntzer/numpy,brandon-rhodes/numpy,embray/numpy,ChristopherHogan/numpy,has2k1/numpy,has2k1/numpy,ChanderG/numpy,tynn/numpy,has2k1/numpy,SunghanKim/numpy,pbrod/numpy,githubmlai/numpy,ahaldane/numpy,jschueller/numpy,skymanaditya1/numpy,behzadnouri/numpy,behzadnouri/numpy,rgommers/numpy,sigma-random/numpy,jankoslavic/numpy,MaPePeR/numpy,Anwesh43/numpy,Dapid/numpy,felipebetancur/numpy,GaZ3ll3/numpy,musically-ut/numpy,gmcastil/numpy,sonnyhu/numpy,mindw/numpy,grlee77/numpy,dwillmer/numpy,mortada/numpy,jorisvandenbossche/numpy,tynn/numpy,dch312/numpy,pyparallel/numpy,andsor/numpy,abalkin/numpy,shoyer/numpy,WarrenWeckesser/numpy,joferkington/numpy,groutr/numpy,mingwpy/numpy,stuarteberg/numpy,Yusa95/numpy,hainm/numpy,ChanderG/numpy,cowlicks/numpy,madphysicist/numpy,gfyoung/numpy,SunghanKim/numpy,mhvk/numpy,ESSS/numpy,utke1/numpy,astrofrog/numpy,GrimDerp/numpy,pdebuyl/numpy,nguyentu1602/numpy,bmorris3/numpy,gfyoung/numpy,stuarteberg/numpy,has2k1/numpy,mwiebe/numpy,seberg/numpy,anntzer/numpy,dwf/numpy,nbeaver/numpy,SunghanKim/numpy,argriffing/numpy,astrofrog/numpy,mindw/numpy,CMartelLML/numpy,trankmichael/numpy,sinhrks/numpy,KaelChen/numpy,ssanderson/numpy,dwf/numpy,naritta/numpy,pbrod/numpy,dato-code/numpy,ddasilva/numpy,KaelChen/numpy,argriffing/numpy,rgommers/numpy,bringingheavendown/numpy,dwf/numpy,BMJHayward/numpy,rudimeier/numpy,mortada/numpy,GaZ3ll3/numpy,githubmlai/numpy,Srisai85/numpy,MichaelAquilina/numpy,numpy/numpy,anntzer/numpy,rherault-insa/numpy,rudimeier/numpy,rudimeier/numpy,Srisai85/numpy,ewmoore/numpy,rhythmsosad/numpy,simongibbons/numpy,jorisvandenbossche/numpy,Eric89GXL/numpy,cowlicks/numpy,larsmans/numpy,NextThought/pypy-numpy,jakirkham/numpy,BabeNovelty/numpy,stefanv/numpy,ChristopherHogan/numpy,cjermain/numpy,stuarteberg/numpy,ogrisel/numpy,larsmans/numpy,chiffa/numpy,yiakwy/numpy,b-carter/numpy,sigma-random/numpy,chatcannon/numpy,shoyer/numpy,ContinuumIO/numpy,sonnyhu/numpy,rajathkumarmp/numpy,ogrisel/numpy,sonnyhu/numpy,stefanv/numpy,mingwpy/numpy,cjermain/numpy,CMartelLML/numpy,GrimDerp/numpy,andsor/numpy,gmcastil/numpy,ahaldane/numpy,bringingheavendown/numpy,felipebetancur/numpy,BMJHayward/numpy,tdsmith/numpy,b-carter/numpy,joferkington/numpy,grlee77/numpy,skwbc/numpy,MSeifert04/numpy,musically-ut/numpy,ChanderG/numpy,rajathkumarmp/numpy,numpy/numpy-refactor
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) Fix installation of numarray headers on Windows.
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/*') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
<commit_before>from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) <commit_msg>Fix installation of numarray headers on Windows.<commit_after>
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/*') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) Fix installation of numarray headers on Windows.from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/*') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
<commit_before>from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration) <commit_msg>Fix installation of numarray headers on Windows.<commit_after>from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numarray',parent_package,top_path) config.add_data_files('numpy/*') config.add_extension('_capi', sources=['_capi.c'], ) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(configuration=configuration)
602d1ceb755d5d74312e965b5515bbe22c868fd4
sale_commission_pricelist/models/sale_order.py
sale_commission_pricelist/models/sale_order.py
# -*- coding: utf-8 -*- # Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): self.ensure_one() if self.product_id and self.order_id.pricelist_id: rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) if rule.commission_id: self.agents.update({ 'commission': rule.commission_id.id, })
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Carlos Dauden <carlos.dauden@tecnativa.com> # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' def _get_commission_from_pricelist(self): self.ensure_one() if not self.product_id or not self.order_id.pricelist_id: return False rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) return rule.commission_id @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): commission = self._get_commission_from_pricelist() if commission: self.agents.update({ 'commission': commission.id, }) def _prepare_agents_vals(self): self.ensure_one() res = super(SaleOrderLine, self)._prepare_agents_vals() commission = self._get_commission_from_pricelist() if commission: for vals in res: vals['commission'] = commission.id return res
Make this to work on button recompute
[FIX] sale_commission_pricelist: Make this to work on button recompute
Python
agpl-3.0
OCA/commission,OCA/commission
# -*- coding: utf-8 -*- # Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): self.ensure_one() if self.product_id and self.order_id.pricelist_id: rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) if rule.commission_id: self.agents.update({ 'commission': rule.commission_id.id, }) [FIX] sale_commission_pricelist: Make this to work on button recompute
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Carlos Dauden <carlos.dauden@tecnativa.com> # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' def _get_commission_from_pricelist(self): self.ensure_one() if not self.product_id or not self.order_id.pricelist_id: return False rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) return rule.commission_id @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): commission = self._get_commission_from_pricelist() if commission: self.agents.update({ 'commission': commission.id, }) def _prepare_agents_vals(self): self.ensure_one() res = super(SaleOrderLine, self)._prepare_agents_vals() commission = self._get_commission_from_pricelist() if commission: for vals in res: vals['commission'] = commission.id return res
<commit_before># -*- coding: utf-8 -*- # Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): self.ensure_one() if self.product_id and self.order_id.pricelist_id: rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) if rule.commission_id: self.agents.update({ 'commission': rule.commission_id.id, }) <commit_msg>[FIX] sale_commission_pricelist: Make this to work on button recompute<commit_after>
# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Carlos Dauden <carlos.dauden@tecnativa.com> # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' def _get_commission_from_pricelist(self): self.ensure_one() if not self.product_id or not self.order_id.pricelist_id: return False rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) return rule.commission_id @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): commission = self._get_commission_from_pricelist() if commission: self.agents.update({ 'commission': commission.id, }) def _prepare_agents_vals(self): self.ensure_one() res = super(SaleOrderLine, self)._prepare_agents_vals() commission = self._get_commission_from_pricelist() if commission: for vals in res: vals['commission'] = commission.id return res
# -*- coding: utf-8 -*- # Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): self.ensure_one() if self.product_id and self.order_id.pricelist_id: rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) if rule.commission_id: self.agents.update({ 'commission': rule.commission_id.id, }) [FIX] sale_commission_pricelist: Make this to work on button recompute# -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Carlos Dauden <carlos.dauden@tecnativa.com> # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' def _get_commission_from_pricelist(self): self.ensure_one() if not self.product_id or not self.order_id.pricelist_id: return False rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) return rule.commission_id @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): commission = self._get_commission_from_pricelist() if commission: self.agents.update({ 'commission': commission.id, }) def _prepare_agents_vals(self): self.ensure_one() res = super(SaleOrderLine, self)._prepare_agents_vals() commission = self._get_commission_from_pricelist() if commission: for vals in res: vals['commission'] = commission.id return res
<commit_before># -*- coding: utf-8 -*- # Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): self.ensure_one() if self.product_id and self.order_id.pricelist_id: rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) if rule.commission_id: self.agents.update({ 'commission': rule.commission_id.id, }) <commit_msg>[FIX] sale_commission_pricelist: Make this to work on button recompute<commit_after># -*- coding: utf-8 -*- # Copyright 2018 Tecnativa - Carlos Dauden <carlos.dauden@tecnativa.com> # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo import api, models class SaleOrderLine(models.Model): _inherit = 'sale.order.line' def _get_commission_from_pricelist(self): self.ensure_one() if not self.product_id or not self.order_id.pricelist_id: return False rule_id = self.order_id.pricelist_id.get_product_price_rule( product=self.product_id, quantity=self.product_uom_qty or 1.0, partner=self.order_id.partner_id, date=self.order_id.date_order, uom_id=self.product_uom.id)[1] rule = self.env['product.pricelist.item'].browse(rule_id) return rule.commission_id @api.onchange('product_id', 'product_uom_qty') def _onchange_product_id_sale_commission_pricelist(self): commission = self._get_commission_from_pricelist() if commission: self.agents.update({ 'commission': commission.id, }) def _prepare_agents_vals(self): self.ensure_one() res = super(SaleOrderLine, self)._prepare_agents_vals() commission = self._get_commission_from_pricelist() if commission: for vals in res: vals['commission'] = commission.id return res
40bfd177cea186bc975fdc51ab61cf4d9e7026a3
tests/testapp/manage.py
tests/testapp/manage.py
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append('%s/../..' % os.getcwd()) if __name__ == "__main__": execute_manager(settings)
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append(os.path.abspath('%s/../..' % os.getcwd())) if __name__ == "__main__": execute_manager(settings)
Make sure to use abspath when adding dynamic_choices to sys.path
Make sure to use abspath when adding dynamic_choices to sys.path
Python
mit
charettes/django-dynamic-choices,charettes/django-dynamic-choices,charettes/django-dynamic-choices
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append('%s/../..' % os.getcwd()) if __name__ == "__main__": execute_manager(settings) Make sure to use abspath when adding dynamic_choices to sys.path
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append(os.path.abspath('%s/../..' % os.getcwd())) if __name__ == "__main__": execute_manager(settings)
<commit_before>#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append('%s/../..' % os.getcwd()) if __name__ == "__main__": execute_manager(settings) <commit_msg>Make sure to use abspath when adding dynamic_choices to sys.path<commit_after>
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append(os.path.abspath('%s/../..' % os.getcwd())) if __name__ == "__main__": execute_manager(settings)
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append('%s/../..' % os.getcwd()) if __name__ == "__main__": execute_manager(settings) Make sure to use abspath when adding dynamic_choices to sys.path#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append(os.path.abspath('%s/../..' % os.getcwd())) if __name__ == "__main__": execute_manager(settings)
<commit_before>#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append('%s/../..' % os.getcwd()) if __name__ == "__main__": execute_manager(settings) <commit_msg>Make sure to use abspath when adding dynamic_choices to sys.path<commit_after>#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) try: import dynamic_admin #@UnusedImport except ImportError: import sys, os sys.path.append(os.path.abspath('%s/../..' % os.getcwd())) if __name__ == "__main__": execute_manager(settings)
5b563f91d5e7bad48d8a90a190749bcbf09264c0
tests/test_basic.py
tests/test_basic.py
import sys import pubrunner import pubrunner.command_line import os def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main()
import sys import pubrunner import pubrunner.command_line import os import time def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1) def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1)
Add sleeps to test to avoid eutils issues
Add sleeps to test to avoid eutils issues
Python
mit
jakelever/pubrunner,jakelever/pubrunner
import sys import pubrunner import pubrunner.command_line import os def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() Add sleeps to test to avoid eutils issues
import sys import pubrunner import pubrunner.command_line import os import time def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1) def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1)
<commit_before>import sys import pubrunner import pubrunner.command_line import os def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() <commit_msg>Add sleeps to test to avoid eutils issues<commit_after>
import sys import pubrunner import pubrunner.command_line import os import time def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1) def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1)
import sys import pubrunner import pubrunner.command_line import os def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() Add sleeps to test to avoid eutils issuesimport sys import pubrunner import pubrunner.command_line import os import time def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1) def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1)
<commit_before>import sys import pubrunner import pubrunner.command_line import os def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() <commit_msg>Add sleeps to test to avoid eutils issues<commit_after>import sys import pubrunner import pubrunner.command_line import os import time def test_countwords(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','CountWords') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1) def test_textminingcounter(): parentDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) projectPath = os.path.join(parentDir,'examples','TextMiningCounter') sys.argv = ['pubrunner', '--defaultsettings', '--test',projectPath] pubrunner.command_line.main() time.sleep(1)
bfbc156d9efca37c35d18481c4366d3e6deed1ba
slave/skia_slave_scripts/chromeos_run_bench.py
slave/skia_slave_scripts/chromeos_run_bench.py
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep, BuildStepWarning from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): def _Run(self): # TODO(borenet): Re-enable this step once the crash is fixed. # RunBench._Run(self) raise BuildStepWarning('Skipping bench on ChromeOS until crash is fixed.') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): pass if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))
Stop skipping Bench on ChromeOS
Stop skipping Bench on ChromeOS (RunBuilders:Skia_ChromeOS_Alex_Debug_32) Unreviewed. git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@8094 2bbb7eff-a529-9590-31e7-b0007b416f81
Python
bsd-3-clause
Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep, BuildStepWarning from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): def _Run(self): # TODO(borenet): Re-enable this step once the crash is fixed. # RunBench._Run(self) raise BuildStepWarning('Skipping bench on ChromeOS until crash is fixed.') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))Stop skipping Bench on ChromeOS (RunBuilders:Skia_ChromeOS_Alex_Debug_32) Unreviewed. git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@8094 2bbb7eff-a529-9590-31e7-b0007b416f81
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): pass if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))
<commit_before>#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep, BuildStepWarning from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): def _Run(self): # TODO(borenet): Re-enable this step once the crash is fixed. # RunBench._Run(self) raise BuildStepWarning('Skipping bench on ChromeOS until crash is fixed.') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))<commit_msg>Stop skipping Bench on ChromeOS (RunBuilders:Skia_ChromeOS_Alex_Debug_32) Unreviewed. git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@8094 2bbb7eff-a529-9590-31e7-b0007b416f81<commit_after>
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): pass if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep, BuildStepWarning from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): def _Run(self): # TODO(borenet): Re-enable this step once the crash is fixed. # RunBench._Run(self) raise BuildStepWarning('Skipping bench on ChromeOS until crash is fixed.') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))Stop skipping Bench on ChromeOS (RunBuilders:Skia_ChromeOS_Alex_Debug_32) Unreviewed. git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@8094 2bbb7eff-a529-9590-31e7-b0007b416f81#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): pass if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))
<commit_before>#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep, BuildStepWarning from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): def _Run(self): # TODO(borenet): Re-enable this step once the crash is fixed. # RunBench._Run(self) raise BuildStepWarning('Skipping bench on ChromeOS until crash is fixed.') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))<commit_msg>Stop skipping Bench on ChromeOS (RunBuilders:Skia_ChromeOS_Alex_Debug_32) Unreviewed. git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@8094 2bbb7eff-a529-9590-31e7-b0007b416f81<commit_after>#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Run the Skia bench executable. """ from build_step import BuildStep from chromeos_build_step import ChromeOSBuildStep from run_bench import RunBench import sys class ChromeOSRunBench(ChromeOSBuildStep, RunBench): pass if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSRunBench))
e781229453a5d6d654c6ab6acae5ad2866b28f9c
tools/srenqueuer.py
tools/srenqueuer.py
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') res = requests.get(root + '/list_unhandled', auth=(username, password)) queue = json.loads(res.text) for entry in queue: stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid']) requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password))
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') try: res = requests.get(root + '/list_unhandled', auth=(username, password)) except: # For some reason, we sometimes get a requests failure here, even though # everything seems to be working fine. Ignore that, and try again later. return queue = json.loads(res.text) for entry in queue: try: requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) except: # If we fail to mark this as handled, wait until the next try so we # don't run the same thing more than once. It's not the end of the # world ot have to wait... return stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid'])
Handle exceptions better in enqueuer
Handle exceptions better in enqueuer We don't care too much, so just swallow them. People will complain at me if their "pushed" jobs don't get run (eventually).
Python
mpl-2.0
mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') res = requests.get(root + '/list_unhandled', auth=(username, password)) queue = json.loads(res.text) for entry in queue: stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid']) requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) Handle exceptions better in enqueuer We don't care too much, so just swallow them. People will complain at me if their "pushed" jobs don't get run (eventually).
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') try: res = requests.get(root + '/list_unhandled', auth=(username, password)) except: # For some reason, we sometimes get a requests failure here, even though # everything seems to be working fine. Ignore that, and try again later. return queue = json.loads(res.text) for entry in queue: try: requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) except: # If we fail to mark this as handled, wait until the next try so we # don't run the same thing more than once. It's not the end of the # world ot have to wait... return stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid'])
<commit_before>#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') res = requests.get(root + '/list_unhandled', auth=(username, password)) queue = json.loads(res.text) for entry in queue: stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid']) requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) <commit_msg>Handle exceptions better in enqueuer We don't care too much, so just swallow them. People will complain at me if their "pushed" jobs don't get run (eventually).<commit_after>
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') try: res = requests.get(root + '/list_unhandled', auth=(username, password)) except: # For some reason, we sometimes get a requests failure here, even though # everything seems to be working fine. Ignore that, and try again later. return queue = json.loads(res.text) for entry in queue: try: requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) except: # If we fail to mark this as handled, wait until the next try so we # don't run the same thing more than once. It's not the end of the # world ot have to wait... return stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid'])
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') res = requests.get(root + '/list_unhandled', auth=(username, password)) queue = json.loads(res.text) for entry in queue: stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid']) requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) Handle exceptions better in enqueuer We don't care too much, so just swallow them. People will complain at me if their "pushed" jobs don't get run (eventually).#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') try: res = requests.get(root + '/list_unhandled', auth=(username, password)) except: # For some reason, we sometimes get a requests failure here, even though # everything seems to be working fine. Ignore that, and try again later. return queue = json.loads(res.text) for entry in queue: try: requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) except: # If we fail to mark this as handled, wait until the next try so we # don't run the same thing more than once. It's not the end of the # world ot have to wait... return stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid'])
<commit_before>#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') res = requests.get(root + '/list_unhandled', auth=(username, password)) queue = json.loads(res.text) for entry in queue: stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid']) requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) <commit_msg>Handle exceptions better in enqueuer We don't care too much, so just swallow them. People will complain at me if their "pushed" jobs don't get run (eventually).<commit_after>#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public License, # v. 2.0. If a copy of the MPL was not distributed with this file, You can # obtain one at http://mozilla.org/MPL/2.0/. import json import requests import stoneridge @stoneridge.main def main(): parser = stoneridge.ArgumentParser() parser.parse_args() root = stoneridge.get_config('enqueuer', 'root') username = stoneridge.get_config('enqueuer', 'username') password = stoneridge.get_config('enqueuer', 'password') try: res = requests.get(root + '/list_unhandled', auth=(username, password)) except: # For some reason, we sometimes get a requests failure here, even though # everything seems to be working fine. Ignore that, and try again later. return queue = json.loads(res.text) for entry in queue: try: requests.post(root + '/mark_handled', data={'id': entry['pushid']}, auth=(username, password)) except: # If we fail to mark this as handled, wait until the next try so we # don't run the same thing more than once. It's not the end of the # world ot have to wait... return stoneridge.enqueue(nightly=False, ldap=entry['ldap'], sha=entry['sha'], netconfigs=entry['netconfigs'], operating_systems=entry['operating_systems'], srid=entry['srid'])
1de37d04c71713f811d057f63f505348f7124c54
{{cookiecutter.repo_name}}/config/urls.py
{{cookiecutter.repo_name}}/config/urls.py
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^users/', include('apps.users.urls', namespace='users')), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ]
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ]
Revert to old master 2
Revert to old master 2
Python
mit
ameistad/amei-django-template,ameistad/dokku-django-template,ameistad/amei-django-template,ameistad/dokku-django-template,ameistad/amei-django-template,ameistad/django-template,ameistad/amei-django-template,ameistad/dokku-django-template,ameistad/django-template,ameistad/django-template
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^users/', include('apps.users.urls', namespace='users')), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ] Revert to old master 2
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ]
<commit_before>from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^users/', include('apps.users.urls', namespace='users')), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ] <commit_msg>Revert to old master 2<commit_after>
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ]
from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^users/', include('apps.users.urls', namespace='users')), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ] Revert to old master 2from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ]
<commit_before>from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^users/', include('apps.users.urls', namespace='users')), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ] <commit_msg>Revert to old master 2<commit_after>from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', TemplateView.as_view(template_name='start.html'), name='start'), ]
86142c9893d52f3c339675c89b50f27c4bdc64e6
localtv/openid/__init__.py
localtv/openid/__init__.py
from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None): """ We assume that the openid_user has already been externally validated, and simply return the appropriate User, """ return openid_user.user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_perm(self, user_obj, perm): if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.object.get(site=site) return sitelocation.user_is_admin(user_obj)
from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None, username=None, password=None): """ If we get an openid_userassume that the openid_user has already been externally validated, and simply return the appropriate User, Otherwise, we check the username and password against the django.auth system. """ if openid_user is not None: return openid_user.user try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_group_permissions(self, user_obj): return [] def get_all_permissions(self, user_obj): return [] def has_perm(self, user_obj, perm_or_app_label): """ We use this method for both has_perm and has_module_perm since our authentication is an on-off switch, not permissions-based. """ if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.objects.get(site=site) return sitelocation.user_is_admin(user_obj) has_module_perms = has_perm
Make all users get logged in through the OpenIdBackend
Make all users get logged in through the OpenIdBackend By routing all the logins through the OpenIdBackend, we can handle the permissions checking on our own. This allows us use apps (like comments) which depend on the Django authentication system, but with our own permissions system.
Python
agpl-3.0
natea/Miro-Community,natea/Miro-Community,pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity
from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None): """ We assume that the openid_user has already been externally validated, and simply return the appropriate User, """ return openid_user.user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_perm(self, user_obj, perm): if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.object.get(site=site) return sitelocation.user_is_admin(user_obj) Make all users get logged in through the OpenIdBackend By routing all the logins through the OpenIdBackend, we can handle the permissions checking on our own. This allows us use apps (like comments) which depend on the Django authentication system, but with our own permissions system.
from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None, username=None, password=None): """ If we get an openid_userassume that the openid_user has already been externally validated, and simply return the appropriate User, Otherwise, we check the username and password against the django.auth system. """ if openid_user is not None: return openid_user.user try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_group_permissions(self, user_obj): return [] def get_all_permissions(self, user_obj): return [] def has_perm(self, user_obj, perm_or_app_label): """ We use this method for both has_perm and has_module_perm since our authentication is an on-off switch, not permissions-based. """ if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.objects.get(site=site) return sitelocation.user_is_admin(user_obj) has_module_perms = has_perm
<commit_before>from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None): """ We assume that the openid_user has already been externally validated, and simply return the appropriate User, """ return openid_user.user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_perm(self, user_obj, perm): if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.object.get(site=site) return sitelocation.user_is_admin(user_obj) <commit_msg>Make all users get logged in through the OpenIdBackend By routing all the logins through the OpenIdBackend, we can handle the permissions checking on our own. This allows us use apps (like comments) which depend on the Django authentication system, but with our own permissions system.<commit_after>
from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None, username=None, password=None): """ If we get an openid_userassume that the openid_user has already been externally validated, and simply return the appropriate User, Otherwise, we check the username and password against the django.auth system. """ if openid_user is not None: return openid_user.user try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_group_permissions(self, user_obj): return [] def get_all_permissions(self, user_obj): return [] def has_perm(self, user_obj, perm_or_app_label): """ We use this method for both has_perm and has_module_perm since our authentication is an on-off switch, not permissions-based. """ if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.objects.get(site=site) return sitelocation.user_is_admin(user_obj) has_module_perms = has_perm
from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None): """ We assume that the openid_user has already been externally validated, and simply return the appropriate User, """ return openid_user.user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_perm(self, user_obj, perm): if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.object.get(site=site) return sitelocation.user_is_admin(user_obj) Make all users get logged in through the OpenIdBackend By routing all the logins through the OpenIdBackend, we can handle the permissions checking on our own. This allows us use apps (like comments) which depend on the Django authentication system, but with our own permissions system.from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None, username=None, password=None): """ If we get an openid_userassume that the openid_user has already been externally validated, and simply return the appropriate User, Otherwise, we check the username and password against the django.auth system. """ if openid_user is not None: return openid_user.user try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_group_permissions(self, user_obj): return [] def get_all_permissions(self, user_obj): return [] def has_perm(self, user_obj, perm_or_app_label): """ We use this method for both has_perm and has_module_perm since our authentication is an on-off switch, not permissions-based. """ if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.objects.get(site=site) return sitelocation.user_is_admin(user_obj) has_module_perms = has_perm
<commit_before>from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None): """ We assume that the openid_user has already been externally validated, and simply return the appropriate User, """ return openid_user.user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_perm(self, user_obj, perm): if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.object.get(site=site) return sitelocation.user_is_admin(user_obj) <commit_msg>Make all users get logged in through the OpenIdBackend By routing all the logins through the OpenIdBackend, we can handle the permissions checking on our own. This allows us use apps (like comments) which depend on the Django authentication system, but with our own permissions system.<commit_after>from django.contrib.auth.models import User from localtv.models import SiteLocation class OpenIdBackend: def authenticate(self, openid_user=None, username=None, password=None): """ If we get an openid_userassume that the openid_user has already been externally validated, and simply return the appropriate User, Otherwise, we check the username and password against the django.auth system. """ if openid_user is not None: return openid_user.user try: user = User.objects.get(username=username) if user.check_password(password): return user except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None def get_group_permissions(self, user_obj): return [] def get_all_permissions(self, user_obj): return [] def has_perm(self, user_obj, perm_or_app_label): """ We use this method for both has_perm and has_module_perm since our authentication is an on-off switch, not permissions-based. """ if user_obj.is_superuser: return True from django.contrib.sites.models import Site site = Site.objects.get_current() sitelocation = SiteLocation.objects.get(site=site) return sitelocation.user_is_admin(user_obj) has_module_perms = has_perm