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
5b681f55896af1aec9f71bc86c1f17f60a66e4bd
pyfr/syutil.py
pyfr/syutil.py
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)]
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] def norm_jacobi(n, a, b, sym): G, F = sy.gamma, sy.factorial N2 = sy.S(2)**(a + b + 1)/(2*n + a + b + 1)\ * (G(n + a + 1)*G(n + b + 1))/(F(n)*G(n + a + b + 1)) return sy.jacobi(n, a, b, sym) / sy.sqrt(N2)
Add a function for generating normalised Jacobi polynomials.
Add a function for generating normalised Jacobi polynomials.
Python
bsd-3-clause
BrianVermeire/PyFR,tjcorona/PyFR,iyer-arvind/PyFR,tjcorona/PyFR,tjcorona/PyFR,Aerojspark/PyFR
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] Add a function for generating normalised Jacobi polynomials.
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] def norm_jacobi(n, a, b, sym): G, F = sy.gamma, sy.factorial N2 = sy.S(2)**(a + b + 1)/(2*n + a + b + 1)\ * (G(n + a + 1)*G(n + b + 1))/(F(n)*G(n + a + b + 1)) return sy.jacobi(n, a, b, sym) / sy.sqrt(N2)
<commit_before># -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] <commit_msg>Add a function for generating normalised Jacobi polynomials.<commit_after>
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] def norm_jacobi(n, a, b, sym): G, F = sy.gamma, sy.factorial N2 = sy.S(2)**(a + b + 1)/(2*n + a + b + 1)\ * (G(n + a + 1)*G(n + b + 1))/(F(n)*G(n + a + b + 1)) return sy.jacobi(n, a, b, sym) / sy.sqrt(N2)
# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] Add a function for generating normalised Jacobi polynomials.# -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] def norm_jacobi(n, a, b, sym): G, F = sy.gamma, sy.factorial N2 = sy.S(2)**(a + b + 1)/(2*n + a + b + 1)\ * (G(n + a + 1)*G(n + b + 1))/(F(n)*G(n + a + b + 1)) return sy.jacobi(n, a, b, sym) / sy.sqrt(N2)
<commit_before># -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] <commit_msg>Add a function for generating normalised Jacobi polynomials.<commit_after># -*- coding: utf-8 -*- import sympy as sy def lagrange_basis(points, sym): """Generates a basis of polynomials, :math:`l_i(x)`, such that .. math:: l_i(x) = \delta^x_{p_i} where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. """ n = len(points) lagrange_poly = sy.interpolating_poly return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() for i in xrange(n)] def norm_jacobi(n, a, b, sym): G, F = sy.gamma, sy.factorial N2 = sy.S(2)**(a + b + 1)/(2*n + a + b + 1)\ * (G(n + a + 1)*G(n + b + 1))/(F(n)*G(n + a + b + 1)) return sy.jacobi(n, a, b, sym) / sy.sqrt(N2)
2714cf4ff5639761273c91fd360f3b0c7cbf1f8b
github_ebooks.py
github_ebooks.py
#!/usr/bin/python import sys def main(argv): return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
#!/usr/bin/python import sys import argparse import codecs from Database import Database def readFromFile(path, db): f = codecs.open(path, 'r', 'utf-8') commits = [] for line in f: line = line.strip() commits.append((hash(line), line)) db.addCommits(commits) def printCommits(db): for (hash, msg) in db.allCommits(): print msg def main(argv): parser = argparse.ArgumentParser(description='github_ebooks') parser.add_argument('--api-key', dest='api_key', help='Set the API key used for scraping commits') parser.add_argument('--commit-file', dest='commit_file', help='Read commits from the given file and save them in the database') parser.add_argument('--print-commits', dest='print_commits', action='store_const', const=True, default=False) args = parser.parse_args(argv[1:]) db = Database() if args.api_key is not None: db.setConfigValue('api_key', args.api_key) if args.commit_file is not None: readFromFile(args.commit_file, db) if args.print_commits: printCommits(db) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
Add a way to scrape commits from a file.
Add a way to scrape commits from a file.
Python
mit
Fifty-Nine/github_ebooks
#!/usr/bin/python import sys def main(argv): return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) Add a way to scrape commits from a file.
#!/usr/bin/python import sys import argparse import codecs from Database import Database def readFromFile(path, db): f = codecs.open(path, 'r', 'utf-8') commits = [] for line in f: line = line.strip() commits.append((hash(line), line)) db.addCommits(commits) def printCommits(db): for (hash, msg) in db.allCommits(): print msg def main(argv): parser = argparse.ArgumentParser(description='github_ebooks') parser.add_argument('--api-key', dest='api_key', help='Set the API key used for scraping commits') parser.add_argument('--commit-file', dest='commit_file', help='Read commits from the given file and save them in the database') parser.add_argument('--print-commits', dest='print_commits', action='store_const', const=True, default=False) args = parser.parse_args(argv[1:]) db = Database() if args.api_key is not None: db.setConfigValue('api_key', args.api_key) if args.commit_file is not None: readFromFile(args.commit_file, db) if args.print_commits: printCommits(db) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
<commit_before>#!/usr/bin/python import sys def main(argv): return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) <commit_msg>Add a way to scrape commits from a file.<commit_after>
#!/usr/bin/python import sys import argparse import codecs from Database import Database def readFromFile(path, db): f = codecs.open(path, 'r', 'utf-8') commits = [] for line in f: line = line.strip() commits.append((hash(line), line)) db.addCommits(commits) def printCommits(db): for (hash, msg) in db.allCommits(): print msg def main(argv): parser = argparse.ArgumentParser(description='github_ebooks') parser.add_argument('--api-key', dest='api_key', help='Set the API key used for scraping commits') parser.add_argument('--commit-file', dest='commit_file', help='Read commits from the given file and save them in the database') parser.add_argument('--print-commits', dest='print_commits', action='store_const', const=True, default=False) args = parser.parse_args(argv[1:]) db = Database() if args.api_key is not None: db.setConfigValue('api_key', args.api_key) if args.commit_file is not None: readFromFile(args.commit_file, db) if args.print_commits: printCommits(db) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
#!/usr/bin/python import sys def main(argv): return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) Add a way to scrape commits from a file.#!/usr/bin/python import sys import argparse import codecs from Database import Database def readFromFile(path, db): f = codecs.open(path, 'r', 'utf-8') commits = [] for line in f: line = line.strip() commits.append((hash(line), line)) db.addCommits(commits) def printCommits(db): for (hash, msg) in db.allCommits(): print msg def main(argv): parser = argparse.ArgumentParser(description='github_ebooks') parser.add_argument('--api-key', dest='api_key', help='Set the API key used for scraping commits') parser.add_argument('--commit-file', dest='commit_file', help='Read commits from the given file and save them in the database') parser.add_argument('--print-commits', dest='print_commits', action='store_const', const=True, default=False) args = parser.parse_args(argv[1:]) db = Database() if args.api_key is not None: db.setConfigValue('api_key', args.api_key) if args.commit_file is not None: readFromFile(args.commit_file, db) if args.print_commits: printCommits(db) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
<commit_before>#!/usr/bin/python import sys def main(argv): return 0 if __name__ == "__main__": sys.exit(main(sys.argv)) <commit_msg>Add a way to scrape commits from a file.<commit_after>#!/usr/bin/python import sys import argparse import codecs from Database import Database def readFromFile(path, db): f = codecs.open(path, 'r', 'utf-8') commits = [] for line in f: line = line.strip() commits.append((hash(line), line)) db.addCommits(commits) def printCommits(db): for (hash, msg) in db.allCommits(): print msg def main(argv): parser = argparse.ArgumentParser(description='github_ebooks') parser.add_argument('--api-key', dest='api_key', help='Set the API key used for scraping commits') parser.add_argument('--commit-file', dest='commit_file', help='Read commits from the given file and save them in the database') parser.add_argument('--print-commits', dest='print_commits', action='store_const', const=True, default=False) args = parser.parse_args(argv[1:]) db = Database() if args.api_key is not None: db.setConfigValue('api_key', args.api_key) if args.commit_file is not None: readFromFile(args.commit_file, db) if args.print_commits: printCommits(db) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))
26b587086ad4e3eb3c9e15c2c3d96d6f7e5dba21
compshop/urls.py
compshop/urls.py
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductCatalogue, ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^products/', include('store.urls', namespace='products')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Move catalogue to products URL namespace
Move catalogue to products URL namespace
Python
bsd-3-clause
kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductCatalogue, ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Move catalogue to products URL namespace
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^products/', include('store.urls', namespace='products')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<commit_before>"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductCatalogue, ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <commit_msg>Move catalogue to products URL namespace<commit_after>
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^products/', include('store.urls', namespace='products')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductCatalogue, ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Move catalogue to products URL namespace"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^products/', include('store.urls', namespace='products')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<commit_before>"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductCatalogue, ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^catalogue/$', ProductCatalogue.as_view(), name='catalogue'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <commit_msg>Move catalogue to products URL namespace<commit_after>"""compshop URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from store.views import ProductList urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', ProductList.as_view(), name='home'), url(r'^products/', include('store.urls', namespace='products')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
e8ba913722218c86b2b705d8351795a409a514ac
pale/arguments/__init__.py
pale/arguments/__init__.py
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import FloatArgument, IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
Add FloatArgument to arguments module
Add FloatArgument to arguments module
Python
mit
Loudr/pale
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument Add FloatArgument to arguments module
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import FloatArgument, IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
<commit_before>from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument <commit_msg>Add FloatArgument to arguments module<commit_after>
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import FloatArgument, IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument Add FloatArgument to arguments modulefrom .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import FloatArgument, IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
<commit_before>from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument <commit_msg>Add FloatArgument to arguments module<commit_after>from .base import BaseArgument, ListArgument from .boolean import BooleanArgument from .number import FloatArgument, IntegerArgument from .scope import ScopeArgument from .string import StringArgument, StringListArgument from .url import URLArgument
330c90c9bc8b4c6d8df4d15f503e9a483513e5db
install/setup_pi_box.py
install/setup_pi_box.py
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Dropbox token file (dropbox.txt) not found.') print('Authorize Pi-Box and obtain the token file: blah, blah, blah') print('Save the file in: /opt/Pi-Box') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/') print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
Add URL to setup script
Add URL to setup script
Python
mit
projectweekend/Pi-Box,projectweekend/Pi-Box
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Dropbox token file (dropbox.txt) not found.') print('Authorize Pi-Box and obtain the token file: blah, blah, blah') print('Save the file in: /opt/Pi-Box') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory)) Add URL to setup script
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/') print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
<commit_before>import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Dropbox token file (dropbox.txt) not found.') print('Authorize Pi-Box and obtain the token file: blah, blah, blah') print('Save the file in: /opt/Pi-Box') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory)) <commit_msg>Add URL to setup script<commit_after>
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/') print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Dropbox token file (dropbox.txt) not found.') print('Authorize Pi-Box and obtain the token file: blah, blah, blah') print('Save the file in: /opt/Pi-Box') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory)) Add URL to setup scriptimport os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/') print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
<commit_before>import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Dropbox token file (dropbox.txt) not found.') print('Authorize Pi-Box and obtain the token file: blah, blah, blah') print('Save the file in: /opt/Pi-Box') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory)) <commit_msg>Add URL to setup script<commit_after>import os import sys import shutil if not os.path.exists('/opt/Pi-Box'): os.makedirs('/opt/Pi-Box') shutil.copy('./main.py', '/opt/Pi-Box') if not os.path.exists('/opt/Pi-Box/dropbox.txt'): print('Authorize Pi-Box and obtain the token file: http://raspberry-pi-box.herokuapp.com/') print('Copy Dropbox token file (dropbox.txt) to: /opt/Pi-Box.') print('Run the installation script again: ./install.sh') sys.exit() print("Example Pi Box path: /home/username/my-pi-box") pi_box_directory = raw_input("Pi Box path: ") if not os.path.isdir(pi_box_directory): os.makedirs(pi_box_directory) with open('./install/pi-box-conf-template.txt', 'r') as f: upstart_template = f.read() with open('/etc/init/pi-box.conf', 'w+') as f: f.write(upstart_template.format(pi_box_directory))
69cd2732bb629a52da81b865497089c19f29407a
examples/juniper/get-interface-status.py
examples/juniper/get-interface-status.py
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') interface_dict = dict() for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print "{}-{}".format(name, status) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!')
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print ("{}-{}".format(name, status)) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!')
Remove unused statement & format for python3
Remove unused statement & format for python3
Python
apache-2.0
GIC-de/ncclient,leopoul/ncclient,earies/ncclient,einarnn/ncclient,vnitinv/ncclient,ncclient/ncclient,nwautomator/ncclient
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') interface_dict = dict() for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print "{}-{}".format(name, status) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!') Remove unused statement & format for python3
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print ("{}-{}".format(name, status)) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!')
<commit_before>#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') interface_dict = dict() for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print "{}-{}".format(name, status) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!') <commit_msg>Remove unused statement & format for python3<commit_after>
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print ("{}-{}".format(name, status)) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!')
#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') interface_dict = dict() for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print "{}-{}".format(name, status) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!') Remove unused statement & format for python3#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print ("{}-{}".format(name, status)) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!')
<commit_before>#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') interface_dict = dict() for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print "{}-{}".format(name, status) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!') <commit_msg>Remove unused statement & format for python3<commit_after>#!/usr/bin/env python # Python script to fetch interface name and their operation status from ncclient import manager def connect(host, port, user, password): conn = manager.connect(host=host, port=port, username=user, password=password, timeout=10, device_params = {'name':'junos'}, hostkey_verify=False) rpc = "<get-interface-information><terse/></get-interface-information>" response = conn.rpc(rpc) interface_name = response.xpath('//physical-interface/name') interface_status = response.xpath('//physical-interface/oper-status') for name, status in zip(interface_name, interface_status): name = name.text.split('\n')[1] status = status.text.split('\n')[1] print ("{}-{}".format(name, status)) if __name__ == '__main__': connect('router', 830, 'netconf', 'juniper!')
91865fc50b66dc261cf05bba21a371e1130b25f5
integration-test/605-crosswalk-sidewalk.py
integration-test/605-crosswalk-sidewalk.py
# http://www.openstreetmap.org/way/367477828 assert_has_feature( 16, 10471, 25331, 'roads', { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
# http://www.openstreetmap.org/way/444491374 assert_has_feature( 16, 10475, 25332, 'roads', { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
Update osm way used due to data change
Update osm way used due to data change
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
# http://www.openstreetmap.org/way/367477828 assert_has_feature( 16, 10471, 25331, 'roads', { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' }) Update osm way used due to data change
# http://www.openstreetmap.org/way/444491374 assert_has_feature( 16, 10475, 25332, 'roads', { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
<commit_before># http://www.openstreetmap.org/way/367477828 assert_has_feature( 16, 10471, 25331, 'roads', { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' }) <commit_msg>Update osm way used due to data change<commit_after>
# http://www.openstreetmap.org/way/444491374 assert_has_feature( 16, 10475, 25332, 'roads', { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
# http://www.openstreetmap.org/way/367477828 assert_has_feature( 16, 10471, 25331, 'roads', { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' }) Update osm way used due to data change# http://www.openstreetmap.org/way/444491374 assert_has_feature( 16, 10475, 25332, 'roads', { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
<commit_before># http://www.openstreetmap.org/way/367477828 assert_has_feature( 16, 10471, 25331, 'roads', { 'id': 367477828, 'kind': 'path', 'crossing': 'zebra' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' }) <commit_msg>Update osm way used due to data change<commit_after># http://www.openstreetmap.org/way/444491374 assert_has_feature( 16, 10475, 25332, 'roads', { 'id': 444491374, 'kind': 'path', 'crossing': 'traffic_signals' }) # Way: The Embarcadero (397140734) # http://www.openstreetmap.org/way/397140734 assert_has_feature( 16, 10486, 25326, 'roads', { 'id': 397140734, 'kind': 'major_road', 'sidewalk': 'separate' }) # Way: Carrie Furnace Boulevard (438362919) # http://www.openstreetmap.org/way/438362919 assert_has_feature( 16, 18225, 24712, 'roads', { 'id': 438362919, 'kind': 'major_road', 'sidewalk_left': 'sidepath', 'sidewalk_right': 'no' })
71db89cad06dc0aa81e0a7178712e8beb7e7cb01
turbustat/tests/test_cramer.py
turbustat/tests/test_cramer.py
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def test_cramer(self): self.tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"]) self.tester2.distance_metric(normalize=False) self.tester3 = Cramer_Distance(dataset2["cube"], small_data) self.tester3.distance_metric(normalize=False) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance)
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances def test_cramer(): tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(): small_data = dataset1["cube"][0][:, :26, :26] tester2 = Cramer_Distance(small_data, dataset2["cube"]) tester2.distance_metric(normalize=False) tester3 = Cramer_Distance(dataset2["cube"], small_data) tester3.distance_metric(normalize=False) npt.assert_almost_equal(tester2.distance, tester3.distance)
Remove importing UnitCase from Cramer tests
Remove importing UnitCase from Cramer tests
Python
mit
Astroua/TurbuStat,e-koch/TurbuStat
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def test_cramer(self): self.tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"]) self.tester2.distance_metric(normalize=False) self.tester3 = Cramer_Distance(dataset2["cube"], small_data) self.tester3.distance_metric(normalize=False) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance) Remove importing UnitCase from Cramer tests
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances def test_cramer(): tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(): small_data = dataset1["cube"][0][:, :26, :26] tester2 = Cramer_Distance(small_data, dataset2["cube"]) tester2.distance_metric(normalize=False) tester3 = Cramer_Distance(dataset2["cube"], small_data) tester3.distance_metric(normalize=False) npt.assert_almost_equal(tester2.distance, tester3.distance)
<commit_before># Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def test_cramer(self): self.tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"]) self.tester2.distance_metric(normalize=False) self.tester3 = Cramer_Distance(dataset2["cube"], small_data) self.tester3.distance_metric(normalize=False) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance) <commit_msg>Remove importing UnitCase from Cramer tests<commit_after>
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances def test_cramer(): tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(): small_data = dataset1["cube"][0][:, :26, :26] tester2 = Cramer_Distance(small_data, dataset2["cube"]) tester2.distance_metric(normalize=False) tester3 = Cramer_Distance(dataset2["cube"], small_data) tester3.distance_metric(normalize=False) npt.assert_almost_equal(tester2.distance, tester3.distance)
# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def test_cramer(self): self.tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"]) self.tester2.distance_metric(normalize=False) self.tester3 = Cramer_Distance(dataset2["cube"], small_data) self.tester3.distance_metric(normalize=False) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance) Remove importing UnitCase from Cramer tests# Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances def test_cramer(): tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(): small_data = dataset1["cube"][0][:, :26, :26] tester2 = Cramer_Distance(small_data, dataset2["cube"]) tester2.distance_metric(normalize=False) tester3 = Cramer_Distance(dataset2["cube"], small_data) tester3.distance_metric(normalize=False) npt.assert_almost_equal(tester2.distance, tester3.distance)
<commit_before># Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' from unittest import TestCase import numpy as np import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances class testCramer(TestCase): def test_cramer(self): self.tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(self.tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(self.tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(self): small_data = dataset1["cube"][0][:, :26, :26] self.tester2 = Cramer_Distance(small_data, dataset2["cube"]) self.tester2.distance_metric(normalize=False) self.tester3 = Cramer_Distance(dataset2["cube"], small_data) self.tester3.distance_metric(normalize=False) npt.assert_almost_equal(self.tester2.distance, self.tester3.distance) <commit_msg>Remove importing UnitCase from Cramer tests<commit_after># Licensed under an MIT open source license - see LICENSE ''' Test functions for Cramer ''' import numpy.testing as npt from ..statistics import Cramer_Distance from ._testing_data import \ dataset1, dataset2, computed_data, computed_distances def test_cramer(): tester = \ Cramer_Distance(dataset1["cube"], dataset2["cube"], noise_value1=0.1, noise_value2=0.1).distance_metric(normalize=False) npt.assert_allclose(tester.data_matrix1, computed_data["cramer_val"]) npt.assert_almost_equal(tester.distance, computed_distances['cramer_distance']) def test_cramer_spatial_diff(): small_data = dataset1["cube"][0][:, :26, :26] tester2 = Cramer_Distance(small_data, dataset2["cube"]) tester2.distance_metric(normalize=False) tester3 = Cramer_Distance(dataset2["cube"], small_data) tester3.distance_metric(normalize=False) npt.assert_almost_equal(tester2.distance, tester3.distance)
b4525469d227e1878e9ded3f541577b3487b7d9e
run_game.py
run_game.py
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import sys sys.path.insert(0, 'pyglet-c9188efc2e30') import getopt import os import ookoobah.main def run(): ookoobah.main.main() if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) # Start the actual game run()
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import os import sys import getopt if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) sys.path.insert(0, 'pyglet-c9188efc2e30') import ookoobah.main ookoobah.main.main()
Fix pyglet and game loading.
Fix pyglet and game loading.
Python
mit
vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import sys sys.path.insert(0, 'pyglet-c9188efc2e30') import getopt import os import ookoobah.main def run(): ookoobah.main.main() if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) # Start the actual game run() Fix pyglet and game loading.
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import os import sys import getopt if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) sys.path.insert(0, 'pyglet-c9188efc2e30') import ookoobah.main ookoobah.main.main()
<commit_before>#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import sys sys.path.insert(0, 'pyglet-c9188efc2e30') import getopt import os import ookoobah.main def run(): ookoobah.main.main() if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) # Start the actual game run() <commit_msg>Fix pyglet and game loading.<commit_after>
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import os import sys import getopt if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) sys.path.insert(0, 'pyglet-c9188efc2e30') import ookoobah.main ookoobah.main.main()
#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import sys sys.path.insert(0, 'pyglet-c9188efc2e30') import getopt import os import ookoobah.main def run(): ookoobah.main.main() if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) # Start the actual game run() Fix pyglet and game loading.#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import os import sys import getopt if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) sys.path.insert(0, 'pyglet-c9188efc2e30') import ookoobah.main ookoobah.main.main()
<commit_before>#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import sys sys.path.insert(0, 'pyglet-c9188efc2e30') import getopt import os import ookoobah.main def run(): ookoobah.main.main() if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) # Start the actual game run() <commit_msg>Fix pyglet and game loading.<commit_after>#!/usr/bin/env python """Point of execution for play. Configures module path and libraries and then calls lib.main.main. """ import os import sys import getopt if __name__ == "__main__": # Change to the game directory os.chdir(os.path.dirname(os.path.join(".", sys.argv[0]))) sys.path.insert(0, 'pyglet-c9188efc2e30') import ookoobah.main ookoobah.main.main()
10ec59777c0b364e05dc022ac3178d0c6d0ca916
plugin/formatters.py
plugin/formatters.py
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return None, 'Invalid JSON'
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON'
Fix parsing of JSON formatting errors
Fix parsing of JSON formatting errors
Python
mit
Rypac/sublime-format
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return None, 'Invalid JSON' Fix parsing of JSON formatting errors
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON'
<commit_before>import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return None, 'Invalid JSON' <commit_msg>Fix parsing of JSON formatting errors<commit_after>
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON'
import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return None, 'Invalid JSON' Fix parsing of JSON formatting errorsimport json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON'
<commit_before>import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return None, 'Invalid JSON' <commit_msg>Fix parsing of JSON formatting errors<commit_after>import json from collections import OrderedDict def format_json(input, settings=None): indent = 4 if settings: indent = settings.get('tab_size', indent) try: data = json.loads(input, object_pairs_hook=OrderedDict) return True, json.dumps(data, indent=indent, separators=(',', ': ')), None except ValueError: return False, None, 'Invalid JSON'
ae3092cfeb99f89e98517e9db29d8f013fceb1c5
touchdown/tests/test_ssh_client.py
touchdown/tests/test_ssh_client.py
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff.
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): @unittest.skip('test doesn\'t work on CI') def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff.
Disable tests that don't work on travis
Tests: Disable tests that don't work on travis
Python
apache-2.0
yaybu/touchdown
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff. Tests: Disable tests that don't work on travis
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): @unittest.skip('test doesn\'t work on CI') def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff.
<commit_before># Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff. <commit_msg>Tests: Disable tests that don't work on travis<commit_after>
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): @unittest.skip('test doesn\'t work on CI') def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff.
# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff. Tests: Disable tests that don't work on travis# Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): @unittest.skip('test doesn\'t work on CI') def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff.
<commit_before># Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff. <commit_msg>Tests: Disable tests that don't work on travis<commit_after># Copyright 2015 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import mock from touchdown.tests.fixtures.ssh_connection import SshConnectionFixture from touchdown.tests.testcases import WorkspaceTestCase class TestSshClient(WorkspaceTestCase): @unittest.skip('test doesn\'t work on CI') def test_ssh_client(self): goal = self.create_goal('ssh') ssh_connection = self.fixtures.enter_context(SshConnectionFixture(goal, self.workspace)) connection_plan = goal.get_service(ssh_connection.ssh_connection, 'describe') self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.verify_transport')) self.fixtures.enter_context(mock.patch('touchdown.ssh.client.Client.set_input_encoding')) connection_plan.get_client() # FIXME: How to make the dummy server run stuff? Or fake run stuff.
ac571170c4ba8db7899c0323778933edc46dd025
salt/runners/pillar.py
salt/runners/pillar.py
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains = salt.utils.minions.get_grains(minion) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top
Use the new get_minion_data function
Use the new get_minion_data function
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains = salt.utils.minions.get_grains(minion) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top Use the new get_minion_data function
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top
<commit_before># -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains = salt.utils.minions.get_grains(minion) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top <commit_msg>Use the new get_minion_data function<commit_after>
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top
# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains = salt.utils.minions.get_grains(minion) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top Use the new get_minion_data function# -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top
<commit_before># -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains = salt.utils.minions.get_grains(minion) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top <commit_msg>Use the new get_minion_data function<commit_after># -*- coding: utf-8 -*- ''' Functions to interact with the pillar compiler on the master ''' # Import salt libs import salt.pillar import salt.utils.minions def show_top(minion=None, saltenv='base'): ''' Returns the compiled top data for pillar for a specific minion. If no minion is specified, we use the first minion we find. CLI Example: .. code-block:: bash salt-run pillar.show_top ''' id_, grains, _ = salt.utils.minions.get_minion_data(minion, __opts__) pillar = salt.pillar.Pillar( __opts__, grains, id_, saltenv) top, errors = pillar.get_top() if errors: return errors return top
e70856cb18fa86f955dda6cb18cddbdc431a5577
chipy_org/libs/social_auth_pipelines.py
chipy_org/libs/social_auth_pipelines.py
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if is_new: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
Revert "Fixes to the create_user pipeline"
Revert "Fixes to the create_user pipeline" This reverts commit 49dd1b5205498425f7af247f7c390a48a423db4c.
Python
mit
chicagopython/chipy.org,brianray/chipy.org,brianray/chipy.org,bharathelangovan/chipy.org,bharathelangovan/chipy.org,chicagopython/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,tanyaschlusser/chipy.org,agfor/chipy.org,chicagopython/chipy.org,brianray/chipy.org,bharathelangovan/chipy.org,agfor/chipy.org
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if is_new: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {} Revert "Fixes to the create_user pipeline" This reverts commit 49dd1b5205498425f7af247f7c390a48a423db4c.
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
<commit_before>from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if is_new: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {} <commit_msg>Revert "Fixes to the create_user pipeline" This reverts commit 49dd1b5205498425f7af247f7c390a48a423db4c.<commit_after>
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if is_new: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {} Revert "Fixes to the create_user pipeline" This reverts commit 49dd1b5205498425f7af247f7c390a48a423db4c.from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
<commit_before>from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if is_new: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {} <commit_msg>Revert "Fixes to the create_user pipeline" This reverts commit 49dd1b5205498425f7af247f7c390a48a423db4c.<commit_after>from django.utils.translation import ugettext from django.contrib.auth.models import User from social_auth.backends.pipeline.user import create_user as social_auth_create_user from social_auth.exceptions import AuthAlreadyAssociated def create_user(backend, details, response, uid, username, user = None, is_new = False, *args, **kwargs): ''' Check if a user with this email already exists. If they do, don't create an account. ''' if not user: if User.objects.filter(email = details.get('email')).exists(): msg = ugettext('This email is already in use. First login with your other account and under the top right menu click add account.') raise AuthAlreadyAssociated(backend, msg % { 'provider': backend.name }) else: return social_auth_create_user(backend, details, response, uid, username, user = None, *args, **kwargs) else: return {}
e097c4f6c6333a7017642d376f8dd158b4a963b2
package_monitor/migrations/0007_add_django_version_info.py
package_monitor/migrations/0007_add_django_version_info.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name=b'python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name='python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
Fix up migrations, part 2
Fix up migrations, part 2
Python
mit
yunojuno/django-package-monitor,yunojuno/django-package-monitor
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name=b'python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ] Fix up migrations, part 2
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name='python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name=b'python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ] <commit_msg>Fix up migrations, part 2<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name='python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name=b'python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ] Fix up migrations, part 2# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name='python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
<commit_before># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name=b'python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ] <commit_msg>Fix up migrations, part 2<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('package_monitor', '0006_add_python_version_info'), ] operations = [ migrations.AddField( model_name='packageversion', name='django_support', field=models.CharField(help_text=b'Django version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), migrations.AlterField( model_name='packageversion', name='python_support', field=models.CharField(help_text=b'Python version support as specified in the PyPI classifiers.', max_length=100, null=True, blank=True), ), ]
e09af91b45355294c16249bcd3c0bf07982cd39c
websaver/parsed_data/models.py
websaver/parsed_data/models.py
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
Add fpp k/d data to the model.
Add fpp k/d data to the model.
Python
mit
aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler,aiirohituzi/myWebCrawler
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userNameAdd fpp k/d data to the model.
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
<commit_before>from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName<commit_msg>Add fpp k/d data to the model.<commit_after>
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userNameAdd fpp k/d data to the model.from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
<commit_before>from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName<commit_msg>Add fpp k/d data to the model.<commit_after>from django.db import models # Create your models here. class RatingData(models.Model): userName = models.CharField(max_length=30) solofpp = models.CharField(max_length=5, null=True) duofpp = models.CharField(max_length=5, null=True) squadfpp = models.CharField(max_length=5, null=True) solo = models.CharField(max_length=5, null=True) duo = models.CharField(max_length=5, null=True) squad = models.CharField(max_length=5, null=True) solokd = models.CharField(max_length=5, null=True) duokd = models.CharField(max_length=5, null=True) squadkd = models.CharField(max_length=5, null=True) solofppkd = models.CharField(max_length=5, null=True) duofppkd = models.CharField(max_length=5, null=True) squadfppkd = models.CharField(max_length=5, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('created_at',) def __str__(self): return self.userName
1ee8f9dcb74d65e22bf785692a696ec743bcb932
pyatmlab/__init__.py
pyatmlab/__init__.py
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry()
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() ureg.define("micro- = 1e-6 = µ-")
Use µ- prefix rather than u-
Use µ- prefix rather than u-
Python
bsd-3-clause
olemke/pyatmlab,gerritholl/pyatmlab
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() Use µ- prefix rather than u-
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() ureg.define("micro- = 1e-6 = µ-")
<commit_before>#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() <commit_msg>Use µ- prefix rather than u-<commit_after>
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() ureg.define("micro- = 1e-6 = µ-")
#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() Use µ- prefix rather than u-#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() ureg.define("micro- = 1e-6 = µ-")
<commit_before>#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() <commit_msg>Use µ- prefix rather than u-<commit_after>#!/usr/bin/env python from . import meta __version__ = "0.1.0+" __doc__ = """This is pyatmlab """ from pint import UnitRegistry ureg = UnitRegistry() ureg.define("micro- = 1e-6 = µ-")
fe547c93a476b5093930ff08fef8fe48a16dc930
examples/monitoring/ligier_mirror.py
examples/monitoring/ligier_mirror.py
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain()
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. This script is also available as a command line utility in km3pipe, which can be accessed by the command ``ligiermirror``. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain()
Add ref to ligiermirror CLU
Add ref to ligiermirror CLU
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain() Add ref to ligiermirror CLU
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. This script is also available as a command line utility in km3pipe, which can be accessed by the command ``ligiermirror``. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain()
<commit_before>#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain() <commit_msg>Add ref to ligiermirror CLU<commit_after>
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. This script is also available as a command line utility in km3pipe, which can be accessed by the command ``ligiermirror``. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain()
#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain() Add ref to ligiermirror CLU#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. This script is also available as a command line utility in km3pipe, which can be accessed by the command ``ligiermirror``. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain()
<commit_before>#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain() <commit_msg>Add ref to ligiermirror CLU<commit_after>#!/usr/bin/env python # coding=utf-8 # vim: ts=4 sw=4 et """ ============= Ligier Mirror ============= Subscribes to given tag(s) and sends them to another Ligier. This script is also available as a command line utility in km3pipe, which can be accessed by the command ``ligiermirror``. """ # Author: Tamas Gal <tgal@km3net.de> # License: MIT from __future__ import division import socket from km3pipe import Pipeline, Module from km3pipe.io import CHPump class LigierSender(Module): def configure(self): self.ligier = self.get("ligier") or "127.0.0.1" self.port = self.get("port") or 5553 self.socket = socket.socket() self.client = self.socket.connect((self.ligier, self.port)) def process(self, blob): self.socket.send(blob["CHPrefix"].data + blob["CHData"]) def finish(self): self.socket.close() pipe = Pipeline() pipe.attach(CHPump, host='192.168.0.121', port=5553, tags='IO_EVT, IO_SUM, IO_TSL', timeout=60 * 60 * 24 * 7, max_queue=2000) pipe.attach(LigierSender) pipe.drain()
8e5a84a62662779cbf3965f5460b320f68d66c6a
alg_strongly_connected_graph.py
alg_strongly_connected_graph.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graph by Kosaraju's Algorithm.""" def main(): pass if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graphs by Kosaraju's Algorithm.""" def main(): adjacency_dict = { 'A': {'B'}, 'B': {'C', 'E'}, 'C': {'C', 'F'}, 'D': {'B', 'G'}, 'E': {'A', 'D'}, 'F': {'H'}, 'G': {'E'}, 'H': {'I'}, 'I': {'F'} } if __name__ == '__main__': main()
Add adjacency_dict for strongly connected graphs
Add adjacency_dict for strongly connected graphs
Python
bsd-2-clause
bowen0701/algorithms_data_structures
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graph by Kosaraju's Algorithm.""" def main(): pass if __name__ == '__main__': main() Add adjacency_dict for strongly connected graphs
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graphs by Kosaraju's Algorithm.""" def main(): adjacency_dict = { 'A': {'B'}, 'B': {'C', 'E'}, 'C': {'C', 'F'}, 'D': {'B', 'G'}, 'E': {'A', 'D'}, 'F': {'H'}, 'G': {'E'}, 'H': {'I'}, 'I': {'F'} } if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graph by Kosaraju's Algorithm.""" def main(): pass if __name__ == '__main__': main() <commit_msg>Add adjacency_dict for strongly connected graphs<commit_after>
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graphs by Kosaraju's Algorithm.""" def main(): adjacency_dict = { 'A': {'B'}, 'B': {'C', 'E'}, 'C': {'C', 'F'}, 'D': {'B', 'G'}, 'E': {'A', 'D'}, 'F': {'H'}, 'G': {'E'}, 'H': {'I'}, 'I': {'F'} } if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graph by Kosaraju's Algorithm.""" def main(): pass if __name__ == '__main__': main() Add adjacency_dict for strongly connected graphsfrom __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graphs by Kosaraju's Algorithm.""" def main(): adjacency_dict = { 'A': {'B'}, 'B': {'C', 'E'}, 'C': {'C', 'F'}, 'D': {'B', 'G'}, 'E': {'A', 'D'}, 'F': {'H'}, 'G': {'E'}, 'H': {'I'}, 'I': {'F'} } if __name__ == '__main__': main()
<commit_before>from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graph by Kosaraju's Algorithm.""" def main(): pass if __name__ == '__main__': main() <commit_msg>Add adjacency_dict for strongly connected graphs<commit_after>from __future__ import absolute_import from __future__ import print_function from __future__ import division def dfs_recur(): pass def traverse_dfs_recur(): pass def transpose_graph(): pass def strongly_connected_graph(): """Find strongly connected graphs by Kosaraju's Algorithm.""" def main(): adjacency_dict = { 'A': {'B'}, 'B': {'C', 'E'}, 'C': {'C', 'F'}, 'D': {'B', 'G'}, 'E': {'A', 'D'}, 'F': {'H'}, 'G': {'E'}, 'H': {'I'}, 'I': {'F'} } if __name__ == '__main__': main()
201863f214e54feca811185151bf953d1eedca6d
app/ml_models/affect_ai_test.py
app/ml_models/affect_ai_test.py
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
Write part of a test
chore: Write part of a test
Python
mit
OmegaHorizonResearch/agile-analyst
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass chore: Write part of a test
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
<commit_before>import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass <commit_msg>chore: Write part of a test<commit_after>
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass chore: Write part of a testimport affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
<commit_before>import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass <commit_msg>chore: Write part of a test<commit_after>import affect_ai import pytest # words: foo, bar, baz, goo, car, caz, hoo, dar, daz, ioo, ear, eaz, loo, far, faz; corpora: happiness 1, satisfaction 2, elation 2, 3 ai = affect_ai.affect_AI(15, 5) # Test that an affect_AI object gets created correctly def test_creation(): # We create an affect_ai object with some parameters # We make sure those parameters do what they should within the object assert ai.vocab_size == 15 pass # Test that an affect_AI object can be trained, and builds vocabulary correctly def test_training(): # We try to pass in corpora to the affect_ai object we created earlier # We make sure its internal objects change as they should pass # Test that an affect_AI object correctly scores samples def test_scoring(): # We have the affect_ai score a sample of words containing some of its trained words # We compare the scored result to what we know it should be pass
6c3f869150e5797c06b5f63758280b60e296d658
core/admin.py
core/admin.py
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm def get_actions_replacer(orig_func): def fixed_get_actions(self, request): """ Remove the delete action (if present) if user does not have the necessary permission """ # Get the base actions actions = orig_func(self, request) # Get the app label and model name to form the permission name app_label = self.model._meta.app_label model_name = self.model._meta.model_name perm = "%s.delete_%s" % (app_label, model_name) # If the user does not have the specific delete perm, remove the action if not request.user.has_perm(perm): if 'delete_selected' in actions: del actions['delete_selected'] return actions return fixed_get_actions admin.ModelAdmin.get_actions = get_actions_replacer(admin.ModelAdmin.get_actions)
Remove the bulk delete action if the user does not have delete permissions on the model being viewed
Remove the bulk delete action if the user does not have delete permissions on the model being viewed
Python
mit
uktrade/navigator,uktrade/navigator,uktrade/navigator,uktrade/navigator
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm Remove the bulk delete action if the user does not have delete permissions on the model being viewed
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm def get_actions_replacer(orig_func): def fixed_get_actions(self, request): """ Remove the delete action (if present) if user does not have the necessary permission """ # Get the base actions actions = orig_func(self, request) # Get the app label and model name to form the permission name app_label = self.model._meta.app_label model_name = self.model._meta.model_name perm = "%s.delete_%s" % (app_label, model_name) # If the user does not have the specific delete perm, remove the action if not request.user.has_perm(perm): if 'delete_selected' in actions: del actions['delete_selected'] return actions return fixed_get_actions admin.ModelAdmin.get_actions = get_actions_replacer(admin.ModelAdmin.get_actions)
<commit_before>from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm <commit_msg>Remove the bulk delete action if the user does not have delete permissions on the model being viewed<commit_after>
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm def get_actions_replacer(orig_func): def fixed_get_actions(self, request): """ Remove the delete action (if present) if user does not have the necessary permission """ # Get the base actions actions = orig_func(self, request) # Get the app label and model name to form the permission name app_label = self.model._meta.app_label model_name = self.model._meta.model_name perm = "%s.delete_%s" % (app_label, model_name) # If the user does not have the specific delete perm, remove the action if not request.user.has_perm(perm): if 'delete_selected' in actions: del actions['delete_selected'] return actions return fixed_get_actions admin.ModelAdmin.get_actions = get_actions_replacer(admin.ModelAdmin.get_actions)
from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm Remove the bulk delete action if the user does not have delete permissions on the model being viewedfrom django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm def get_actions_replacer(orig_func): def fixed_get_actions(self, request): """ Remove the delete action (if present) if user does not have the necessary permission """ # Get the base actions actions = orig_func(self, request) # Get the app label and model name to form the permission name app_label = self.model._meta.app_label model_name = self.model._meta.model_name perm = "%s.delete_%s" % (app_label, model_name) # If the user does not have the specific delete perm, remove the action if not request.user.has_perm(perm): if 'delete_selected' in actions: del actions['delete_selected'] return actions return fixed_get_actions admin.ModelAdmin.get_actions = get_actions_replacer(admin.ModelAdmin.get_actions)
<commit_before>from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm <commit_msg>Remove the bulk delete action if the user does not have delete permissions on the model being viewed<commit_after>from django.contrib import admin from django.contrib.admin.forms import AdminAuthenticationForm from django import forms class NavigatorLoginForm(AdminAuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'autocomplete': 'off'})) admin.site.login_form = NavigatorLoginForm def get_actions_replacer(orig_func): def fixed_get_actions(self, request): """ Remove the delete action (if present) if user does not have the necessary permission """ # Get the base actions actions = orig_func(self, request) # Get the app label and model name to form the permission name app_label = self.model._meta.app_label model_name = self.model._meta.model_name perm = "%s.delete_%s" % (app_label, model_name) # If the user does not have the specific delete perm, remove the action if not request.user.has_perm(perm): if 'delete_selected' in actions: del actions['delete_selected'] return actions return fixed_get_actions admin.ModelAdmin.get_actions = get_actions_replacer(admin.ModelAdmin.get_actions)
8b51c9904fd09354ff5385fc1740d9270da8287c
should-I-boot-this.py
should-I-boot-this.py
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.environ['LAB'] not in config.sections(): print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) sys.exit(0) # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
Allow boots for unknown labs
jenkins: Allow boots for unknown labs Signed-off-by: Florent Jacquet <692930aa2e4df70616939784b5b6c25eb1f2335c@free-electrons.com>
Python
lgpl-2.1
kernelci/lava-ci-staging,kernelci/lava-ci-staging,kernelci/lava-ci-staging
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0) jenkins: Allow boots for unknown labs Signed-off-by: Florent Jacquet <692930aa2e4df70616939784b5b6c25eb1f2335c@free-electrons.com>
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.environ['LAB'] not in config.sections(): print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) sys.exit(0) # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
<commit_before>#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0) <commit_msg>jenkins: Allow boots for unknown labs Signed-off-by: Florent Jacquet <692930aa2e4df70616939784b5b6c25eb1f2335c@free-electrons.com><commit_after>
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.environ['LAB'] not in config.sections(): print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) sys.exit(0) # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0) jenkins: Allow boots for unknown labs Signed-off-by: Florent Jacquet <692930aa2e4df70616939784b5b6c25eb1f2335c@free-electrons.com>#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.environ['LAB'] not in config.sections(): print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) sys.exit(0) # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
<commit_before>#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Check if we need to stop here if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0) <commit_msg>jenkins: Allow boots for unknown labs Signed-off-by: Florent Jacquet <692930aa2e4df70616939784b5b6c25eb1f2335c@free-electrons.com><commit_after>#!/usr/bin/env python3 # -*- coding:utf-8 -* # import os import sys import configparser """ To test the script, just export those variables and play with their values export LAB=lab-free-electrons export TREE=mainline """ config = configparser.ConfigParser() config.read('labs.ini') # Is the lab existing? if os.environ['LAB'] not in config.sections(): print("Unknown lab (%s). Allowing boot of %s." % (os.environ['LAB'], os.environ['TREE'])) sys.exit(0) # Is the tree blacklisted for this lab? if os.environ['TREE'] in config[os.environ['LAB']]['tree_blacklist'].split(): print("Tree '%s' is blacklisted for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(1) print("Booting tree '%s' is allowed for lab '%s'" % (os.environ['TREE'], os.environ['LAB'])) sys.exit(0)
2434c06d806fd10832ebae73408021dbc1470269
test_settings.py
test_settings.py
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # See setup.py for an explanation as to why these aren't enabled by default ''' INSTALLED_APPS += ( 'banner', #'jmbo_calendar', # requires atlas 'chart', #'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', #'show', # requires jmbo_calendar #'jmbo_twitter', ) ''' CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Foundry provides high-level testing tools for other content types INSTALLED_APPS += ( 'banner', 'jmbo_calendar', 'chart', 'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', 'show', 'jmbo_twitter', ) CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
Test all the Jmbo content types
Test all the Jmbo content types
Python
bsd-3-clause
praekelt/jmbo-foundry,praekelt/jmbo-foundry,praekelt/jmbo-foundry
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # See setup.py for an explanation as to why these aren't enabled by default ''' INSTALLED_APPS += ( 'banner', #'jmbo_calendar', # requires atlas 'chart', #'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', #'show', # requires jmbo_calendar #'jmbo_twitter', ) ''' CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False Test all the Jmbo content types
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Foundry provides high-level testing tools for other content types INSTALLED_APPS += ( 'banner', 'jmbo_calendar', 'chart', 'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', 'show', 'jmbo_twitter', ) CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
<commit_before>from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # See setup.py for an explanation as to why these aren't enabled by default ''' INSTALLED_APPS += ( 'banner', #'jmbo_calendar', # requires atlas 'chart', #'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', #'show', # requires jmbo_calendar #'jmbo_twitter', ) ''' CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False <commit_msg>Test all the Jmbo content types<commit_after>
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Foundry provides high-level testing tools for other content types INSTALLED_APPS += ( 'banner', 'jmbo_calendar', 'chart', 'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', 'show', 'jmbo_twitter', ) CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # See setup.py for an explanation as to why these aren't enabled by default ''' INSTALLED_APPS += ( 'banner', #'jmbo_calendar', # requires atlas 'chart', #'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', #'show', # requires jmbo_calendar #'jmbo_twitter', ) ''' CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False Test all the Jmbo content typesfrom os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Foundry provides high-level testing tools for other content types INSTALLED_APPS += ( 'banner', 'jmbo_calendar', 'chart', 'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', 'show', 'jmbo_twitter', ) CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
<commit_before>from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # See setup.py for an explanation as to why these aren't enabled by default ''' INSTALLED_APPS += ( 'banner', #'jmbo_calendar', # requires atlas 'chart', #'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', #'show', # requires jmbo_calendar #'jmbo_twitter', ) ''' CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False <commit_msg>Test all the Jmbo content types<commit_after>from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } # Foundry provides high-level testing tools for other content types INSTALLED_APPS += ( 'banner', 'jmbo_calendar', 'chart', 'competition', 'downloads', 'friends', 'gallery', 'music', 'poll', 'show', 'jmbo_twitter', ) CKEDITOR_UPLOAD_PATH = expanduser('~') # Disable celery CELERY_ALWAYS_EAGER = True BROKER_BACKEND = 'memory' # xxx: get tests to pass with migrations SOUTH_TESTS_MIGRATE = False
038a905e58c42881c12d53911eb70926cfbc76f2
nsq/util.py
nsq/util.py
'''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack( struct.pack('>l', len(message)) + ''.join(map(pack, message))) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
'''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
Fix failing test about passing nested iterables to pack
Fix failing test about passing nested iterables to pack
Python
mit
dlecocq/nsq-py,dlecocq/nsq-py
'''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack( struct.pack('>l', len(message)) + ''.join(map(pack, message))) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj) Fix failing test about passing nested iterables to pack
'''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
<commit_before>'''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack( struct.pack('>l', len(message)) + ''.join(map(pack, message))) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj) <commit_msg>Fix failing test about passing nested iterables to pack<commit_after>
'''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
'''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack( struct.pack('>l', len(message)) + ''.join(map(pack, message))) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj) Fix failing test about passing nested iterables to pack'''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
<commit_before>'''Some utilities used around town''' import struct def pack(message): '''Pack the provided message''' if isinstance(message, basestring): # Return # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message else: # Return # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack( struct.pack('>l', len(message)) + ''.join(map(pack, message))) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj) <commit_msg>Fix failing test about passing nested iterables to pack<commit_after>'''Some utilities used around town''' import struct def pack_string(message): '''Pack a single message in the TCP protocol format''' # [ 4-byte message size ][ N-byte binary data ] return struct.pack('>l', len(message)) + message def pack_iterable(messages): '''Pack an iterable of messages in the TCP protocol format''' # [ 4-byte body size ] # [ 4-byte num messages ] # [ 4-byte message #1 size ][ N-byte binary data ] # ... (repeated <num_messages> times) return pack_string( struct.pack('>l', len(messages)) + ''.join(map(pack_string, messages))) def pack(message): '''Pack the provided message''' if isinstance(message, basestring): return pack_string(message) else: return pack_iterable(message) def hexify(message): '''Print out printable characters, but others in hex''' import string hexified = [] for char in message: if (char in '\n\r \t') or (char not in string.printable): hexified.append('\\x%02x' % ord(char)) else: hexified.append(char) return ''.join(hexified) def distribute(total, objects): '''Generator for (count, object) tuples that distributes count evenly among the provided objects''' for index, obj in enumerate(objects): start = (index * total) / len(objects) stop = ((index + 1) * total) / len(objects) yield (stop - start, obj)
513560a051d9388cd39384860ddce6a938501080
bad.py
bad.py
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
Allow user to set their initial amount of cash and drugs
Allow user to set their initial amount of cash and drugs
Python
apache-2.0
brint/cheating_bad
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass Allow user to set their initial amount of cash and drugs
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
<commit_before>from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass <commit_msg>Allow user to set their initial amount of cash and drugs<commit_after>
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass Allow user to set their initial amount of cash and drugsfrom selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
<commit_before>from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") num_cooks = 100 num_sells = 50 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 time.sleep( 1 ) counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass <commit_msg>Allow user to set their initial amount of cash and drugs<commit_after>from selenium import webdriver from selenium.webdriver.common.keys import Keys import time driver = webdriver.Chrome() driver.get("http://clickingbad.nullism.com/") # Amount you'd like to have in terms of cash and # drugs to start the game init_drugs = 10000 init_cash = 10000 # Number of cooks and sells to do in a row num_cooks = 500 num_sells = 500 cook = driver.find_element_by_id('make_btn') sell = driver.find_element_by_id('sell_btn') driver.execute_script("gm.add_widgets(" + str(init_drugs) + ")") driver.execute_script("gm.add_cash(" + str(init_cash) + ")") while True: try: counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_cooks: cook.click() counter+=1 counter = 0 driver.execute_script("window.scrollTo(0,0);") while counter < num_sells: sell.click() counter+=1 time.sleep( 1 ) except: time.sleep( 5 ) pass
428e1e669e8b5e59da2c4d87716ffd329b4a084a
test/bluezutils.py
test/bluezutils.py
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found")
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" DEVICE_INTERFACE = SERVICE_NAME + ".Device" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") def find_device(device_address, adapter_pattern=None): return find_device_in_objects(get_managed_objects(), device_address, adapter_pattern) def find_device_in_objects(objects, device_address, adapter_pattern=None): bus = dbus.SystemBus() path_prefix = "" if adapter_pattern: adapter = find_adapter_in_objects(objects, adapter_pattern) path_prefix = adapter.object_path for path, ifaces in objects.iteritems(): device = ifaces.get(DEVICE_INTERFACE) if device is None: continue if (device["Address"] == device_address and path.startswith(path_prefix)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, DEVICE_INTERFACE) raise Exception("Bluetooth device not found")
Add helper function to find devices
test: Add helper function to find devices Add a helper function to the utility library as an alternative to the convenience method Adapter.FindDevice() in the D-Bus API.
Python
lgpl-2.1
silent-snowman/bluez,pstglia/external-bluetooth-bluez,ComputeCycles/bluez,mapfau/bluez,ComputeCycles/bluez,mapfau/bluez,pstglia/external-bluetooth-bluez,pkarasev3/bluez,pkarasev3/bluez,pkarasev3/bluez,pstglia/external-bluetooth-bluez,pkarasev3/bluez,ComputeCycles/bluez,mapfau/bluez,ComputeCycles/bluez,silent-snowman/bluez,mapfau/bluez,pstglia/external-bluetooth-bluez,silent-snowman/bluez,silent-snowman/bluez
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") test: Add helper function to find devices Add a helper function to the utility library as an alternative to the convenience method Adapter.FindDevice() in the D-Bus API.
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" DEVICE_INTERFACE = SERVICE_NAME + ".Device" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") def find_device(device_address, adapter_pattern=None): return find_device_in_objects(get_managed_objects(), device_address, adapter_pattern) def find_device_in_objects(objects, device_address, adapter_pattern=None): bus = dbus.SystemBus() path_prefix = "" if adapter_pattern: adapter = find_adapter_in_objects(objects, adapter_pattern) path_prefix = adapter.object_path for path, ifaces in objects.iteritems(): device = ifaces.get(DEVICE_INTERFACE) if device is None: continue if (device["Address"] == device_address and path.startswith(path_prefix)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, DEVICE_INTERFACE) raise Exception("Bluetooth device not found")
<commit_before>import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") <commit_msg>test: Add helper function to find devices Add a helper function to the utility library as an alternative to the convenience method Adapter.FindDevice() in the D-Bus API.<commit_after>
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" DEVICE_INTERFACE = SERVICE_NAME + ".Device" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") def find_device(device_address, adapter_pattern=None): return find_device_in_objects(get_managed_objects(), device_address, adapter_pattern) def find_device_in_objects(objects, device_address, adapter_pattern=None): bus = dbus.SystemBus() path_prefix = "" if adapter_pattern: adapter = find_adapter_in_objects(objects, adapter_pattern) path_prefix = adapter.object_path for path, ifaces in objects.iteritems(): device = ifaces.get(DEVICE_INTERFACE) if device is None: continue if (device["Address"] == device_address and path.startswith(path_prefix)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, DEVICE_INTERFACE) raise Exception("Bluetooth device not found")
import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") test: Add helper function to find devices Add a helper function to the utility library as an alternative to the convenience method Adapter.FindDevice() in the D-Bus API.import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" DEVICE_INTERFACE = SERVICE_NAME + ".Device" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") def find_device(device_address, adapter_pattern=None): return find_device_in_objects(get_managed_objects(), device_address, adapter_pattern) def find_device_in_objects(objects, device_address, adapter_pattern=None): bus = dbus.SystemBus() path_prefix = "" if adapter_pattern: adapter = find_adapter_in_objects(objects, adapter_pattern) path_prefix = adapter.object_path for path, ifaces in objects.iteritems(): device = ifaces.get(DEVICE_INTERFACE) if device is None: continue if (device["Address"] == device_address and path.startswith(path_prefix)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, DEVICE_INTERFACE) raise Exception("Bluetooth device not found")
<commit_before>import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") <commit_msg>test: Add helper function to find devices Add a helper function to the utility library as an alternative to the convenience method Adapter.FindDevice() in the D-Bus API.<commit_after>import dbus SERVICE_NAME = "org.bluez" ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter" DEVICE_INTERFACE = SERVICE_NAME + ".Device" def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects() def find_adapter(pattern=None): return find_adapter_in_objects(get_managed_objects(), pattern) def find_adapter_in_objects(objects, pattern=None): bus = dbus.SystemBus() for path, ifaces in objects.iteritems(): adapter = ifaces.get(ADAPTER_INTERFACE) if adapter is None: continue if not pattern or pattern == adapter["Address"] or path.endswith(pattern)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, ADAPTER_INTERFACE) raise Exception("Bluetooth adapter not found") def find_device(device_address, adapter_pattern=None): return find_device_in_objects(get_managed_objects(), device_address, adapter_pattern) def find_device_in_objects(objects, device_address, adapter_pattern=None): bus = dbus.SystemBus() path_prefix = "" if adapter_pattern: adapter = find_adapter_in_objects(objects, adapter_pattern) path_prefix = adapter.object_path for path, ifaces in objects.iteritems(): device = ifaces.get(DEVICE_INTERFACE) if device is None: continue if (device["Address"] == device_address and path.startswith(path_prefix)): obj = bus.get_object(SERVICE_NAME, path) return dbus.Interface(obj, DEVICE_INTERFACE) raise Exception("Bluetooth device not found")
8cd193b9e842918c03aa25ce0eaf1cca1c843c95
rrsm/StateMachine.py
rrsm/StateMachine.py
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): self.States = RequiredStates self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): if type(RequiredStates) is dict: self.States = RequiredStates self.StateCodes = dict([(code,state) for state,code in RequiredStates.iteritems()]) # This is done for speed of the rest of the class elif type(RequiredStates) is list: self.States = dict([(code,state) for code,state in enumerate(RequiredStates)]) self.StateCodes = dict([(state,code) for code,state in enumerate(RequiredStates)]) self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other SM = StateMachine(['A','B'])
Enable Dictionaries or Lists to create the Machine
Enable Dictionaries or Lists to create the Machine
Python
mit
jnmclarty/rrsm
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): self.States = RequiredStates self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other Enable Dictionaries or Lists to create the Machine
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): if type(RequiredStates) is dict: self.States = RequiredStates self.StateCodes = dict([(code,state) for state,code in RequiredStates.iteritems()]) # This is done for speed of the rest of the class elif type(RequiredStates) is list: self.States = dict([(code,state) for code,state in enumerate(RequiredStates)]) self.StateCodes = dict([(state,code) for code,state in enumerate(RequiredStates)]) self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other SM = StateMachine(['A','B'])
<commit_before>class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): self.States = RequiredStates self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other <commit_msg>Enable Dictionaries or Lists to create the Machine<commit_after>
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): if type(RequiredStates) is dict: self.States = RequiredStates self.StateCodes = dict([(code,state) for state,code in RequiredStates.iteritems()]) # This is done for speed of the rest of the class elif type(RequiredStates) is list: self.States = dict([(code,state) for code,state in enumerate(RequiredStates)]) self.StateCodes = dict([(state,code) for code,state in enumerate(RequiredStates)]) self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other SM = StateMachine(['A','B'])
class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): self.States = RequiredStates self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other Enable Dictionaries or Lists to create the Machineclass StateMachine(object): def __init__(self,RequiredStates,InitialState=0): if type(RequiredStates) is dict: self.States = RequiredStates self.StateCodes = dict([(code,state) for state,code in RequiredStates.iteritems()]) # This is done for speed of the rest of the class elif type(RequiredStates) is list: self.States = dict([(code,state) for code,state in enumerate(RequiredStates)]) self.StateCodes = dict([(state,code) for code,state in enumerate(RequiredStates)]) self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other SM = StateMachine(['A','B'])
<commit_before>class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): self.States = RequiredStates self.StateCodes = dict([(v,k) for k,v in RequiredStates.iteritems()]) # This is done for speed of the rest of the class self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other <commit_msg>Enable Dictionaries or Lists to create the Machine<commit_after>class StateMachine(object): def __init__(self,RequiredStates,InitialState=0): if type(RequiredStates) is dict: self.States = RequiredStates self.StateCodes = dict([(code,state) for state,code in RequiredStates.iteritems()]) # This is done for speed of the rest of the class elif type(RequiredStates) is list: self.States = dict([(code,state) for code,state in enumerate(RequiredStates)]) self.StateCodes = dict([(state,code) for code,state in enumerate(RequiredStates)]) self.SwitchTo(InitialState) for StateCodes,States in self.States.iteritems(): setattr(StateMachine,States,StateCodes) def SwitchTo(self,NewState): if type(NewState) is int: self.CurrentCode = NewState else: self.CurrentCode = self.StateCodes[NewState] def CurrentState(self): return self.States[self.CurrentCode] def __eq__(self,other): return self.CurrentCode == other SM = StateMachine(['A','B'])
6d5eaee8b1c13eb08cbf48b4c72c5b2d8f0d96b4
test/runner.py
test/runner.py
import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1)
# -*- encoding: utf-8 -*- import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import test.nagios_results as tr import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg, tr)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1)
Rename the nagios-results test suite into a valid identifier.
Rename the nagios-results test suite into a valid identifier. This way, we can run its tests from within a test.runner module.
Python
lgpl-2.1
hpcugent/vsc-processcontrol,hpcugent/vsc-processcontrol
import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1) Rename the nagios-results test suite into a valid identifier. This way, we can run its tests from within a test.runner module.
# -*- encoding: utf-8 -*- import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import test.nagios_results as tr import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg, tr)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1)
<commit_before>import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1) <commit_msg>Rename the nagios-results test suite into a valid identifier. This way, we can run its tests from within a test.runner module.<commit_after>
# -*- encoding: utf-8 -*- import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import test.nagios_results as tr import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg, tr)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1)
import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1) Rename the nagios-results test suite into a valid identifier. This way, we can run its tests from within a test.runner module.# -*- encoding: utf-8 -*- import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import test.nagios_results as tr import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg, tr)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1)
<commit_before>import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1) <commit_msg>Rename the nagios-results test suite into a valid identifier. This way, we can run its tests from within a test.runner module.<commit_after># -*- encoding: utf-8 -*- import sys import os import test.cache as tc import test.dateandtime as td import test.nagios as tn import test.generaloption as tg import test.nagios_results as tr import unittest suite = unittest.TestSuite([x.suite() for x in (tc, td, tn, tg, tr)]) try: import xmlrunner rs = xmlrunner.XMLTestRunner(output="test-reports").run(suite) except ImportError, err: rs = unittest.TextTestRunner().run(suite) if not rs.wasSuccessful(): sys.exit(1)
90a724313902e3d95f1a37d9102af1544c9bc61d
segments/set_term_title.py
segments/set_term_title.py
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\\e]0;%n@%m: %~\\a' else: import socket set_title = '\\e]0;%s@%s: %s\\a' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\033]0;%n@%m: %~\007' else: import socket set_title = '\033]0;%s@%s: %s\007' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
Fix use of escape characters in "set terminal title" segment.
Fix use of escape characters in "set terminal title" segment. Escape characters were incorrect for non-BASH shells.
Python
mit
nicholascapo/powerline-shell,b-ryan/powerline-shell,junix/powerline-shell,wrgoldstein/powerline-shell,rbanffy/powerline-shell,b-ryan/powerline-shell,mart-e/powerline-shell,blieque/powerline-shell,paulhybryant/powerline-shell,tswsl1989/powerline-shell,torbjornvatn/powerline-shell,MartinWetterwald/powerline-shell,iKrishneel/powerline-shell,fellipecastro/powerline-shell,ceholden/powerline-shell,banga/powerline-shell,banga/powerline-shell,handsomecheung/powerline-shell,saghul/shline,strycore/powerline-shell,bitIO/powerline-shell,intfrr/powerline-shell,yc2prime/powerline-shell,mcdope/powerline-shell,milkbikis/powerline-shell,paulhybryant/powerline-shell,JulianVolodia/powerline-shell,dtrip/powerline-shell,paol/powerline-shell,Menci/powerline-shell,LeonardoGentile/powerline-shell
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\\e]0;%n@%m: %~\\a' else: import socket set_title = '\\e]0;%s@%s: %s\\a' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment() Fix use of escape characters in "set terminal title" segment. Escape characters were incorrect for non-BASH shells.
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\033]0;%n@%m: %~\007' else: import socket set_title = '\033]0;%s@%s: %s\007' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
<commit_before>def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\\e]0;%n@%m: %~\\a' else: import socket set_title = '\\e]0;%s@%s: %s\\a' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment() <commit_msg>Fix use of escape characters in "set terminal title" segment. Escape characters were incorrect for non-BASH shells.<commit_after>
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\033]0;%n@%m: %~\007' else: import socket set_title = '\033]0;%s@%s: %s\007' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\\e]0;%n@%m: %~\\a' else: import socket set_title = '\\e]0;%s@%s: %s\\a' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment() Fix use of escape characters in "set terminal title" segment. Escape characters were incorrect for non-BASH shells.def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\033]0;%n@%m: %~\007' else: import socket set_title = '\033]0;%s@%s: %s\007' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
<commit_before>def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\\e]0;%n@%m: %~\\a' else: import socket set_title = '\\e]0;%s@%s: %s\\a' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment() <commit_msg>Fix use of escape characters in "set terminal title" segment. Escape characters were incorrect for non-BASH shells.<commit_after>def add_term_title_segment(): term = os.getenv('TERM') if not (('xterm' in term) or ('rxvt' in term)): return if powerline.args.shell == 'bash': set_title = '\\[\\e]0;\\u@\\h: \\w\\a\\]' elif powerline.args.shell == 'zsh': set_title = '\033]0;%n@%m: %~\007' else: import socket set_title = '\033]0;%s@%s: %s\007' % (os.getenv('USER'), socket.gethostname().split('.')[0], powerline.cwd or os.getenv('PWD')) powerline.append(set_title, None, None, '') add_term_title_segment()
680679ed2b05bd5131016d13f66f73249e51a102
tests/utils.py
tests/utils.py
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], }
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } def make_call_stub(retval=None): calls = [] def call_stub(*args, **kwargs): calls.append({'args': args, 'kwargs': kwargs}) return retval call_stub.calls = calls return call_stub
Add generic monkeypatch call stub
Add generic monkeypatch call stub
Python
mit
valohai/valohai-cli
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } Add generic monkeypatch call stub
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } def make_call_stub(retval=None): calls = [] def call_stub(*args, **kwargs): calls.append({'args': args, 'kwargs': kwargs}) return retval call_stub.calls = calls return call_stub
<commit_before>from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } <commit_msg>Add generic monkeypatch call stub<commit_after>
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } def make_call_stub(retval=None): calls = [] def call_stub(*args, **kwargs): calls.append({'args': args, 'kwargs': kwargs}) return retval call_stub.calls = calls return call_stub
from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } Add generic monkeypatch call stubfrom uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } def make_call_stub(retval=None): calls = [] def call_stub(*args, **kwargs): calls.append({'args': args, 'kwargs': kwargs}) return retval call_stub.calls = calls return call_stub
<commit_before>from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } <commit_msg>Add generic monkeypatch call stub<commit_after>from uuid import uuid4 from valohai_cli.utils import get_random_string def get_project_data(n_projects): return { 'results': [ {'id': str(uuid4()), 'name': get_random_string()} for i in range(n_projects) ], } def make_call_stub(retval=None): calls = [] def call_stub(*args, **kwargs): calls.append({'args': args, 'kwargs': kwargs}) return retval call_stub.calls = calls return call_stub
035ff2c50c5611406af172c6215f712086b75335
tfr/sklearn.py
tfr/sklearn.py
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # TODO: make this configurable self.output_frame_size = hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, output_frame_size=None, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # if no output frame size is specified the input hop size is the default self.output_frame_size = output_frame_size if output_frame_size is not None else hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
Add the output_frame_size parameter to PitchgramTransformer.
Add the output_frame_size parameter to PitchgramTransformer. Without it the deserialization via jsonpickle fails.
Python
mit
bzamecnik/tfr,bzamecnik/tfr
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # TODO: make this configurable self.output_frame_size = hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self Add the output_frame_size parameter to PitchgramTransformer. Without it the deserialization via jsonpickle fails.
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, output_frame_size=None, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # if no output frame size is specified the input hop size is the default self.output_frame_size = output_frame_size if output_frame_size is not None else hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
<commit_before>from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # TODO: make this configurable self.output_frame_size = hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self <commit_msg>Add the output_frame_size parameter to PitchgramTransformer. Without it the deserialization via jsonpickle fails.<commit_after>
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, output_frame_size=None, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # if no output frame size is specified the input hop size is the default self.output_frame_size = output_frame_size if output_frame_size is not None else hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # TODO: make this configurable self.output_frame_size = hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self Add the output_frame_size parameter to PitchgramTransformer. Without it the deserialization via jsonpickle fails.from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, output_frame_size=None, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # if no output frame size is specified the input hop size is the default self.output_frame_size = output_frame_size if output_frame_size is not None else hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
<commit_before>from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # TODO: make this configurable self.output_frame_size = hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self <commit_msg>Add the output_frame_size parameter to PitchgramTransformer. Without it the deserialization via jsonpickle fails.<commit_after>from sklearn.base import BaseEstimator, TransformerMixin from .signal import SignalFrames from .reassignment import pitchgram class PitchgramTransformer(BaseEstimator, TransformerMixin): def __init__(self, sample_rate=44100, frame_size=4096, hop_size=2048, output_frame_size=None, bin_range=[-48, 67], bin_division=1): self.sample_rate = sample_rate self.frame_size = frame_size self.hop_size = hop_size # if no output frame size is specified the input hop size is the default self.output_frame_size = output_frame_size if output_frame_size is not None else hop_size self.bin_range = bin_range self.bin_division = bin_division def transform(self, X, **transform_params): """ Transforms audio clip X into a normalized pitchgram. Input: X - mono audio clip - numpy array of shape (samples,) Output: X_pitchgram - numpy array of shape (frames, bins) """ signal_frames = SignalFrames(X, self.frame_size, self.hop_size, self.sample_rate, mono_mix=True) X_pitchgram = pitchgram( signal_frames, self.output_frame_size, magnitudes='power_db_normalized', bin_range=self.bin_range, bin_division=self.bin_division) return X_pitchgram def fit(self, X, y=None, **fit_params): return self
cb7db2933c180b7f7862352a759a2a90a48d247f
metric/models.py
metric/models.py
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{}/{}: {}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{0}/{1}: {2}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
Fix 'zero length field name in format' error
Fix 'zero length field name in format' error
Python
mit
dhh1128/ascent-dashboard,dhh1128/ascent-dashboard
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{}/{}: {}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4: Fix 'zero length field name in format' error
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{0}/{1}: {2}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
<commit_before>from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{}/{}: {}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4: <commit_msg>Fix 'zero length field name in format' error<commit_after>
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{0}/{1}: {2}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{}/{}: {}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4: Fix 'zero length field name in format' errorfrom django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{0}/{1}: {2}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
<commit_before>from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{}/{}: {}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4: <commit_msg>Fix 'zero length field name in format' error<commit_after>from django.db import models class Metric(models.Model): class Meta: db_table = 'metric' def __unicode__(self): return self.name name = models.CharField(max_length=128) explanation_url = models.CharField(max_length=256) units = models.CharField(max_length=128) class Environment(models.Model): class Meta: db_table = 'environment' class Procedure(models.Model): class Meta: db_table = 'procedure' class Sample(models.Model): class Meta: db_table = 'samples' ordering = ['metric', 'sample_date'] unique_together = ('metric', 'sample_date') def __unicode__(self): return '{0}/{1}: {2}'.format(self.sample_date, self.metric.name, self.value) metric = models.ForeignKey(Metric) sample_date = models.DateField() value = models.FloatField() environment = models.ForeignKey(Environment, blank=True, null=True) procedure = models.ForeignKey(Procedure, blank=True, null=True) # vim: set et sw=4 ts=4:
3fba63784b83c24a88a4d26606f22865122c806e
run.py
run.py
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') print config_file app = create_app(config_file) if __name__ == '__main__': app.run()
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') app = create_app(config_file) if __name__ == '__main__': app.run(debug=True)
Set debug mode to True in development
Set debug mode to True in development
Python
mit
kxxoling/horus,kxxoling/horus,kxxoling/horus
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') print config_file app = create_app(config_file) if __name__ == '__main__': app.run() Set debug mode to True in development
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') app = create_app(config_file) if __name__ == '__main__': app.run(debug=True)
<commit_before>import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') print config_file app = create_app(config_file) if __name__ == '__main__': app.run() <commit_msg>Set debug mode to True in development<commit_after>
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') app = create_app(config_file) if __name__ == '__main__': app.run(debug=True)
import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') print config_file app = create_app(config_file) if __name__ == '__main__': app.run() Set debug mode to True in developmentimport os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') app = create_app(config_file) if __name__ == '__main__': app.run(debug=True)
<commit_before>import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') print config_file app = create_app(config_file) if __name__ == '__main__': app.run() <commit_msg>Set debug mode to True in development<commit_after>import os from horus.apps import create_app config_file = os.path.join(os.path.dirname(os.path.realpath(__file__)) , 'config.py') app = create_app(config_file) if __name__ == '__main__': app.run(debug=True)
eab1de115f010922531a5a2c5f023bf2294f2af4
sendgrid/__init__.py
sendgrid/__init__.py
"""A small django app around sendgrid and its webhooks""" from utils import SendgridEmailMessage, SendgridEmailMultiAlternatives from models import Email from signals import email_event __version__ = '0.1.0' __all__ = ('SendgridEmailMessage', 'SendgridEmailMultiAlternatives', 'Email', 'email_event')
"""A small django app around sendgrid and its webhooks""" __version__ = '0.1.0'
Revert "add __all__ parameter to main module"
Revert "add __all__ parameter to main module" This reverts commit bc9e574206e75b1a50bd1b8eb4bd56f96a18cf51.
Python
bsd-2-clause
resmio/django-sendgrid
"""A small django app around sendgrid and its webhooks""" from utils import SendgridEmailMessage, SendgridEmailMultiAlternatives from models import Email from signals import email_event __version__ = '0.1.0' __all__ = ('SendgridEmailMessage', 'SendgridEmailMultiAlternatives', 'Email', 'email_event') Revert "add __all__ parameter to main module" This reverts commit bc9e574206e75b1a50bd1b8eb4bd56f96a18cf51.
"""A small django app around sendgrid and its webhooks""" __version__ = '0.1.0'
<commit_before>"""A small django app around sendgrid and its webhooks""" from utils import SendgridEmailMessage, SendgridEmailMultiAlternatives from models import Email from signals import email_event __version__ = '0.1.0' __all__ = ('SendgridEmailMessage', 'SendgridEmailMultiAlternatives', 'Email', 'email_event') <commit_msg>Revert "add __all__ parameter to main module" This reverts commit bc9e574206e75b1a50bd1b8eb4bd56f96a18cf51.<commit_after>
"""A small django app around sendgrid and its webhooks""" __version__ = '0.1.0'
"""A small django app around sendgrid and its webhooks""" from utils import SendgridEmailMessage, SendgridEmailMultiAlternatives from models import Email from signals import email_event __version__ = '0.1.0' __all__ = ('SendgridEmailMessage', 'SendgridEmailMultiAlternatives', 'Email', 'email_event') Revert "add __all__ parameter to main module" This reverts commit bc9e574206e75b1a50bd1b8eb4bd56f96a18cf51."""A small django app around sendgrid and its webhooks""" __version__ = '0.1.0'
<commit_before>"""A small django app around sendgrid and its webhooks""" from utils import SendgridEmailMessage, SendgridEmailMultiAlternatives from models import Email from signals import email_event __version__ = '0.1.0' __all__ = ('SendgridEmailMessage', 'SendgridEmailMultiAlternatives', 'Email', 'email_event') <commit_msg>Revert "add __all__ parameter to main module" This reverts commit bc9e574206e75b1a50bd1b8eb4bd56f96a18cf51.<commit_after>"""A small django app around sendgrid and its webhooks""" __version__ = '0.1.0'
906766ad4bee0f0db560300982a71c222b59a677
example_config.py
example_config.py
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
Add missing required heroku config variable
Add missing required heroku config variable
Python
agpl-3.0
pluralsight/guides-cms,paulocheque/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True Add missing required heroku config variable
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
<commit_before>""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True <commit_msg>Add missing required heroku config variable<commit_after>
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True Add missing required heroku config variable""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
<commit_before>""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True <commit_msg>Add missing required heroku config variable<commit_after>""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # This should automatically be set by heroku if you've added a database to # your app. SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] class DevelopmentConfig(Config): DEBUG = True
fcdc3974015499f822d9e3355a6fe937c18eaf9a
src/nodeconductor_assembly_waldur/slurm_invoices/models.py
src/nodeconductor_assembly_waldur/slurm_invoices/models.py
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
Add verbose name for SLURM package
Add verbose name for SLURM package [WAL-1141]
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) Add verbose name for SLURM package [WAL-1141]
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
<commit_before>from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) <commit_msg>Add verbose name for SLURM package [WAL-1141]<commit_after>
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) Add verbose name for SLURM package [WAL-1141]from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
<commit_before>from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) <commit_msg>Add verbose name for SLURM package [WAL-1141]<commit_after>from decimal import Decimal from django.db import models from django.core.validators import MinValueValidator from django.utils.translation import ugettext_lazy as _ from nodeconductor.structure import models as structure_models from nodeconductor_assembly_waldur.common import mixins as common_mixins class SlurmPackage(common_mixins.ProductCodeMixin, models.Model): class Meta(object): verbose_name = _('SLURM package') verbose_name_plural = _('SLURM packages') PRICE_MAX_DIGITS = 14 PRICE_DECIMAL_PLACES = 10 service_settings = models.OneToOneField(structure_models.ServiceSettings, related_name='+', limit_choices_to={'type': 'SLURM'}) cpu_price = models.DecimalField(default=0, verbose_name=_('Price for CPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) gpu_price = models.DecimalField(default=0, verbose_name=_('Price for GPU hour'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))]) ram_price = models.DecimalField(default=0, verbose_name=_('Price for GB RAM'), max_digits=PRICE_MAX_DIGITS, decimal_places=PRICE_DECIMAL_PLACES, validators=[MinValueValidator(Decimal('0'))])
d6acda58c696c5b348da8c6a4fef3bf06cea0e58
weight/models.py
weight/models.py
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
Add default ordering to weight entries
Add default ordering to weight entries
Python
agpl-3.0
kjagoo/wger_stark,wger-project/wger,wger-project/wger,wger-project/wger,kjagoo/wger_stark,wger-project/wger,rolandgeider/wger,petervanderdoes/wger,petervanderdoes/wger,petervanderdoes/wger,kjagoo/wger_stark,petervanderdoes/wger,DeveloperMal/wger,DeveloperMal/wger,DeveloperMal/wger,rolandgeider/wger,DeveloperMal/wger,kjagoo/wger_stark,rolandgeider/wger,rolandgeider/wger
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight) Add default ordering to weight entries
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
<commit_before># This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight) <commit_msg>Add default ordering to weight entries<commit_after>
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight) Add default ordering to weight entries# This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
<commit_before># This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight) <commit_msg>Add default ordering to weight entries<commit_after># This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
9c24683e9594e62f9ba901481c66e40c39a20b4a
tools/metrics/histograms/validate_format.py
tools/metrics/histograms/validate_format.py
# Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms def main(): # This will raise an exception if the file is not well-formatted. histograms = extract_histograms.ExtractHistograms('histograms.xml') if __name__ == '__main__': main()
# Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms import os.path def main(): # This will raise an exception if the file is not well-formatted. xml_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'histograms.xml') histograms = extract_histograms.ExtractHistograms(xml_file) if __name__ == '__main__': main()
Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms.
Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms. Review URL: https://codereview.chromium.org/80433003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@236508 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,jaruba/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,dednal/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,axinging/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,dushu1203/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,ltilve/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,jaruba/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,patrickm/chromium.src,dednal/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,jaruba/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,markYoungH/chromium.src,littlstar/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,jaruba/chromium.src,anirudhSK/chromium,M4sse/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,patrickm/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,anirudhSK/chromium,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,patrickm/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,bright-sparks/chromium-spacewalk,ltilve/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,jaruba/chromium.src,Chilledheart/chromium,ltilve/chromium,patrickm/chromium.src,jaruba/chromium.src
# Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms def main(): # This will raise an exception if the file is not well-formatted. histograms = extract_histograms.ExtractHistograms('histograms.xml') if __name__ == '__main__': main() Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms. Review URL: https://codereview.chromium.org/80433003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@236508 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms import os.path def main(): # This will raise an exception if the file is not well-formatted. xml_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'histograms.xml') histograms = extract_histograms.ExtractHistograms(xml_file) if __name__ == '__main__': main()
<commit_before># Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms def main(): # This will raise an exception if the file is not well-formatted. histograms = extract_histograms.ExtractHistograms('histograms.xml') if __name__ == '__main__': main() <commit_msg>Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms. Review URL: https://codereview.chromium.org/80433003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@236508 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
# Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms import os.path def main(): # This will raise an exception if the file is not well-formatted. xml_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'histograms.xml') histograms = extract_histograms.ExtractHistograms(xml_file) if __name__ == '__main__': main()
# Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms def main(): # This will raise an exception if the file is not well-formatted. histograms = extract_histograms.ExtractHistograms('histograms.xml') if __name__ == '__main__': main() Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms. Review URL: https://codereview.chromium.org/80433003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@236508 0039d316-1c4b-4281-b951-d872f2087c98# Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms import os.path def main(): # This will raise an exception if the file is not well-formatted. xml_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'histograms.xml') histograms = extract_histograms.ExtractHistograms(xml_file) if __name__ == '__main__': main()
<commit_before># Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms def main(): # This will raise an exception if the file is not well-formatted. histograms = extract_histograms.ExtractHistograms('histograms.xml') if __name__ == '__main__': main() <commit_msg>Make it possible to run the histograms XML validator from directories other than tools/metrics/histograms. Review URL: https://codereview.chromium.org/80433003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@236508 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright 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. """Verifies that the histograms XML file is well-formatted.""" import extract_histograms import os.path def main(): # This will raise an exception if the file is not well-formatted. xml_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'histograms.xml') histograms = extract_histograms.ExtractHistograms(xml_file) if __name__ == '__main__': main()
40c97fa33c8739bd27b03891782b542217534904
ognskylines/commands/database.py
ognskylines/commands/database.py
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure=0): """Drop all tables.""" if sure: Base.metadata.drop_all(engine) print('Dropped all tables.') else:
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure='n'): """Drop all tables.""" if sure == 'y': Base.metadata.drop_all(engine) print('Dropped all tables.') else: print("Add argument '--sure y' to drop all tables.")
Change confirmation flag to '--sure y'
CLI: Change confirmation flag to '--sure y'
Python
agpl-3.0
kerel-fs/ogn-skylines-gateway,kerel-fs/ogn-skylines-gateway
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure=0): """Drop all tables.""" if sure: Base.metadata.drop_all(engine) print('Dropped all tables.') else: CLI: Change confirmation flag to '--sure y'
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure='n'): """Drop all tables.""" if sure == 'y': Base.metadata.drop_all(engine) print('Dropped all tables.') else: print("Add argument '--sure y' to drop all tables.")
<commit_before>from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure=0): """Drop all tables.""" if sure: Base.metadata.drop_all(engine) print('Dropped all tables.') else: <commit_msg>CLI: Change confirmation flag to '--sure y'<commit_after>
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure='n'): """Drop all tables.""" if sure == 'y': Base.metadata.drop_all(engine) print('Dropped all tables.') else: print("Add argument '--sure y' to drop all tables.")
from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure=0): """Drop all tables.""" if sure: Base.metadata.drop_all(engine) print('Dropped all tables.') else: CLI: Change confirmation flag to '--sure y'from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure='n'): """Drop all tables.""" if sure == 'y': Base.metadata.drop_all(engine) print('Dropped all tables.') else: print("Add argument '--sure y' to drop all tables.")
<commit_before>from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure=0): """Drop all tables.""" if sure: Base.metadata.drop_all(engine) print('Dropped all tables.') else: <commit_msg>CLI: Change confirmation flag to '--sure y'<commit_after>from ognskylines.dbutils import engine from ognskylines.model import Base from manager import Manager manager = Manager() @manager.command def init(): """Initialize the database.""" Base.metadata.create_all(engine) print('Done.') @manager.command def drop(sure='n'): """Drop all tables.""" if sure == 'y': Base.metadata.drop_all(engine) print('Dropped all tables.') else: print("Add argument '--sure y' to drop all tables.")
335f1de1120e658f4e87dcbbcaf882146df895bb
zounds/__init__.py
zounds/__init__.py
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature, ComplexDomain from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir
Add onset detection processing node to top-level exports
Add onset detection processing node to top-level exports
Python
mit
JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds,JohnVinyard/zounds
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir Add onset detection processing node to top-level exports
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature, ComplexDomain from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir
<commit_before>from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir <commit_msg>Add onset detection processing node to top-level exports<commit_after>
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature, ComplexDomain from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir
from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir Add onset detection processing node to top-level exportsfrom node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature, ComplexDomain from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir
<commit_before>from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir <commit_msg>Add onset detection processing node to top-level exports<commit_after>from node.duration import \ Hours, Minutes, Seconds, Milliseconds, Microseconds, Picoseconds from node.audio_metadata import MetaData, AudioMetaDataEncoder from node.ogg_vorbis import \ OggVorbis, OggVorbisDecoder, OggVorbisEncoder, OggVorbisFeature, \ OggVorbisWrapper from node.audiostream import AudioStream from node.basic import Slice, Sum, Max from node.learn import KMeans, BinaryRbm, LinearRbm, Learned from node.onset import \ MeasureOfTransience, MovingAveragePeakPicker, SparseTimestampDecoder, \ SparseTimestampEncoder, TimeSliceDecoder, TimeSliceFeature, ComplexDomain from node.preprocess import \ MeanStdNormalization, UnitNorm, PreprocessingPipeline from node.random_samples import ReservoirSampler from node.resample import Resampler from node.samplerate import \ SR11025, SR22050, SR44100, SR48000, SR96000, HalfLapped from node.sliding_window import SlidingWindow, OggVorbisWindowingFunc from node.spectral import FFT, DCT, BarkBands, Chroma, BFCC from node.template_match import TemplateMatch from node.timeseries import \ TimeSlice, ConstantRateTimeSeriesEncoder, ConstantRateTimeSeriesFeature, \ GreedyConstantRateTimeSeriesDecoder from node.api import ZoundsApp from node.util import process_dir
3c25f2802f70a16869e93fb301428c31452c00f0
plyer/platforms/macosx/uniqueid.py
plyer/platforms/macosx/uniqueid.py
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
Fix TypeError if `LANG` is not set in on osx
Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.
Python
mit
kivy/plyer,kived/plyer,KeyWeeUsr/plyer,johnbolia/plyer,johnbolia/plyer,kivy/plyer,KeyWeeUsr/plyer,kived/plyer,KeyWeeUsr/plyer,kivy/plyer
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID() Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
<commit_before>from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID() <commit_msg>Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.<commit_after>
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID() Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
<commit_before>from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID() <commit_msg>Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.<commit_after>from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
844e63b78df318e88fe9d262c7e0a09fcfef8c76
handroll/tests/test_configuration.py
handroll/tests/test_configuration.py
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") print conf_file args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
Delete a stray Python 2 print statement.
Delete a stray Python 2 print statement.
Python
bsd-2-clause
handroll/handroll
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") print conf_file args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir) Delete a stray Python 2 print statement.
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
<commit_before># Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") print conf_file args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir) <commit_msg>Delete a stray Python 2 print statement.<commit_after>
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") print conf_file args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir) Delete a stray Python 2 print statement.# Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
<commit_before># Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") print conf_file args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir) <commit_msg>Delete a stray Python 2 print statement.<commit_after># Copyright (c) 2014, Matt Layman import inspect import tempfile import unittest from handroll import configuration class FakeArgs(object): def __init__(self): self.outdir = None self.timing = None class TestConfiguration(unittest.TestCase): def test_loads_from_outdir_argument(self): config = configuration.Configuration() args = FakeArgs() args.outdir = 'out' config.load_from_arguments(args) self.assertEqual(args.outdir, config.outdir) def test_build_config_from_file(self): conf_file = inspect.cleandoc( """[site] outdir = out""") args = FakeArgs() with tempfile.NamedTemporaryFile(delete=False) as f: f.write(conf_file) config = configuration.build_config(f.name, args) self.assertEqual('out', config.outdir)
076aa11e353440b0c61a763c4b1bb2e4b57b9a30
custom/enikshay/ucr/views.py
custom/enikshay/ucr/views.py
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) .aggregate(Min('date_created')) ) if oldest_indicator['date_created__min'] is not None: hours_behind = (now - oldest_indicator['date_created__min']).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 return None
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() try: oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) )[0] hours_behind = (now - oldest_indicator.date_created).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 except IndexError: return None
Use implicit ordering of AsyncIndicator model
Use implicit ordering of AsyncIndicator model
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) .aggregate(Min('date_created')) ) if oldest_indicator['date_created__min'] is not None: hours_behind = (now - oldest_indicator['date_created__min']).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 return None Use implicit ordering of AsyncIndicator model
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() try: oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) )[0] hours_behind = (now - oldest_indicator.date_created).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 except IndexError: return None
<commit_before>from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) .aggregate(Min('date_created')) ) if oldest_indicator['date_created__min'] is not None: hours_behind = (now - oldest_indicator['date_created__min']).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 return None <commit_msg>Use implicit ordering of AsyncIndicator model<commit_after>
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() try: oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) )[0] hours_behind = (now - oldest_indicator.date_created).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 except IndexError: return None
from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) .aggregate(Min('date_created')) ) if oldest_indicator['date_created__min'] is not None: hours_behind = (now - oldest_indicator['date_created__min']).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 return None Use implicit ordering of AsyncIndicator modelfrom __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() try: oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) )[0] hours_behind = (now - oldest_indicator.date_created).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 except IndexError: return None
<commit_before>from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) .aggregate(Min('date_created')) ) if oldest_indicator['date_created__min'] is not None: hours_behind = (now - oldest_indicator['date_created__min']).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 return None <commit_msg>Use implicit ordering of AsyncIndicator model<commit_after>from __future__ import absolute_import from __future__ import division from datetime import datetime from django.db.models import Min from corehq.apps.userreports.models import AsyncIndicator from corehq.apps.userreports.reports.view import CustomConfigurableReport class MonitoredReport(CustomConfigurableReport): """For reports backed by an async datasource, shows an indication of how far behind the report might be, in increments of 12 hours. """ template_name = 'enikshay/ucr/monitored_report.html' @property def page_context(self): context = super(MonitoredReport, self).page_context context['hours_behind'] = self.hours_behind() return context def hours_behind(self): """returns the number of hours behind this report is, to the nearest 12 hour bucket. """ now = datetime.utcnow() try: oldest_indicator = ( AsyncIndicator.objects .filter(indicator_config_ids__contains=[self.spec.config_id]) )[0] hours_behind = (now - oldest_indicator.date_created).total_seconds() / (60 * 60) return int(1 + (hours_behind // 12)) * 12 except IndexError: return None
efcb8603251514286388427277a4ab4e22c9b0e5
main.py
main.py
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table, Library, Framework from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) if len(libsContaining) > 1: print "Conflict for symbol '{0}':".format(symbol), libsContaining libnames = [lib.name for lib in libsContaining] if "System" in libnames: libsContaining = set([Library("System")]) else: libsContaining = set([libsContaining[0]]) print "Choosing:", libsContaining neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])
Choose one when there are multiple options, preferring (for now) System
Choose one when there are multiple options, preferring (for now) System
Python
bsd-2-clause
hortont424/guesscc,hortont424/guesscc
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])Choose one when there are multiple options, preferring (for now) System
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table, Library, Framework from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) if len(libsContaining) > 1: print "Conflict for symbol '{0}':".format(symbol), libsContaining libnames = [lib.name for lib in libsContaining] if "System" in libnames: libsContaining = set([Library("System")]) else: libsContaining = set([libsContaining[0]]) print "Choosing:", libsContaining neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])
<commit_before>#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])<commit_msg>Choose one when there are multiple options, preferring (for now) System<commit_after>
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table, Library, Framework from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) if len(libsContaining) > 1: print "Conflict for symbol '{0}':".format(symbol), libsContaining libnames = [lib.name for lib in libsContaining] if "System" in libnames: libsContaining = set([Library("System")]) else: libsContaining = set([libsContaining[0]]) print "Choosing:", libsContaining neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])
#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])Choose one when there are multiple options, preferring (for now) System#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table, Library, Framework from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) if len(libsContaining) > 1: print "Conflict for symbol '{0}':".format(symbol), libsContaining libnames = [lib.name for lib in libsContaining] if "System" in libnames: libsContaining = set([Library("System")]) else: libsContaining = set([libsContaining[0]]) print "Choosing:", libsContaining neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])
<commit_before>#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])<commit_msg>Choose one when there are multiple options, preferring (for now) System<commit_after>#!/usr/bin/env python from generateSymbolTable import generate_default_symbol_table, Library, Framework from scanner import scan_source_files from glob import glob filenames = ["symbolScanner.c"] filenames = glob("/Users/hortont/Desktop/particles/*.c") symbolTable = generate_default_symbol_table() (wantSymbols, haveSymbols) = scan_source_files(filenames) neededLibs = set() for symbol in wantSymbols: if symbol in haveSymbols: continue libsContaining = symbolTable["_" + symbol] if len(libsContaining) == 0: print "Can't find symbol '{0}'.".format(symbol) if len(libsContaining) > 1: print "Conflict for symbol '{0}':".format(symbol), libsContaining libnames = [lib.name for lib in libsContaining] if "System" in libnames: libsContaining = set([Library("System")]) else: libsContaining = set([libsContaining[0]]) print "Choosing:", libsContaining neededLibs |= libsContaining print " ".join([lib.generate_args() for lib in neededLibs])
0ec6bebb4665185854ccf58c99229bae41ef74d4
pybtex/tests/bibtex_parser_test.py
pybtex/tests/bibtex_parser_test.py
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result)
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ( '''@ARTICLE{ test, title="Nested braces and {"quotes"}", }''', BibliographyData({u'test': Entry('article', {u'title': 'Nested braces and {"quotes"}'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result)
Add a test for quoted strings with {"quotes"} in .bib files.
Add a test for quoted strings with {"quotes"} in .bib files.
Python
mit
live-clones/pybtex
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result) Add a test for quoted strings with {"quotes"} in .bib files.
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ( '''@ARTICLE{ test, title="Nested braces and {"quotes"}", }''', BibliographyData({u'test': Entry('article', {u'title': 'Nested braces and {"quotes"}'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result)
<commit_before>from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result) <commit_msg>Add a test for quoted strings with {"quotes"} in .bib files.<commit_after>
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ( '''@ARTICLE{ test, title="Nested braces and {"quotes"}", }''', BibliographyData({u'test': Entry('article', {u'title': 'Nested braces and {"quotes"}'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result)
from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result) Add a test for quoted strings with {"quotes"} in .bib files.from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ( '''@ARTICLE{ test, title="Nested braces and {"quotes"}", }''', BibliographyData({u'test': Entry('article', {u'title': 'Nested braces and {"quotes"}'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result)
<commit_before>from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result) <commit_msg>Add a test for quoted strings with {"quotes"} in .bib files.<commit_after>from pybtex.database import BibliographyData from pybtex.core import Entry from pybtex.database.input.bibtex import Parser from cStringIO import StringIO test_data = [ ( ''' ''', BibliographyData(), ), ( '''@ARTICLE{ test, title={Polluted with {DDT}. }, }''', BibliographyData({u'test': Entry('article', {u'title': 'Polluted with {DDT}.'})}), ), ( '''@ARTICLE{ test, title="Nested braces and {"quotes"}", }''', BibliographyData({u'test': Entry('article', {u'title': 'Nested braces and {"quotes"}'})}), ), ] def _test(bibtex_input, correct_result): parser = Parser(encoding='UTF-8') parser.parse_stream(StringIO(bibtex_input)) result = parser.data assert result == correct_result def test_bibtex_parser(): for bibtex_input, correct_result in test_data: _test(bibtex_input, correct_result)
48f1d12f97be8a7bca60809967b88f77ba7d6393
setup.py
setup.py
from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
Use new Epsilon versioned feature.
Use new Epsilon versioned feature.
Python
mit
twisted/axiom,hawkowl/axiom
from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj) Use new Epsilon versioned feature.
from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
<commit_before>from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj) <commit_msg>Use new Epsilon versioned feature.<commit_after>
from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj) Use new Epsilon versioned feature.from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
<commit_before>from distutils.core import setup distobj = setup( name="Axiom", version="0.1", maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/AxiomProject", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj) <commit_msg>Use new Epsilon versioned feature.<commit_after>from distutils.core import setup import axiom distobj = setup( name="Axiom", version=axiom.version.short(), maintainer="Divmod, Inc.", maintainer_email="support@divmod.org", url="http://divmod.org/trac/wiki/DivmodAxiom", license="MIT", platforms=["any"], description="An in-process object-relational database", classifiers=[ "Intended Audience :: Developers", "Programming Language :: Python", "Development Status :: 2 - Pre-Alpha", "Topic :: Database"], scripts=['bin/axiomatic'], packages=['axiom', 'axiom.scripts', 'axiom.plugins', 'axiom.test'], package_data={'axiom': ['examples/*']}) from epsilon.setuphelper import regeneratePluginCache regeneratePluginCache(distobj)
88791b8ec57c5a19e6be6daccfd09b6cb53bdbe8
setup.py
setup.py
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), )
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), project_urls={ 'Homepage': 'http://taskcluster.github.io/slugid.py', 'Source': 'https://github.com/taskcluster/slugid.py', }, )
Add Homepage and Source project URLs for PyPI
Add Homepage and Source project URLs for PyPI
Python
mpl-2.0
taskcluster/slugid.py
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), ) Add Homepage and Source project URLs for PyPI
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), project_urls={ 'Homepage': 'http://taskcluster.github.io/slugid.py', 'Source': 'https://github.com/taskcluster/slugid.py', }, )
<commit_before>#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), ) <commit_msg>Add Homepage and Source project URLs for PyPI<commit_after>
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), project_urls={ 'Homepage': 'http://taskcluster.github.io/slugid.py', 'Source': 'https://github.com/taskcluster/slugid.py', }, )
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), ) Add Homepage and Source project URLs for PyPI#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), project_urls={ 'Homepage': 'http://taskcluster.github.io/slugid.py', 'Source': 'https://github.com/taskcluster/slugid.py', }, )
<commit_before>#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), ) <commit_msg>Add Homepage and Source project URLs for PyPI<commit_after>#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'slugid', ] version = '' with open('slugid/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError('Cannot find version information') setup( name='slugid', version=version, description='Base64 encoded uuid v4 slugs', author='Pete Moore', author_email='pmoore@mozilla.com', url='http://taskcluster.github.io/slugid.py', packages=packages, package_data={'': ['LICENSE', 'README.md']}, license='MPL 2.0', classifiers=( 'Intended Audience :: Developers', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', ), project_urls={ 'Homepage': 'http://taskcluster.github.io/slugid.py', 'Source': 'https://github.com/taskcluster/slugid.py', }, )
8ab509811887a3495a55951ece04c2e1e5af38eb
cass-prototype/reddit/models.py
cass-prototype/reddit/models.py
import uuid from cassandra.cqlengine import columns, models class Blog(models.Model): blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False)
""" In a real app, we should probably split all these models into separate apps. Since this is a prototype, we have it all here to more easily understand Resource: https://datastax.github.io/python-driver/cqlengine/models.html """ import uuid from cassandra.cqlengine import columns, models, usertype, ValidationError class Address(usertype.UserType): """ Custom field: Address """ street = columns.Text(required=True) zipcode = columns.Integer() email = columns.Text() def validate(self): super(Address, self).validate() if len(self.zipcode) < 4: raise ValidationError("This Zip Code seems too short") class User(models.Model): """ A User """ user_id = columns.UUID(primary_key=True) first_name = columns.Text() last_name = columns.Text() addr = columns.UserDefinedType(Address) todo_list = columns.List(columns.Text) favorite_restaurant = columns.Map(columns.Text, columns.Text) favorite_numbers = columns.Set(columns.Integer) class Blog(models.Model): """ General Info about a Blog (aka a Subreddit) """ blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) class Post(models.Model): """ A Post inside a Blog/Subreddit """ post_id = columns.TimeUUID(primary_key=True, partition_key=True) blog_id = columns.UUID(partition_key=True) created_at = columns.DateTime() post_title = columns.Text() content = columns.Text() tags = columns.Set(columns.Text) flagged = columns.Boolean(default=False) class PostVote(models.Model): """ Cassandra requires counters in a separate table (unless the counter is part of the primary key definition, which in this case it isn't) """ post_id = columns.TimeUUID(primary_key=True, default=uuid.uuid4) upvotes = columns.Counter() downvotes = columns.Counter() class Category(models.Model): name = columns.Text(primary_key=True) blog_id = columns.UUID(primary_key=True) post_id = columns.TimeUUID(primary_key=True) post_title = columns.Text()
Add more Data Models with different Column types
Add more Data Models with different Column types
Python
mit
WilliamQLiu/django-cassandra-prototype,WilliamQLiu/django-cassandra-prototype
import uuid from cassandra.cqlengine import columns, models class Blog(models.Model): blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) Add more Data Models with different Column types
""" In a real app, we should probably split all these models into separate apps. Since this is a prototype, we have it all here to more easily understand Resource: https://datastax.github.io/python-driver/cqlengine/models.html """ import uuid from cassandra.cqlengine import columns, models, usertype, ValidationError class Address(usertype.UserType): """ Custom field: Address """ street = columns.Text(required=True) zipcode = columns.Integer() email = columns.Text() def validate(self): super(Address, self).validate() if len(self.zipcode) < 4: raise ValidationError("This Zip Code seems too short") class User(models.Model): """ A User """ user_id = columns.UUID(primary_key=True) first_name = columns.Text() last_name = columns.Text() addr = columns.UserDefinedType(Address) todo_list = columns.List(columns.Text) favorite_restaurant = columns.Map(columns.Text, columns.Text) favorite_numbers = columns.Set(columns.Integer) class Blog(models.Model): """ General Info about a Blog (aka a Subreddit) """ blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) class Post(models.Model): """ A Post inside a Blog/Subreddit """ post_id = columns.TimeUUID(primary_key=True, partition_key=True) blog_id = columns.UUID(partition_key=True) created_at = columns.DateTime() post_title = columns.Text() content = columns.Text() tags = columns.Set(columns.Text) flagged = columns.Boolean(default=False) class PostVote(models.Model): """ Cassandra requires counters in a separate table (unless the counter is part of the primary key definition, which in this case it isn't) """ post_id = columns.TimeUUID(primary_key=True, default=uuid.uuid4) upvotes = columns.Counter() downvotes = columns.Counter() class Category(models.Model): name = columns.Text(primary_key=True) blog_id = columns.UUID(primary_key=True) post_id = columns.TimeUUID(primary_key=True) post_title = columns.Text()
<commit_before>import uuid from cassandra.cqlengine import columns, models class Blog(models.Model): blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) <commit_msg>Add more Data Models with different Column types<commit_after>
""" In a real app, we should probably split all these models into separate apps. Since this is a prototype, we have it all here to more easily understand Resource: https://datastax.github.io/python-driver/cqlengine/models.html """ import uuid from cassandra.cqlengine import columns, models, usertype, ValidationError class Address(usertype.UserType): """ Custom field: Address """ street = columns.Text(required=True) zipcode = columns.Integer() email = columns.Text() def validate(self): super(Address, self).validate() if len(self.zipcode) < 4: raise ValidationError("This Zip Code seems too short") class User(models.Model): """ A User """ user_id = columns.UUID(primary_key=True) first_name = columns.Text() last_name = columns.Text() addr = columns.UserDefinedType(Address) todo_list = columns.List(columns.Text) favorite_restaurant = columns.Map(columns.Text, columns.Text) favorite_numbers = columns.Set(columns.Integer) class Blog(models.Model): """ General Info about a Blog (aka a Subreddit) """ blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) class Post(models.Model): """ A Post inside a Blog/Subreddit """ post_id = columns.TimeUUID(primary_key=True, partition_key=True) blog_id = columns.UUID(partition_key=True) created_at = columns.DateTime() post_title = columns.Text() content = columns.Text() tags = columns.Set(columns.Text) flagged = columns.Boolean(default=False) class PostVote(models.Model): """ Cassandra requires counters in a separate table (unless the counter is part of the primary key definition, which in this case it isn't) """ post_id = columns.TimeUUID(primary_key=True, default=uuid.uuid4) upvotes = columns.Counter() downvotes = columns.Counter() class Category(models.Model): name = columns.Text(primary_key=True) blog_id = columns.UUID(primary_key=True) post_id = columns.TimeUUID(primary_key=True) post_title = columns.Text()
import uuid from cassandra.cqlengine import columns, models class Blog(models.Model): blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) Add more Data Models with different Column types""" In a real app, we should probably split all these models into separate apps. Since this is a prototype, we have it all here to more easily understand Resource: https://datastax.github.io/python-driver/cqlengine/models.html """ import uuid from cassandra.cqlengine import columns, models, usertype, ValidationError class Address(usertype.UserType): """ Custom field: Address """ street = columns.Text(required=True) zipcode = columns.Integer() email = columns.Text() def validate(self): super(Address, self).validate() if len(self.zipcode) < 4: raise ValidationError("This Zip Code seems too short") class User(models.Model): """ A User """ user_id = columns.UUID(primary_key=True) first_name = columns.Text() last_name = columns.Text() addr = columns.UserDefinedType(Address) todo_list = columns.List(columns.Text) favorite_restaurant = columns.Map(columns.Text, columns.Text) favorite_numbers = columns.Set(columns.Integer) class Blog(models.Model): """ General Info about a Blog (aka a Subreddit) """ blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) class Post(models.Model): """ A Post inside a Blog/Subreddit """ post_id = columns.TimeUUID(primary_key=True, partition_key=True) blog_id = columns.UUID(partition_key=True) created_at = columns.DateTime() post_title = columns.Text() content = columns.Text() tags = columns.Set(columns.Text) flagged = columns.Boolean(default=False) class PostVote(models.Model): """ Cassandra requires counters in a separate table (unless the counter is part of the primary key definition, which in this case it isn't) """ post_id = columns.TimeUUID(primary_key=True, default=uuid.uuid4) upvotes = columns.Counter() downvotes = columns.Counter() class Category(models.Model): name = columns.Text(primary_key=True) blog_id = columns.UUID(primary_key=True) post_id = columns.TimeUUID(primary_key=True) post_title = columns.Text()
<commit_before>import uuid from cassandra.cqlengine import columns, models class Blog(models.Model): blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) <commit_msg>Add more Data Models with different Column types<commit_after>""" In a real app, we should probably split all these models into separate apps. Since this is a prototype, we have it all here to more easily understand Resource: https://datastax.github.io/python-driver/cqlengine/models.html """ import uuid from cassandra.cqlengine import columns, models, usertype, ValidationError class Address(usertype.UserType): """ Custom field: Address """ street = columns.Text(required=True) zipcode = columns.Integer() email = columns.Text() def validate(self): super(Address, self).validate() if len(self.zipcode) < 4: raise ValidationError("This Zip Code seems too short") class User(models.Model): """ A User """ user_id = columns.UUID(primary_key=True) first_name = columns.Text() last_name = columns.Text() addr = columns.UserDefinedType(Address) todo_list = columns.List(columns.Text) favorite_restaurant = columns.Map(columns.Text, columns.Text) favorite_numbers = columns.Set(columns.Integer) class Blog(models.Model): """ General Info about a Blog (aka a Subreddit) """ blog_id = columns.UUID(primary_key=True, default=uuid.uuid4) created_at = columns.DateTime() user = columns.Text(index=True) description = columns.Text(required=False) class Post(models.Model): """ A Post inside a Blog/Subreddit """ post_id = columns.TimeUUID(primary_key=True, partition_key=True) blog_id = columns.UUID(partition_key=True) created_at = columns.DateTime() post_title = columns.Text() content = columns.Text() tags = columns.Set(columns.Text) flagged = columns.Boolean(default=False) class PostVote(models.Model): """ Cassandra requires counters in a separate table (unless the counter is part of the primary key definition, which in this case it isn't) """ post_id = columns.TimeUUID(primary_key=True, default=uuid.uuid4) upvotes = columns.Counter() downvotes = columns.Counter() class Category(models.Model): name = columns.Text(primary_key=True) blog_id = columns.UUID(primary_key=True) post_id = columns.TimeUUID(primary_key=True) post_title = columns.Text()
0a88885f322f49c9f4cc990a3147f1ee162e8fe4
cellcounter/statistics/views.py
cellcounter/statistics/views.py
from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,)
from rest_framework import status from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from rest_framework.response import Response from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if self.request.user.is_authenticated(): user = self.request.user else: user = None serializer.save(session_id=request.session.session_key, ip_address=request.META.get('REMOTE_ADDR'), user=user) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Update create() method of view to include extra data
Update create() method of view to include extra data
Python
mit
haematologic/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter
from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) Update create() method of view to include extra data
from rest_framework import status from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from rest_framework.response import Response from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if self.request.user.is_authenticated(): user = self.request.user else: user = None serializer.save(session_id=request.session.session_key, ip_address=request.META.get('REMOTE_ADDR'), user=user) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
<commit_before>from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) <commit_msg>Update create() method of view to include extra data<commit_after>
from rest_framework import status from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from rest_framework.response import Response from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if self.request.user.is_authenticated(): user = self.request.user else: user = None serializer.save(session_id=request.session.session_key, ip_address=request.META.get('REMOTE_ADDR'), user=user) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) Update create() method of view to include extra datafrom rest_framework import status from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from rest_framework.response import Response from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if self.request.user.is_authenticated(): user = self.request.user else: user = None serializer.save(session_id=request.session.session_key, ip_address=request.META.get('REMOTE_ADDR'), user=user) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
<commit_before>from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) <commit_msg>Update create() method of view to include extra data<commit_after>from rest_framework import status from rest_framework.generics import ListCreateAPIView from rest_framework.permissions import BasePermission from rest_framework.throttling import AnonRateThrottle from rest_framework.response import Response from .serializers import CountInstanceSerializer from .models import CountInstance SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class OpenPostStaffGet(BasePermission): """ Allows posting by anonymous users, but requires a staff user to GET/HEAD/OPTIONS """ def has_permission(self, request, view): if (request.method == 'POST' or request.method in SAFE_METHODS and request.user.is_authenticated() and request.user.is_staff): return True return False class CountInstanceAnonThrottle(AnonRateThrottle): rate = '1/minute' class ListCreateCountInstanceAPI(ListCreateAPIView): permission_classes = (OpenPostStaffGet,) serializer_class = CountInstanceSerializer queryset = CountInstance.objects.all() throttle_classes = (CountInstanceAnonThrottle,) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) if self.request.user.is_authenticated(): user = self.request.user else: user = None serializer.save(session_id=request.session.session_key, ip_address=request.META.get('REMOTE_ADDR'), user=user) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
cfe6638194d477968689f3062af398630170fd80
foodsaving/conversations/serializers.py
foodsaving/conversations/serializers.py
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def validate_conversation(self, conversation): if self.context['request'].user not in conversation.participants.all(): raise serializers.ValidationError("You are not in this conversation") return conversation def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
Validate user is in conversation on create message
Validate user is in conversation on create message
Python
agpl-3.0
yunity/yunity-core,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/foodsaving-backend
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) Validate user is in conversation on create message
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def validate_conversation(self, conversation): if self.context['request'].user not in conversation.participants.all(): raise serializers.ValidationError("You are not in this conversation") return conversation def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
<commit_before>from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) <commit_msg>Validate user is in conversation on create message<commit_after>
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def validate_conversation(self, conversation): if self.context['request'].user not in conversation.participants.all(): raise serializers.ValidationError("You are not in this conversation") return conversation def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) Validate user is in conversation on create messagefrom rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def validate_conversation(self, conversation): if self.context['request'].user not in conversation.participants.all(): raise serializers.ValidationError("You are not in this conversation") return conversation def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
<commit_before>from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) <commit_msg>Validate user is in conversation on create message<commit_after>from rest_framework import serializers from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def validate_conversation(self, conversation): if self.context['request'].user not in conversation.participants.all(): raise serializers.ValidationError("You are not in this conversation") return conversation def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
4f94e7bc314e31f322c912762339fda047d04688
src/gpio-shutdown.py
src/gpio-shutdown.py
#!/usr/bin/env python3 import RPIO import subprocess PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main()
#!/usr/bin/env python3 import RPIO import subprocess import time PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() # do an efficient spin-lock here so that we can continue waiting for an # interrupt while True: # this sleep() is an attempt to prevent the CPU from staying at 100% time.sleep(10)
Add sleeping spin-wait to listener script
Add sleeping spin-wait to listener script This will prevent the script from exiting, thus defeating the entire purpose of using a separate GPIO button to shutdown
Python
epl-1.0
MSOE-Supermileage/datacollector,MSOE-Supermileage/datacollector,MSOE-Supermileage/datacollector
#!/usr/bin/env python3 import RPIO import subprocess PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() Add sleeping spin-wait to listener script This will prevent the script from exiting, thus defeating the entire purpose of using a separate GPIO button to shutdown
#!/usr/bin/env python3 import RPIO import subprocess import time PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() # do an efficient spin-lock here so that we can continue waiting for an # interrupt while True: # this sleep() is an attempt to prevent the CPU from staying at 100% time.sleep(10)
<commit_before>#!/usr/bin/env python3 import RPIO import subprocess PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() <commit_msg> Add sleeping spin-wait to listener script This will prevent the script from exiting, thus defeating the entire purpose of using a separate GPIO button to shutdown<commit_after>
#!/usr/bin/env python3 import RPIO import subprocess import time PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() # do an efficient spin-lock here so that we can continue waiting for an # interrupt while True: # this sleep() is an attempt to prevent the CPU from staying at 100% time.sleep(10)
#!/usr/bin/env python3 import RPIO import subprocess PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() Add sleeping spin-wait to listener script This will prevent the script from exiting, thus defeating the entire purpose of using a separate GPIO button to shutdown#!/usr/bin/env python3 import RPIO import subprocess import time PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() # do an efficient spin-lock here so that we can continue waiting for an # interrupt while True: # this sleep() is an attempt to prevent the CPU from staying at 100% time.sleep(10)
<commit_before>#!/usr/bin/env python3 import RPIO import subprocess PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() <commit_msg> Add sleeping spin-wait to listener script This will prevent the script from exiting, thus defeating the entire purpose of using a separate GPIO button to shutdown<commit_after>#!/usr/bin/env python3 import RPIO import subprocess import time PIN_MODE = RPIO.BCM SHUTDOWN_BTN_PIN = 4 PIN_PULL = RPIO.PUD_DOWN EDGE_DETECT = 'rising' def main(): RPIO.setmode(PIN_MODE) RPIO.setup(SHUTDOWN_BTN_PIN, RPIO.IN, pull_up_down=PIN_PULL) RPIO.add_interrupt_callback(SHUTDOWN_BTN_PIN, shutdown_callback, edge=EDGE_DETECT, pull_up_down=PIN_PULL, debounce_timeout_ms=33) def shutdown_callback(gpio_id, value): subprocess.call('shutdown now') if __name__ == '__main__': main() # do an efficient spin-lock here so that we can continue waiting for an # interrupt while True: # this sleep() is an attempt to prevent the CPU from staying at 100% time.sleep(10)
cf18a3141f6b9d618cd35adc2f574965fba29c92
tests/testcases.py
tests/testcases.py
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) for i in self.client.images(): if 'figtest' in i['Tag']: self.client.remove_image(i) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
Remove images created by tests
Remove images created by tests
Python
apache-2.0
anweiss/docker.github.io,ekristen/compose,dilgerma/compose,aduermael/docker.github.io,Yelp/docker-compose,bsmr-docker/compose,bfirsh/fig,jgrowl/compose,nerro/compose,londoncalling/docker.github.io,ChrisChinchilla/compose,shubheksha/docker.github.io,prologic/compose,shubheksha/docker.github.io,danix800/docker.github.io,uvgroovy/compose,Chouser/compose,mrfuxi/compose,ralphtheninja/compose,docker-zh/docker.github.io,docker/docker.github.io,kojiromike/compose,johnstep/docker.github.io,bdwill/docker.github.io,kikkomep/compose,genki/compose,denverdino/denverdino.github.io,Yelp/docker-compose,joeuo/docker.github.io,unodba/compose,au-phiware/compose,twitherspoon/compose,BSWANG/denverdino.github.io,heroku/fig,ZJaffee/compose,charleswhchan/compose,gdevillele/docker.github.io,heroku/fig,mnuessler/compose,BSWANG/denverdino.github.io,alunduil/fig,shin-/docker.github.io,mark-adams/compose,dockerhn/compose,TomasTomecek/compose,ouziel-slama/compose,brunocascio/compose,nhumrich/compose,calou/compose,joaofnfernandes/docker.github.io,ain/compose,LuisBosquez/docker.github.io,feelobot/compose,cclauss/compose,VinceBarresi/compose,phiroict/docker,johnstep/docker.github.io,GM-Alex/compose,thaJeztah/docker.github.io,phiroict/docker,thaJeztah/docker.github.io,KalleDK/compose,simonista/compose,thaJeztah/docker.github.io,DoubleMalt/compose,rillig/docker.github.io,docker/docker.github.io,troy0820/docker.github.io,phiroict/docker,dnephin/compose,pspierce/compose,Dakno/compose,philwrenn/compose,thaJeztah/compose,joeuo/docker.github.io,Katlean/fig,ain/compose,mnuessler/compose,ChrisChinchilla/compose,Chouser/compose,tpounds/compose,anweiss/docker.github.io,LuisBosquez/docker.github.io,troy0820/docker.github.io,bcicen/fig,benhamill/compose,joeuo/docker.github.io,qzio/compose,joaofnfernandes/docker.github.io,aduermael/docker.github.io,TomasTomecek/compose,ionrock/compose,pspierce/compose,jzwlqx/denverdino.github.io,mrfuxi/compose,VinceBarresi/compose,jiekechoo/compose,swoopla/compose,bdwill/docker.github.io,saada/compose,simonista/compose,jessekl/compose,andrewgee/compose,gtrdotmcs/compose,londoncalling/docker.github.io,alunduil/fig,au-phiware/compose,amitsaha/compose,sanscontext/docker.github.io,danix800/docker.github.io,sanscontext/docker.github.io,LuisBosquez/docker.github.io,jonaseck2/compose,mdaue/compose,jeanpralo/compose,glogiotatidis/compose,j-fuentes/compose,hoogenm/compose,ggtools/compose,shin-/docker.github.io,mohitsoni/compose,mosquito/docker-compose,ZJaffee/compose,menglingwei/denverdino.github.io,tangkun75/compose,mbailey/compose,JimGalasyn/docker.github.io,danix800/docker.github.io,docker-zh/docker.github.io,thieman/compose,nhumrich/compose,KalleDK/compose,JimGalasyn/docker.github.io,alexisbellido/docker.github.io,dockerhn/compose,hypriot/compose,rgbkrk/compose,johnstep/docker.github.io,bbirand/compose,jorgeLuizChaves/compose,aanand/fig,docker/docker.github.io,iamluc/compose,bcicen/fig,tiry/compose,joaofnfernandes/docker.github.io,sebglazebrook/compose,artemkaint/compose,schmunk42/compose,kojiromike/compose,vlajos/compose,noironetworks/compose,sebglazebrook/compose,denverdino/denverdino.github.io,goloveychuk/compose,sanscontext/docker.github.io,denverdino/denverdino.github.io,shin-/compose,benhamill/compose,bsmr-docker/compose,shin-/docker.github.io,mdaue/compose,bobphill/compose,docker/docker.github.io,rillig/docker.github.io,gdevillele/docker.github.io,unodba/compose,alexisbellido/docker.github.io,abesto/fig,Dakno/compose,mindaugasrukas/compose,jrabbit/compose,qzio/compose,uvgroovy/compose,jzwlqx/denverdino.github.io,kikkomep/compose,goloveychuk/compose,shin-/compose,mnowster/compose,mindaugasrukas/compose,josephpage/compose,iamluc/compose,xydinesh/compose,vlajos/compose,moxiegirl/compose,GM-Alex/compose,rstacruz/compose,gdevillele/docker.github.io,artemkaint/compose,jzwlqx/denverdino.github.io,denverdino/docker.github.io,ggtools/compose,bfirsh/fig,amitsaha/compose,andrewgee/compose,alexandrev/compose,denverdino/compose,browning/compose,bdwill/docker.github.io,runcom/compose,troy0820/docker.github.io,ionrock/compose,johnstep/docker.github.io,jrabbit/compose,dopry/compose,tpounds/compose,j-fuentes/compose,zhangspook/compose,alexisbellido/docker.github.io,glogiotatidis/compose,michael-k/docker-compose,shin-/docker.github.io,jzwlqx/denverdino.github.io,danix800/docker.github.io,bdwill/docker.github.io,saada/compose,charleswhchan/compose,bbirand/compose,thaJeztah/compose,shakamunyi/fig,alexisbellido/docker.github.io,josephpage/compose,joaofnfernandes/docker.github.io,joaofnfernandes/docker.github.io,rillig/docker.github.io,LuisBosquez/docker.github.io,rstacruz/compose,alexandrev/compose,thaJeztah/docker.github.io,genki/compose,alexisbellido/docker.github.io,screwgoth/compose,bobphill/compose,denverdino/docker.github.io,cgvarela/compose,troy0820/docker.github.io,jessekl/compose,moxiegirl/compose,rgbkrk/compose,prologic/compose,heroku/fig,bcicen/fig,denverdino/denverdino.github.io,dopry/compose,jeanpralo/compose,docker-zh/docker.github.io,hypriot/compose,albers/compose,abesto/fig,aduermael/docker.github.io,sanscontext/docker.github.io,jonaseck2/compose,mchasal/compose,KevinGreene/compose,shubheksha/docker.github.io,d2bit/compose,TheDataShed/compose,rillig/docker.github.io,anweiss/docker.github.io,lmesz/compose,sanscontext/docker.github.io,gtrdotmcs/compose,funkyfuture/docker-compose,xydinesh/compose,JimGalasyn/docker.github.io,calou/compose,runcom/compose,funkyfuture/docker-compose,twitherspoon/compose,bdwill/docker.github.io,docker/docker.github.io,marcusmartins/compose,talolard/compose,joeuo/docker.github.io,docker-zh/docker.github.io,johnstep/docker.github.io,phiroict/docker,BSWANG/denverdino.github.io,swoopla/compose,BSWANG/denverdino.github.io,viranch/compose,aduermael/docker.github.io,BSWANG/denverdino.github.io,MSakamaki/compose,LuisBosquez/docker.github.io,d2bit/compose,menglingwei/denverdino.github.io,thieman/compose,docker-zh/docker.github.io,londoncalling/docker.github.io,londoncalling/docker.github.io,shakamunyi/fig,denverdino/docker.github.io,RobertNorthard/compose,anweiss/docker.github.io,joeuo/docker.github.io,lmesz/compose,ph-One/compose,ralphtheninja/compose,denverdino/compose,thaJeztah/docker.github.io,talolard/compose,shubheksha/docker.github.io,michael-k/docker-compose,jgrowl/compose,mohitsoni/compose,denverdino/docker.github.io,ekristen/compose,mosquito/docker-compose,aanand/fig,lukemarsden/compose,vdemeester/compose,sdurrheimer/compose,browning/compose,menglingwei/denverdino.github.io,zhangspook/compose,mnowster/compose,denverdino/denverdino.github.io,shubheksha/docker.github.io,ph-One/compose,TheDataShed/compose,dnephin/compose,dbdd4us/compose,jzwlqx/denverdino.github.io,tiry/compose,cclauss/compose,KevinGreene/compose,denverdino/docker.github.io,philwrenn/compose,mbailey/compose,mark-adams/compose,DoubleMalt/compose,nerro/compose,marcusmartins/compose,jiekechoo/compose,phiroict/docker,brunocascio/compose,JimGalasyn/docker.github.io,Katlean/fig,viranch/compose,tangkun75/compose,lukemarsden/compose,RobertNorthard/compose,noironetworks/compose,JimGalasyn/docker.github.io,mchasal/compose,albers/compose,ouziel-slama/compose,jorgeLuizChaves/compose,schmunk42/compose,anweiss/docker.github.io,gdevillele/docker.github.io,vdemeester/compose,londoncalling/docker.github.io,shin-/docker.github.io,gdevillele/docker.github.io,feelobot/compose,menglingwei/denverdino.github.io,sdurrheimer/compose,dilgerma/compose,cgvarela/compose,hoogenm/compose,screwgoth/compose,menglingwei/denverdino.github.io,MSakamaki/compose,dbdd4us/compose
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs ) Remove images created by tests
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) for i in self.client.images(): if 'figtest' in i['Tag']: self.client.remove_image(i) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
<commit_before>from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs ) <commit_msg>Remove images created by tests<commit_after>
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) for i in self.client.images(): if 'figtest' in i['Tag']: self.client.remove_image(i) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs ) Remove images created by testsfrom __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) for i in self.client.images(): if 'figtest' in i['Tag']: self.client.remove_image(i) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
<commit_before>from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs ) <commit_msg>Remove images created by tests<commit_after>from __future__ import unicode_literals from __future__ import absolute_import from fig.packages.docker import Client from fig.service import Service from fig.cli.utils import docker_url from . import unittest class DockerClientTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = Client(docker_url()) cls.client.pull('ubuntu') def setUp(self): for c in self.client.containers(all=True): if c['Names'] and 'figtest' in c['Names'][0]: self.client.kill(c['Id']) self.client.remove_container(c['Id']) for i in self.client.images(): if 'figtest' in i['Tag']: self.client.remove_image(i) def create_service(self, name, **kwargs): return Service( project='figtest', name=name, client=self.client, image="ubuntu", command=["/bin/sleep", "300"], **kwargs )
e51087bf04f56ae79a8af8ae059a2dbe28fb1d74
src/oscar/core/decorators.py
src/oscar/core/decorators.py
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = "Method '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % f.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = "Class '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % cls.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings from oscar.utils.deprecation import RemovedInOscar15Warning def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = ( "Method '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (f.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = ( "Class '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (cls.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated
Set RemovedInOscar15Warning for existing deprecation warnings
Set RemovedInOscar15Warning for existing deprecation warnings
Python
bsd-3-clause
solarissmoke/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,solarissmoke/django-oscar,django-oscar/django-oscar,sasha0/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,solarissmoke/django-oscar
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = "Method '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % f.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = "Class '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % cls.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated Set RemovedInOscar15Warning for existing deprecation warnings
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings from oscar.utils.deprecation import RemovedInOscar15Warning def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = ( "Method '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (f.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = ( "Class '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (cls.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated
<commit_before>try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = "Method '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % f.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = "Class '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % cls.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated <commit_msg>Set RemovedInOscar15Warning for existing deprecation warnings<commit_after>
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings from oscar.utils.deprecation import RemovedInOscar15Warning def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = ( "Method '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (f.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = ( "Class '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (cls.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated
try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = "Method '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % f.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = "Class '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % cls.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated Set RemovedInOscar15Warning for existing deprecation warningstry: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings from oscar.utils.deprecation import RemovedInOscar15Warning def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = ( "Method '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (f.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = ( "Class '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (cls.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated
<commit_before>try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = "Method '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % f.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = "Class '%s' is deprecated and will be " \ "removed in the next major version of django-oscar" \ % cls.__name__ warnings.warn(message, DeprecationWarning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated <commit_msg>Set RemovedInOscar15Warning for existing deprecation warnings<commit_after>try: from types import ClassType except ImportError: # Python 3 CHECK_TYPES = (type,) else: # Python 2: new and old-style classes CHECK_TYPES = (type, ClassType) import warnings from oscar.utils.deprecation import RemovedInOscar15Warning def deprecated(obj): if isinstance(obj, CHECK_TYPES): return _deprecated_cls(cls=obj) else: return _deprecated_func(f=obj) def _deprecated_func(f): def _deprecated(*args, **kwargs): message = ( "Method '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (f.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) return f(*args, **kwargs) return _deprecated def _deprecated_cls(cls): class Deprecated(cls): def __init__(self, *args, **kwargs): message = ( "Class '%s' is deprecated and will be " + "removed in Oscar 1.5" ) % (cls.__name__) warnings.warn(message, RemovedInOscar15Warning, stacklevel=2) super(Deprecated, self).__init__(*args, **kwargs) return Deprecated
b42e271885968239c1779df546c57597437aa2da
src/test/test_all.py
src/test/test_all.py
from astral.geocoder import all_locations from astral.sun import sun def test_AllLocations(test_database): for location in all_locations(test_database): sun(location.observer)
from astral.geocoder import all_locations from astral.sun import noon def test_AllLocations(test_database): for location in all_locations(test_database): noon(location.observer)
Use the `noon` function instead of `sun`.
Use the `noon` function instead of `sun`. All we're doing is check that we can call the function for all locations. This can fail for `sun` but does not for `noon`
Python
apache-2.0
sffjunkie/astral,sffjunkie/astral
from astral.geocoder import all_locations from astral.sun import sun def test_AllLocations(test_database): for location in all_locations(test_database): sun(location.observer) Use the `noon` function instead of `sun`. All we're doing is check that we can call the function for all locations. This can fail for `sun` but does not for `noon`
from astral.geocoder import all_locations from astral.sun import noon def test_AllLocations(test_database): for location in all_locations(test_database): noon(location.observer)
<commit_before>from astral.geocoder import all_locations from astral.sun import sun def test_AllLocations(test_database): for location in all_locations(test_database): sun(location.observer) <commit_msg>Use the `noon` function instead of `sun`. All we're doing is check that we can call the function for all locations. This can fail for `sun` but does not for `noon`<commit_after>
from astral.geocoder import all_locations from astral.sun import noon def test_AllLocations(test_database): for location in all_locations(test_database): noon(location.observer)
from astral.geocoder import all_locations from astral.sun import sun def test_AllLocations(test_database): for location in all_locations(test_database): sun(location.observer) Use the `noon` function instead of `sun`. All we're doing is check that we can call the function for all locations. This can fail for `sun` but does not for `noon`from astral.geocoder import all_locations from astral.sun import noon def test_AllLocations(test_database): for location in all_locations(test_database): noon(location.observer)
<commit_before>from astral.geocoder import all_locations from astral.sun import sun def test_AllLocations(test_database): for location in all_locations(test_database): sun(location.observer) <commit_msg>Use the `noon` function instead of `sun`. All we're doing is check that we can call the function for all locations. This can fail for `sun` but does not for `noon`<commit_after>from astral.geocoder import all_locations from astral.sun import noon def test_AllLocations(test_database): for location in all_locations(test_database): noon(location.observer)
5fc503c05ed9eadfc831e0521a40b16a9810d8fa
plenum/__metadata__.py
plenum/__metadata__.py
""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
Increase plenum version to 0.1.158
Increase plenum version to 0.1.158
Python
apache-2.0
evernym/plenum,evernym/zeno
""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } Increase plenum version to 0.1.158
""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
<commit_before>""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } <commit_msg>Increase plenum version to 0.1.158<commit_after>
""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } Increase plenum version to 0.1.158""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
<commit_before>""" plenum package metadata """ __version_info__ = (0, 1, 157) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" } <commit_msg>Increase plenum version to 0.1.158<commit_after>""" plenum package metadata """ __version_info__ = (0, 1, 158) __version__ = '{}.{}.{}'.format(*__version_info__) __author__ = "Evernym, Inc." __license__ = "Apache 2.0" __all__ = ['__version_info__', '__version__', '__author__', '__license__'] __dependencies__ = { "ledger": ">=0.0.31" }
864f10669895ac28f17167a2be84bcab7fd9e389
conf/jupyter_notebook_config.py
conf/jupyter_notebook_config.py
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
Disable delete_to_trash to prevent an error while deleting
Disable delete_to_trash to prevent an error while deleting
Python
bsd-3-clause
NII-cloud-operation/Jupyter-LC_docker,NII-cloud-operation/Jupyter-LC_docker
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD'] Disable delete_to_trash to prevent an error while deleting
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
<commit_before>import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD'] <commit_msg>Disable delete_to_trash to prevent an error while deleting<commit_after>
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD'] Disable delete_to_trash to prevent an error while deletingimport os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
<commit_before>import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD'] <commit_msg>Disable delete_to_trash to prevent an error while deleting<commit_after>import os c.NotebookApp.ip = '*' c.MultiKernelManager.kernel_manager_class = 'lc_wrapper.LCWrapperKernelManager' c.KernelManager.shutdown_wait_time = 10.0 c.FileContentsManager.delete_to_trash = False if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD']
5fc4af3039caec0f245e04e5a219451dfb73fb9c
distarray/localapi/tests/test_format.py
distarray/localapi/tests/test_format.py
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected)
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) class TestReadMagic(unittest.TestCase): def test_read_magic(self): prefix = six.b('\x93DARRY') prefix_len = 8 fp = six.BytesIO(six.b('\x93DARRY\x03\x02')) major, minor = fmt.read_magic(fp, prefix=prefix, prefix_len=prefix_len) expected = (3, 2) self.assertEqual((major, minor), expected)
Add a test for read_magic.
Add a test for read_magic.
Python
bsd-3-clause
enthought/distarray,enthought/distarray
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) Add a test for read_magic.
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) class TestReadMagic(unittest.TestCase): def test_read_magic(self): prefix = six.b('\x93DARRY') prefix_len = 8 fp = six.BytesIO(six.b('\x93DARRY\x03\x02')) major, minor = fmt.read_magic(fp, prefix=prefix, prefix_len=prefix_len) expected = (3, 2) self.assertEqual((major, minor), expected)
<commit_before># encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) <commit_msg>Add a test for read_magic.<commit_after>
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) class TestReadMagic(unittest.TestCase): def test_read_magic(self): prefix = six.b('\x93DARRY') prefix_len = 8 fp = six.BytesIO(six.b('\x93DARRY\x03\x02')) major, minor = fmt.read_magic(fp, prefix=prefix, prefix_len=prefix_len) expected = (3, 2) self.assertEqual((major, minor), expected)
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) Add a test for read_magic.# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) class TestReadMagic(unittest.TestCase): def test_read_magic(self): prefix = six.b('\x93DARRY') prefix_len = 8 fp = six.BytesIO(six.b('\x93DARRY\x03\x02')) major, minor = fmt.read_magic(fp, prefix=prefix, prefix_len=prefix_len) expected = (3, 2) self.assertEqual((major, minor), expected)
<commit_before># encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) <commit_msg>Add a test for read_magic.<commit_after># encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- import unittest import six from distarray.localapi import format as fmt class TestMagic(unittest.TestCase): def test_magic_0(self): expected = six.b('\x93DARRY\x03\x02') prefix = six.b('\x93DARRY') major = 3 minor = 2 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) def test_magic_1(self): expected = six.b('\x93NUMPY\x01\x00') prefix = six.b('\x93NUMPY') major = 1 minor = 0 result = fmt.magic(major=major, minor=minor, prefix=prefix) self.assertEqual(result, expected) class TestReadMagic(unittest.TestCase): def test_read_magic(self): prefix = six.b('\x93DARRY') prefix_len = 8 fp = six.BytesIO(six.b('\x93DARRY\x03\x02')) major, minor = fmt.read_magic(fp, prefix=prefix, prefix_len=prefix_len) expected = (3, 2) self.assertEqual((major, minor), expected)
b75e3646ccd1b61868a47017f14f25960e52578c
bot/action/standard/info/action.py
bot/action/standard/info/action.py
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message))
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class UserInfoAction(Action): def process(self, event): message = event.message replied_message = message.reply_to_message if replied_message is None: user = message.from_ else: user = replied_message.from_ formatter = UserInfoFormatter(self.api, user, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message))
Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply
Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class UserInfoAction(Action): def process(self, event): message = event.message replied_message = message.reply_to_message if replied_message is None: user = message.from_ else: user = replied_message.from_ formatter = UserInfoFormatter(self.api, user, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message))
<commit_before>from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) <commit_msg>Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply<commit_after>
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class UserInfoAction(Action): def process(self, event): message = event.message replied_message = message.reply_to_message if replied_message is None: user = message.from_ else: user = replied_message.from_ formatter = UserInfoFormatter(self.api, user, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message))
from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no replyfrom bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class UserInfoAction(Action): def process(self, event): message = event.message replied_message = message.reply_to_message if replied_message is None: user = message.from_ else: user = replied_message.from_ formatter = UserInfoFormatter(self.api, user, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message))
<commit_before>from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) <commit_msg>Create UserInfoAction that shows the info of the user which the message replies to, or the current user if there is no reply<commit_after>from bot.action.core.action import Action from bot.action.standard.info.formatter.chat import ChatInfoFormatter from bot.action.standard.info.formatter.user import UserInfoFormatter class MeInfoAction(Action): def process(self, event): formatter = UserInfoFormatter(self.api, event.message.from_, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class UserInfoAction(Action): def process(self, event): message = event.message replied_message = message.reply_to_message if replied_message is None: user = message.from_ else: user = replied_message.from_ formatter = UserInfoFormatter(self.api, user, event.chat) formatter.format(member_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message)) class ChatInfoAction(Action): def process(self, event): formatter = ChatInfoFormatter(self.api, event.chat, self.cache.bot_info, event.message.from_) formatter.format(full_info=True) response = formatter.get_formatted() self.api.send_message(response.build_message().to_chat_replying(event.message))
cd79c8054fc30525628046b34649572d297e13b1
pages/tests/__init__.py
pages/tests/__init__.py
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase #from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite
Test fail because of an import
Test fail because of an import
Python
bsd-3-clause
batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,pombredanne/django-page-cms-1,akaihola/django-page-cms,akaihola/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite Test fail because of an import
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase #from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite
<commit_before>"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite <commit_msg>Test fail because of an import<commit_after>
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase #from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite
"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite Test fail because of an import"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase #from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite
<commit_before>"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite <commit_msg>Test fail because of an import<commit_after>"""Django page CMS test suite module""" import unittest from pages.tests.test_functionnal import FunctionnalTestCase from pages.tests.test_unit import UnitTestCase from pages.tests.test_regression import RegressionTestCase #from pages.tests.test_pages_link import LinkTestCase from pages.tests.test_auto_render import AutoRenderTestCase def suite(): suite = unittest.TestSuite() from pages import settings if not settings.PAGE_ENABLE_TESTS: return suite suite.addTest(unittest.makeSuite(UnitTestCase)) suite.addTest(unittest.makeSuite(RegressionTestCase)) # suite.addTest(unittest.makeSuite(LinkTestCase)) suite.addTest(unittest.makeSuite(AutoRenderTestCase)) # being the slower test I run it at the end suite.addTest(unittest.makeSuite(FunctionnalTestCase)) return suite
a0f030cd03d28d97924a3277722d7a51cf3a3e92
cms/test_utils/project/extensionapp/models.py
cms/test_utils/project/extensionapp/models.py
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
Update extension app to include a M2M
Update extension app to include a M2M
Python
bsd-3-clause
kk9599/django-cms,jrclaramunt/django-cms,farhaadila/django-cms,FinalAngel/django-cms,leture/django-cms,yakky/django-cms,wuzhihui1123/django-cms,czpython/django-cms,jproffitt/django-cms,astagi/django-cms,DylannCordel/django-cms,evildmp/django-cms,jrclaramunt/django-cms,SachaMPS/django-cms,netzkolchose/django-cms,donce/django-cms,bittner/django-cms,jeffreylu9/django-cms,cyberintruder/django-cms,takeshineshiro/django-cms,Vegasvikk/django-cms,nostalgiaz/django-cms,kk9599/django-cms,rryan/django-cms,rscnt/django-cms,SmithsonianEnterprises/django-cms,jsma/django-cms,sephii/django-cms,selecsosi/django-cms,jsma/django-cms,SmithsonianEnterprises/django-cms,donce/django-cms,sznekol/django-cms,robmagee/django-cms,rsalmaso/django-cms,Livefyre/django-cms,divio/django-cms,owers19856/django-cms,isotoma/django-cms,intip/django-cms,qnub/django-cms,divio/django-cms,farhaadila/django-cms,iddqd1/django-cms,josjevv/django-cms,stefanfoulis/django-cms,farhaadila/django-cms,SofiaReis/django-cms,wuzhihui1123/django-cms,owers19856/django-cms,MagicSolutions/django-cms,jproffitt/django-cms,FinalAngel/django-cms,benzkji/django-cms,360youlun/django-cms,bittner/django-cms,netzkolchose/django-cms,jeffreylu9/django-cms,vstoykov/django-cms,stefanw/django-cms,jeffreylu9/django-cms,chkir/django-cms,nimbis/django-cms,vxsx/django-cms,selecsosi/django-cms,chkir/django-cms,qnub/django-cms,Jaccorot/django-cms,evildmp/django-cms,bittner/django-cms,wuzhihui1123/django-cms,iddqd1/django-cms,datakortet/django-cms,Vegasvikk/django-cms,benzkji/django-cms,wyg3958/django-cms,andyzsf/django-cms,MagicSolutions/django-cms,vstoykov/django-cms,intip/django-cms,intip/django-cms,memnonila/django-cms,takeshineshiro/django-cms,philippze/django-cms,vxsx/django-cms,jproffitt/django-cms,Livefyre/django-cms,SachaMPS/django-cms,stefanfoulis/django-cms,rryan/django-cms,AlexProfi/django-cms,petecummings/django-cms,vxsx/django-cms,rscnt/django-cms,dhorelik/django-cms,rsalmaso/django-cms,Vegasvikk/django-cms,liuyisiyisi/django-cms,youprofit/django-cms,wyg3958/django-cms,FinalAngel/django-cms,sznekol/django-cms,360youlun/django-cms,jrief/django-cms,andyzsf/django-cms,stefanw/django-cms,nostalgiaz/django-cms,selecsosi/django-cms,jsma/django-cms,donce/django-cms,360youlun/django-cms,rryan/django-cms,benzkji/django-cms,petecummings/django-cms,memnonila/django-cms,DylannCordel/django-cms,intgr/django-cms,Jaccorot/django-cms,rscnt/django-cms,frnhr/django-cms,astagi/django-cms,rsalmaso/django-cms,irudayarajisawa/django-cms,andyzsf/django-cms,chmberl/django-cms,saintbird/django-cms,evildmp/django-cms,frnhr/django-cms,MagicSolutions/django-cms,evildmp/django-cms,mkoistinen/django-cms,liuyisiyisi/django-cms,datakortet/django-cms,jeffreylu9/django-cms,intip/django-cms,vad/django-cms,isotoma/django-cms,divio/django-cms,mkoistinen/django-cms,intgr/django-cms,stefanw/django-cms,AlexProfi/django-cms,rryan/django-cms,stefanfoulis/django-cms,chmberl/django-cms,dhorelik/django-cms,nimbis/django-cms,mkoistinen/django-cms,Livefyre/django-cms,jrclaramunt/django-cms,saintbird/django-cms,yakky/django-cms,datakortet/django-cms,irudayarajisawa/django-cms,vstoykov/django-cms,jsma/django-cms,irudayarajisawa/django-cms,astagi/django-cms,FinalAngel/django-cms,wyg3958/django-cms,sephii/django-cms,kk9599/django-cms,saintbird/django-cms,divio/django-cms,chmberl/django-cms,josjevv/django-cms,intgr/django-cms,jrief/django-cms,wuzhihui1123/django-cms,webu/django-cms,frnhr/django-cms,sznekol/django-cms,SofiaReis/django-cms,philippze/django-cms,czpython/django-cms,frnhr/django-cms,vxsx/django-cms,cyberintruder/django-cms,cyberintruder/django-cms,rsalmaso/django-cms,timgraham/django-cms,yakky/django-cms,isotoma/django-cms,benzkji/django-cms,Livefyre/django-cms,nimbis/django-cms,AlexProfi/django-cms,robmagee/django-cms,jrief/django-cms,ScholzVolkmer/django-cms,robmagee/django-cms,webu/django-cms,netzkolchose/django-cms,intgr/django-cms,keimlink/django-cms,memnonila/django-cms,timgraham/django-cms,yakky/django-cms,datakortet/django-cms,mkoistinen/django-cms,philippze/django-cms,youprofit/django-cms,SmithsonianEnterprises/django-cms,SofiaReis/django-cms,chkir/django-cms,vad/django-cms,ScholzVolkmer/django-cms,takeshineshiro/django-cms,DylannCordel/django-cms,jrief/django-cms,liuyisiyisi/django-cms,stefanfoulis/django-cms,czpython/django-cms,owers19856/django-cms,petecummings/django-cms,keimlink/django-cms,nimbis/django-cms,ScholzVolkmer/django-cms,selecsosi/django-cms,leture/django-cms,jproffitt/django-cms,iddqd1/django-cms,keimlink/django-cms,qnub/django-cms,timgraham/django-cms,andyzsf/django-cms,SachaMPS/django-cms,czpython/django-cms,vad/django-cms,dhorelik/django-cms,vad/django-cms,youprofit/django-cms,netzkolchose/django-cms,Jaccorot/django-cms,sephii/django-cms,bittner/django-cms,isotoma/django-cms,josjevv/django-cms,nostalgiaz/django-cms,webu/django-cms,stefanw/django-cms,nostalgiaz/django-cms,sephii/django-cms,leture/django-cms
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension) Update extension app to include a M2M
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
<commit_before># -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension) <commit_msg>Update extension app to include a M2M<commit_after>
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension) Update extension app to include a M2M# -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
<commit_before># -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension) <commit_msg>Update extension app to include a M2M<commit_after># -*- coding: utf-8 -*- from cms.extensions import PageExtension, TitleExtension from cms.extensions.extension_pool import extension_pool from django.contrib.auth.models import User from django.db import models class MyPageExtension(PageExtension): extra = models.CharField(blank=True, default='', max_length=255) favorite_users = models.ManyToManyField(User, blank=True, null=True) def copy_relations(self, other, language): for favorite_user in other.favorite_users.all(): favorite_user.pk = None favorite_user.mypageextension = self favorite_user.save() extension_pool.register(MyPageExtension) class MyTitleExtension(TitleExtension): extra_title = models.CharField(blank=True, default='', max_length=255) extension_pool.register(MyTitleExtension)
f0d3ef7e6b98aa37f14a077a922e39121b7ab6a4
sipa.py
sipa.py
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ from sipa import app, logger from sipa.base import init_app init_app(app) logger.info('Starting sipa...') logger.warning('Running in Debug mode') if __name__ == "__main__": app.run(debug=True, host="0.0.0.0")
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ import argparse from sipa import app, logger from sipa.base import init_app init_app(app) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Sipa launcher") parser.add_argument("--debug", action="store_true", help="run Sipa in debug mode") parser.add_argument("--exposed", action="store_const", const='0.0.0.0', dest='host', help="expose Sipa on the network") parser.add_argument("-p", "--port", action="store", help="tcp port to use", type=int, default=5000) args = parser.parse_args() logger.info('Starting sipa...') if args.debug: logger.warning('Running in Debug mode') app.run(debug=args.debug, host=args.host, port=args.port)
Use argparse to enable some options
Use argparse to enable some options Fix #51 Now, `--debug`, `--port/-p` and `--exposed` are available. Note that most probably you will have to add `--exposed` to the command you use if you run sipa directly in something like a docker container.
Python
mit
MarauderXtreme/sipa,lukasjuhrich/sipa,agdsn/sipa,fgrsnau/sipa,fgrsnau/sipa,fgrsnau/sipa,agdsn/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa,agdsn/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa,agdsn/sipa,lukasjuhrich/sipa
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ from sipa import app, logger from sipa.base import init_app init_app(app) logger.info('Starting sipa...') logger.warning('Running in Debug mode') if __name__ == "__main__": app.run(debug=True, host="0.0.0.0") Use argparse to enable some options Fix #51 Now, `--debug`, `--port/-p` and `--exposed` are available. Note that most probably you will have to add `--exposed` to the command you use if you run sipa directly in something like a docker container.
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ import argparse from sipa import app, logger from sipa.base import init_app init_app(app) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Sipa launcher") parser.add_argument("--debug", action="store_true", help="run Sipa in debug mode") parser.add_argument("--exposed", action="store_const", const='0.0.0.0', dest='host', help="expose Sipa on the network") parser.add_argument("-p", "--port", action="store", help="tcp port to use", type=int, default=5000) args = parser.parse_args() logger.info('Starting sipa...') if args.debug: logger.warning('Running in Debug mode') app.run(debug=args.debug, host=args.host, port=args.port)
<commit_before># -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ from sipa import app, logger from sipa.base import init_app init_app(app) logger.info('Starting sipa...') logger.warning('Running in Debug mode') if __name__ == "__main__": app.run(debug=True, host="0.0.0.0") <commit_msg>Use argparse to enable some options Fix #51 Now, `--debug`, `--port/-p` and `--exposed` are available. Note that most probably you will have to add `--exposed` to the command you use if you run sipa directly in something like a docker container.<commit_after>
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ import argparse from sipa import app, logger from sipa.base import init_app init_app(app) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Sipa launcher") parser.add_argument("--debug", action="store_true", help="run Sipa in debug mode") parser.add_argument("--exposed", action="store_const", const='0.0.0.0', dest='host', help="expose Sipa on the network") parser.add_argument("-p", "--port", action="store", help="tcp port to use", type=int, default=5000) args = parser.parse_args() logger.info('Starting sipa...') if args.debug: logger.warning('Running in Debug mode') app.run(debug=args.debug, host=args.host, port=args.port)
# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ from sipa import app, logger from sipa.base import init_app init_app(app) logger.info('Starting sipa...') logger.warning('Running in Debug mode') if __name__ == "__main__": app.run(debug=True, host="0.0.0.0") Use argparse to enable some options Fix #51 Now, `--debug`, `--port/-p` and `--exposed` are available. Note that most probably you will have to add `--exposed` to the command you use if you run sipa directly in something like a docker container.# -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ import argparse from sipa import app, logger from sipa.base import init_app init_app(app) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Sipa launcher") parser.add_argument("--debug", action="store_true", help="run Sipa in debug mode") parser.add_argument("--exposed", action="store_const", const='0.0.0.0', dest='host', help="expose Sipa on the network") parser.add_argument("-p", "--port", action="store", help="tcp port to use", type=int, default=5000) args = parser.parse_args() logger.info('Starting sipa...') if args.debug: logger.warning('Running in Debug mode') app.run(debug=args.debug, host=args.host, port=args.port)
<commit_before># -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ from sipa import app, logger from sipa.base import init_app init_app(app) logger.info('Starting sipa...') logger.warning('Running in Debug mode') if __name__ == "__main__": app.run(debug=True, host="0.0.0.0") <commit_msg>Use argparse to enable some options Fix #51 Now, `--debug`, `--port/-p` and `--exposed` are available. Note that most probably you will have to add `--exposed` to the command you use if you run sipa directly in something like a docker container.<commit_after># -*- coding: utf-8 -*- """ sipa.py ~~~~~~~~~~~~~~ This file shall be used to start the Flask app. Specific things are handled in the `sipa` package. """ import argparse from sipa import app, logger from sipa.base import init_app init_app(app) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Sipa launcher") parser.add_argument("--debug", action="store_true", help="run Sipa in debug mode") parser.add_argument("--exposed", action="store_const", const='0.0.0.0', dest='host', help="expose Sipa on the network") parser.add_argument("-p", "--port", action="store", help="tcp port to use", type=int, default=5000) args = parser.parse_args() logger.info('Starting sipa...') if args.debug: logger.warning('Running in Debug mode') app.run(debug=args.debug, host=args.host, port=args.port)
f14e3dfe844203946a33b9b3329e569d7114d7d6
demo.py
demo.py
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(request): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True)
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(_): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True)
Rename unused but needed variable
Rename unused but needed variable
Python
mit
Mause/resumable
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(request): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True) Rename unused but needed variable
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(_): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True)
<commit_before>#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(request): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True) <commit_msg>Rename unused but needed variable<commit_after>
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(_): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True)
#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(request): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True) Rename unused but needed variable#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(_): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True)
<commit_before>#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(request): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True) <commit_msg>Rename unused but needed variable<commit_after>#!/usr/bin/env python3 from flask import Flask, redirect, request from resumable import rebuild, split app = Flask(__name__) # for the purposes of this demo, we will explicitly pass request # and response (this is not needed in flask) @rebuild def controller(_): page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/welcomed" method=post> <input name="name"/> <button type=submit>Submit</button> </form> ''' response = value(page, 'welcomed') page = ''' <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <form action="/c/my_name" method=post> <label> Hi, {}, my name is <input name="my_name"/> </label> <button type=submit>Submit</button> </form> '''.format(response.form['name']) response = value(page, 'my_name') return value('Sweet, my name is {}!'.format(response.form['my_name'])) @app.route('/c/<name>', methods=['POST', 'GET']) def router(name): return controller[name](request) @app.route('/') def index(): return redirect('/c/controller') if __name__ == '__main__': app.run(debug=True)
eef768a538c82629073b360618d8b39bcbf4c474
tests/dojo_test.py
tests/dojo_test.py
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): pass
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): initial_room_count = len(self.dojo.all_people) room1 = self.dojo.create_room("office", "Blue") room1 = self.dojo.create_room("office", "Blue") new_room_count = len(self.dojo.all_people) self.assertEqual(new_room_count - initial_room_count, 0)
Implement test for duplicate rooms
Implement test for duplicate rooms
Python
mit
EdwinKato/Space-Allocator,EdwinKato/Space-Allocator
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): passImplement test for duplicate rooms
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): initial_room_count = len(self.dojo.all_people) room1 = self.dojo.create_room("office", "Blue") room1 = self.dojo.create_room("office", "Blue") new_room_count = len(self.dojo.all_people) self.assertEqual(new_room_count - initial_room_count, 0)
<commit_before>import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): pass<commit_msg>Implement test for duplicate rooms<commit_after>
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): initial_room_count = len(self.dojo.all_people) room1 = self.dojo.create_room("office", "Blue") room1 = self.dojo.create_room("office", "Blue") new_room_count = len(self.dojo.all_people) self.assertEqual(new_room_count - initial_room_count, 0)
import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): passImplement test for duplicate roomsimport unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): initial_room_count = len(self.dojo.all_people) room1 = self.dojo.create_room("office", "Blue") room1 = self.dojo.create_room("office", "Blue") new_room_count = len(self.dojo.all_people) self.assertEqual(new_room_count - initial_room_count, 0)
<commit_before>import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): pass<commit_msg>Implement test for duplicate rooms<commit_after>import unittest from src.dojo import Dojo class TestCreateRoom (unittest.TestCase): def setUp(self): self.dojo = Dojo() self.test_office = self.dojo.create_room("office", "test") self.test_living_space = self.dojo.create_room("living_space", "test living space") def test_create_room_successfully(self): initial_room_count = len(self.dojo.all_rooms) blue_office = self.dojo.create_room("office", "Blue") self.assertTrue(blue_office) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 1) def test_create_rooms_successfully(self): initial_room_count = len(self.dojo.all_rooms) offices = self.dojo.create_room("office", "Blue", "Black", "Brown") self.assertTrue(offices) new_room_count = len(self.dojo.all_rooms) self.assertEqual(new_room_count - initial_room_count, 3) def test_addition_of_duplicate_room_names(self): initial_room_count = len(self.dojo.all_people) room1 = self.dojo.create_room("office", "Blue") room1 = self.dojo.create_room("office", "Blue") new_room_count = len(self.dojo.all_people) self.assertEqual(new_room_count - initial_room_count, 0)
4e4ff0e235600b1b06bf607004538bd5ff6e5d30
listener.py
listener.py
import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler)
import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
Fix naming of Handler to Reciever
Fix naming of Handler to Reciever
Python
mit
adamcik/pycat,adamcik/pycat
import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler) Fix naming of Handler to Reciever
import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
<commit_before>import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler) <commit_msg>Fix naming of Handler to Reciever<commit_after>
import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler) Fix naming of Handler to Recieverimport asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
<commit_before>import asynchat import asyncore import socket class Handler(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Handler(self, self.accept()) def add(self, handler): self.handlers.append(handler) <commit_msg>Fix naming of Handler to Reciever<commit_after>import asynchat import asyncore import socket class Reciver(asynchat.async_chat): def __init__(self, server, (conn, addr)): asynchat.async_chat.__init__(self, conn) self.set_terminator('\n') self.server = server self.buffer = '' def collect_incoming_data(self, data): self.buffer += data def found_terminator(self): line, self.buffer = self.buffer, '' for handler in self.server.handlers: handler(line) class Listener(asyncore.dispatcher): def __init__(self, port=12345): asyncore.dispatcher.__init__(self) self.port = port self.handlers = [] self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(('', self.port)) self.listen(5) def handle_accept(self): Reciver(self, self.accept()) def add(self, handler): self.handlers.append(handler)
eeb23b7fde3f728355efcc446912b7c8357c0c08
util.py
util.py
def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
Use sys in error cases.
Use sys in error cases.
Python
mit
lightcrest/kahu-api-demo
def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1) Use sys in error cases.
import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
<commit_before>def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1) <commit_msg>Use sys in error cases.<commit_after>
import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1) Use sys in error cases.import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
<commit_before>def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1) <commit_msg>Use sys in error cases.<commit_after>import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
0c6babde080f14c09d4a93d3a6138c36728c4651
contrib/dns_dump_hex_to_text.py
contrib/dns_dump_hex_to_text.py
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print (response.to_text())
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print(response.to_text())
Remove white space between print and ()
Remove white space between print and () TrivialFix Change-Id: I5219e319e9d7e5cc8307e45c60e1e2d2d25d9d5c
Python
apache-2.0
openstack/designate,openstack/designate,openstack/designate
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print (response.to_text()) Remove white space between print and () TrivialFix Change-Id: I5219e319e9d7e5cc8307e45c60e1e2d2d25d9d5c
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print(response.to_text())
<commit_before>#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print (response.to_text()) <commit_msg>Remove white space between print and () TrivialFix Change-Id: I5219e319e9d7e5cc8307e45c60e1e2d2d25d9d5c<commit_after>
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print(response.to_text())
#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print (response.to_text()) Remove white space between print and () TrivialFix Change-Id: I5219e319e9d7e5cc8307e45c60e1e2d2d25d9d5c#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print(response.to_text())
<commit_before>#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print (response.to_text()) <commit_msg>Remove white space between print and () TrivialFix Change-Id: I5219e319e9d7e5cc8307e45c60e1e2d2d25d9d5c<commit_after>#!/usr/bin/env python # Copyright 2014 Hewlett-Packard Development Company, L.P. # # Author: Kiall Mac Innes <kiall@hp.com> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import binascii import sys import dns import dns.message import dns.rdatatype unhexed = binascii.unhexlify(sys.argv[1]) response = dns.message.from_wire(unhexed) print(response.to_text())
78bebaa2902636e33409591675b1bede6c359aad
telepyth/__init__.py
telepyth/__init__.py
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive if is_interactive(): from telepyth.magics import TelePythMagics
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive TelepythClient = TelePythClient # make alias to origin definition if is_interactive(): from telepyth.magics import TelePythMagics
Add alias to TelePythClient which will be deprecated in the future.
Add alias to TelePythClient which will be deprecated in the future.
Python
mit
daskol/telepyth,daskol/telepyth
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive if is_interactive(): from telepyth.magics import TelePythMagics Add alias to TelePythClient which will be deprecated in the future.
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive TelepythClient = TelePythClient # make alias to origin definition if is_interactive(): from telepyth.magics import TelePythMagics
<commit_before># encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive if is_interactive(): from telepyth.magics import TelePythMagics <commit_msg>Add alias to TelePythClient which will be deprecated in the future.<commit_after>
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive TelepythClient = TelePythClient # make alias to origin definition if is_interactive(): from telepyth.magics import TelePythMagics
# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive if is_interactive(): from telepyth.magics import TelePythMagics Add alias to TelePythClient which will be deprecated in the future.# encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive TelepythClient = TelePythClient # make alias to origin definition if is_interactive(): from telepyth.magics import TelePythMagics
<commit_before># encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive if is_interactive(): from telepyth.magics import TelePythMagics <commit_msg>Add alias to TelePythClient which will be deprecated in the future.<commit_after># encoding: utf8 # __init__.py from telepyth.client import TelePythClient from telepyth.utils import is_interactive TelepythClient = TelePythClient # make alias to origin definition if is_interactive(): from telepyth.magics import TelePythMagics
fd4c62b157cfb4f5814e01640cd5d29837092cfc
pronto/parsers/base.py
pronto/parsers/base.py
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref elif os.path.exists(f"{ref}.obo"): url = f"{ref}.obo" elif os.path.exists(f"{ref}.json"): url = f"{ref}.json" else: url = f"http://purl.obolibrary.org/obo/{ref}.obo" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): basepath = os.path.dirname(self.ont.path or "") if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref else: for ext in ["", ".obo", ".json", ".owl"]: if os.path.exists(os.path.join(basepath, f"{ref}{ext}")): url = os.path.join(basepath, f"{ref}{ext}") break else: if not os.path.splitext(ref)[1]: ref = f"{ref}.obo" url = f"http://purl.obolibrary.org/obo/{ref}" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
Improve local import detection in `BaseParser.process_imports`
Improve local import detection in `BaseParser.process_imports`
Python
mit
althonos/pronto
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref elif os.path.exists(f"{ref}.obo"): url = f"{ref}.obo" elif os.path.exists(f"{ref}.json"): url = f"{ref}.json" else: url = f"http://purl.obolibrary.org/obo/{ref}.obo" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, ) Improve local import detection in `BaseParser.process_imports`
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): basepath = os.path.dirname(self.ont.path or "") if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref else: for ext in ["", ".obo", ".json", ".owl"]: if os.path.exists(os.path.join(basepath, f"{ref}{ext}")): url = os.path.join(basepath, f"{ref}{ext}") break else: if not os.path.splitext(ref)[1]: ref = f"{ref}.obo" url = f"http://purl.obolibrary.org/obo/{ref}" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
<commit_before>import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref elif os.path.exists(f"{ref}.obo"): url = f"{ref}.obo" elif os.path.exists(f"{ref}.json"): url = f"{ref}.json" else: url = f"http://purl.obolibrary.org/obo/{ref}.obo" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, ) <commit_msg>Improve local import detection in `BaseParser.process_imports`<commit_after>
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): basepath = os.path.dirname(self.ont.path or "") if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref else: for ext in ["", ".obo", ".json", ".owl"]: if os.path.exists(os.path.join(basepath, f"{ref}{ext}")): url = os.path.join(basepath, f"{ref}{ext}") break else: if not os.path.splitext(ref)[1]: ref = f"{ref}.obo" url = f"http://purl.obolibrary.org/obo/{ref}" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref elif os.path.exists(f"{ref}.obo"): url = f"{ref}.obo" elif os.path.exists(f"{ref}.json"): url = f"{ref}.json" else: url = f"http://purl.obolibrary.org/obo/{ref}.obo" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, ) Improve local import detection in `BaseParser.process_imports`import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): basepath = os.path.dirname(self.ont.path or "") if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref else: for ext in ["", ".obo", ".json", ".owl"]: if os.path.exists(os.path.join(basepath, f"{ref}{ext}")): url = os.path.join(basepath, f"{ref}{ext}") break else: if not os.path.splitext(ref)[1]: ref = f"{ref}.obo" url = f"http://purl.obolibrary.org/obo/{ref}" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
<commit_before>import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref elif os.path.exists(f"{ref}.obo"): url = f"{ref}.obo" elif os.path.exists(f"{ref}.json"): url = f"{ref}.json" else: url = f"http://purl.obolibrary.org/obo/{ref}.obo" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, ) <commit_msg>Improve local import detection in `BaseParser.process_imports`<commit_after>import abc import os import typing import urllib.parse if typing.TYPE_CHECKING: from ..ontology import Ontology class BaseParser(abc.ABC): def __init__(self, ont: 'Ontology'): self.ont = ont @classmethod @abc.abstractmethod def can_parse(cls, path: str, buffer: bytes): """Return `True` if this parser type can parse the given handle. """ return NotImplemented @abc.abstractmethod def parse_from(self, handle: typing.BinaryIO): return NotImplemented def process_imports(self): basepath = os.path.dirname(self.ont.path or "") if self.ont.import_depth != 0: for ref in self.ont.metadata.imports: s = urllib.parse.urlparse(ref).scheme if s in {"ftp", "http", "https"} or os.path.exists(ref): url = ref else: for ext in ["", ".obo", ".json", ".owl"]: if os.path.exists(os.path.join(basepath, f"{ref}{ext}")): url = os.path.join(basepath, f"{ref}{ext}") break else: if not os.path.splitext(ref)[1]: ref = f"{ref}.obo" url = f"http://purl.obolibrary.org/obo/{ref}" self.ont.imports[ref] = type(self.ont)( url, max(self.ont.import_depth-1, 0), self.ont.timeout, )
f78be67a4efec7f343f51418410e9d73b358df19
tatooine.py
tatooine.py
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'] ServicePort = ConsulRetObj[0]['ServicePort'] return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'].decode("utf-8") ServicePort = ConsulRetObj[0]['ServicePort'].decode("utf-8") return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
Convert binary string to UTF-8
Convert binary string to UTF-8
Python
mit
skale-5/tatooine
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'] ServicePort = ConsulRetObj[0]['ServicePort'] return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0') Convert binary string to UTF-8
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'].decode("utf-8") ServicePort = ConsulRetObj[0]['ServicePort'].decode("utf-8") return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
<commit_before>from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'] ServicePort = ConsulRetObj[0]['ServicePort'] return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0') <commit_msg>Convert binary string to UTF-8<commit_after>
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'].decode("utf-8") ServicePort = ConsulRetObj[0]['ServicePort'].decode("utf-8") return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'] ServicePort = ConsulRetObj[0]['ServicePort'] return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0') Convert binary string to UTF-8from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'].decode("utf-8") ServicePort = ConsulRetObj[0]['ServicePort'].decode("utf-8") return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
<commit_before>from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'] ServicePort = ConsulRetObj[0]['ServicePort'] return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0') <commit_msg>Convert binary string to UTF-8<commit_after>from flask import Flask import consul import socket import pprint import redis # Consul key CONSUL_REDIS_KEY = "redis" app = Flask(__name__) def GetRedisFromConsul(): MyConsul = consul.Consul(host='172.17.42.1', port=8500) Index, ConsulRetObj = MyConsul.catalog.service(CONSUL_REDIS_KEY) pprint.pprint(ConsulRetObj) ServiceAddress = ConsulRetObj[0]['Address'].decode("utf-8") ServicePort = ConsulRetObj[0]['ServicePort'].decode("utf-8") return ServiceAddress, ServicePort def GetCounterFromRedis(PServer, PPort): Myredis = redis.StrictRedis(host=PServer, port=PPort, db=0) Myredis.incr("value") return Myredis.get('value') @app.route("/") def hello(): try: RedisServiceAddress, RedisServicePort = GetRedisFromConsul() Output = "Redis Server : %s:%s - counter value : %s" % (RedisServiceAddress,RedisServicePort, GetCounterFromRedis(RedisServiceAddress , RedisServicePort)) except Exception as e: return("Error : %s" % str(e)) return Output if __name__ == "__main__": app.run(host='0.0.0.0')
5b554752aaabd59b8248f9eecfc03458dd9f07d0
coding/admin.py
coding/admin.py
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") date_hierarchy = "action_time" admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
Add date drill down to coding assignment activity list
Add date drill down to coding assignment activity list
Python
mit
inducer/codery,inducer/codery
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin) Add date drill down to coding assignment activity list
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") date_hierarchy = "action_time" admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
<commit_before>from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin) <commit_msg>Add date drill down to coding assignment activity list<commit_after>
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") date_hierarchy = "action_time" admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin) Add date drill down to coding assignment activity listfrom django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") date_hierarchy = "action_time" admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
<commit_before>from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin) <commit_msg>Add date drill down to coding assignment activity list<commit_after>from django.contrib import admin from coding.models import ( Sample, AssignmentTag, CodingAssignment, CodingAssignmentActivity) class SampleAdmin(admin.ModelAdmin): filter_horizontal = ("pieces",) admin.site.register(Sample, SampleAdmin) class AssignmentTagAdmin(admin.ModelAdmin): list_filter = ("study",) list_display = ("name", "study",) admin.site.register(AssignmentTag, AssignmentTagAdmin) class CodingAssignmentAdmin(admin.ModelAdmin): list_filter = ("coder", "tags", "piece__tags", "sample", "state") list_display = ( "piece", "coder", "sample", "state", "creation_time") search_fields = ("piece__id", "piece__title", "sample__name") filter_horizontal = ("tags",) admin.site.register(CodingAssignment, CodingAssignmentAdmin) class CodingAssignmentActivityAdmin(admin.ModelAdmin): search_fields = ( "assignment__piece__id", "assignment__piece__title", "actor__name", ) list_display = ("assignment", "action_time", "actor", "action", "state") list_filter = ("actor", "action", "state") date_hierarchy = "action_time" admin.site.register(CodingAssignmentActivity, CodingAssignmentActivityAdmin)
72e5b32a0306ad608b32eaaa4817b0e5b5ef3c8d
project/asylum/utils.py
project/asylum/utils.py
# -*- coding: utf-8 -*- import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret
# -*- coding: utf-8 -*- import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat()
Add helper for iterating over months and move date proxy here
Add helper for iterating over months and move date proxy here the proxy is now needed by two commands
Python
mit
rambo/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,jautero/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,rambo/asylum,hacklab-fi/asylum,hacklab-fi/asylum,jautero/asylum,rambo/asylum,jautero/asylum,HelsinkiHacklab/asylum,HelsinkiHacklab/asylum
# -*- coding: utf-8 -*- import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret Add helper for iterating over months and move date proxy here the proxy is now needed by two commands
# -*- coding: utf-8 -*- import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat()
<commit_before># -*- coding: utf-8 -*- import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret <commit_msg>Add helper for iterating over months and move date proxy here the proxy is now needed by two commands<commit_after>
# -*- coding: utf-8 -*- import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat()
# -*- coding: utf-8 -*- import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret Add helper for iterating over months and move date proxy here the proxy is now needed by two commands# -*- coding: utf-8 -*- import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat()
<commit_before># -*- coding: utf-8 -*- import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret <commit_msg>Add helper for iterating over months and move date proxy here the proxy is now needed by two commands<commit_after># -*- coding: utf-8 -*- import calendar import datetime import importlib import random from django.conf import settings def get_handler_instance(setting): """Gets instance of class defined in the given setting""" try: setting_value = getattr(settings, setting) except AttributeError: return None if not setting_value: return None module_name, class_name = setting_value.rsplit(".", 1) HandlerClass = getattr(importlib.import_module(module_name), class_name) instance = HandlerClass() return instance def get_random_objects(klass, num=1): ret = [] count = klass.objects.all().count() for x in range(num): random_index = random.randint(0, count - 1) ret.append(klass.objects.all()[random_index]) return ret # Adapted from http://www.ianlewis.org/en/python-date-range-iterator def months(from_date=None, to_date=None): from_date = from_date or datetime.datetime.now().date() while to_date is None or from_date <= to_date: yield from_date from_date = from_date + datetime.timedelta(days=calendar.monthrange(from_date.year, from_date.month)[1]) return def datetime_proxy(delta=datetime.timedelta(days=1)): """Used by management commands needing datetime X days ago""" now_yesterday = datetime.datetime.now() - delta start_yesterday = datetime.datetime.combine(now_yesterday.date(), datetime.datetime.min.time()) return start_yesterday.isoformat()
18c3ec079b5e805f6d0115df55076707bcef48c6
pyconde/core/models.py
pyconde/core/models.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: # register a signal do update permissions every migration. # This is based on app django_extensions update_permissions command from south.signals import post_migrate def update_permissions_after_migration(app,**kwargs): """ Update app permission just after every migration. This is based on app django_extensions update_permissions management command. """ from django.conf import settings from django.db.models import get_app, get_models from django.contrib.auth.management import create_permissions create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0) post_migrate.connect(update_permissions_after_migration) except ImportError: pass
Add South post_migrate signal to work with permission changes
Add South post_migrate signal to work with permission changes
Python
bsd-3-clause
EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep,pysv/djep
Add South post_migrate signal to work with permission changes
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: # register a signal do update permissions every migration. # This is based on app django_extensions update_permissions command from south.signals import post_migrate def update_permissions_after_migration(app,**kwargs): """ Update app permission just after every migration. This is based on app django_extensions update_permissions management command. """ from django.conf import settings from django.db.models import get_app, get_models from django.contrib.auth.management import create_permissions create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0) post_migrate.connect(update_permissions_after_migration) except ImportError: pass
<commit_before><commit_msg>Add South post_migrate signal to work with permission changes<commit_after>
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: # register a signal do update permissions every migration. # This is based on app django_extensions update_permissions command from south.signals import post_migrate def update_permissions_after_migration(app,**kwargs): """ Update app permission just after every migration. This is based on app django_extensions update_permissions management command. """ from django.conf import settings from django.db.models import get_app, get_models from django.contrib.auth.management import create_permissions create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0) post_migrate.connect(update_permissions_after_migration) except ImportError: pass
Add South post_migrate signal to work with permission changes# -*- coding: utf-8 -*- from __future__ import unicode_literals try: # register a signal do update permissions every migration. # This is based on app django_extensions update_permissions command from south.signals import post_migrate def update_permissions_after_migration(app,**kwargs): """ Update app permission just after every migration. This is based on app django_extensions update_permissions management command. """ from django.conf import settings from django.db.models import get_app, get_models from django.contrib.auth.management import create_permissions create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0) post_migrate.connect(update_permissions_after_migration) except ImportError: pass
<commit_before><commit_msg>Add South post_migrate signal to work with permission changes<commit_after># -*- coding: utf-8 -*- from __future__ import unicode_literals try: # register a signal do update permissions every migration. # This is based on app django_extensions update_permissions command from south.signals import post_migrate def update_permissions_after_migration(app,**kwargs): """ Update app permission just after every migration. This is based on app django_extensions update_permissions management command. """ from django.conf import settings from django.db.models import get_app, get_models from django.contrib.auth.management import create_permissions create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0) post_migrate.connect(update_permissions_after_migration) except ImportError: pass
c7d56731125bf7a67d10304ae7be47d333f1165b
akllt/common/templatetags/aklltcommontags.py
akllt/common/templatetags/aklltcommontags.py
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form))
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form))
Add additional space before inline comment.
Add additional space before inline comment.
Python
agpl-3.0
python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form)) Add additional space before inline comment.
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form))
<commit_before>from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form)) <commit_msg>Add additional space before inline comment.<commit_after>
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form))
from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form)) Add additional space before inline comment.from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form))
<commit_before>from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form)) <commit_msg>Add additional space before inline comment.<commit_after>from django import template from django.utils.safestring import mark_safe from akllt.common import formrenderer register = template.Library() # pylint: disable=invalid-name @register.simple_tag(name='formrenderer', takes_context=True) def formrenderer_filter(context, form): return mark_safe(formrenderer.render_fields(context['request'], form))
5af9f2cd214f12e2d16b696a0c62856e389b1397
test/test_doc.py
test/test_doc.py
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings): if type(mc) in (ModuleType, ClassType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings, namespace=None): name = getattr(mc, '__name__', None) if name is None: return if name in ('__builtin__', 'builtins'): return if name.startswith('_'): return if namespace: name = '%s.%s' % (namespace, name) if type(mc) in (ModuleType, ClassType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings, name) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
Improve test script, report namespaces for stuff missing docstrings
Improve test script, report namespaces for stuff missing docstrings
Python
bsd-2-clause
pressel/mpi4py,pressel/mpi4py,pressel/mpi4py,mpi4py/mpi4py,pressel/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings): if type(mc) in (ModuleType, ClassType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main() Improve test script, report namespaces for stuff missing docstrings
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings, namespace=None): name = getattr(mc, '__name__', None) if name is None: return if name in ('__builtin__', 'builtins'): return if name.startswith('_'): return if namespace: name = '%s.%s' % (namespace, name) if type(mc) in (ModuleType, ClassType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings, name) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
<commit_before>import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings): if type(mc) in (ModuleType, ClassType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main() <commit_msg>Improve test script, report namespaces for stuff missing docstrings<commit_after>
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings, namespace=None): name = getattr(mc, '__name__', None) if name is None: return if name in ('__builtin__', 'builtins'): return if name.startswith('_'): return if namespace: name = '%s.%s' % (namespace, name) if type(mc) in (ModuleType, ClassType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings, name) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings): if type(mc) in (ModuleType, ClassType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main() Improve test script, report namespaces for stuff missing docstringsimport types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings, namespace=None): name = getattr(mc, '__name__', None) if name is None: return if name in ('__builtin__', 'builtins'): return if name.startswith('_'): return if namespace: name = '%s.%s' % (namespace, name) if type(mc) in (ModuleType, ClassType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings, name) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
<commit_before>import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings): if type(mc) in (ModuleType, ClassType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): name = getattr(mc, '__name__') if name in ('__builtin__', 'builtin'): return doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main() <commit_msg>Improve test script, report namespaces for stuff missing docstrings<commit_after>import types from mpi4py import MPI import mpiunittest as unittest ModuleType = type(MPI) ClassType = type(MPI.Comm) FunctionType = type(MPI.Init) MethodDescrType = type(MPI.Comm.Get_rank) GetSetDescrType = type(MPI.Comm.rank) def getdocstr(mc, docstrings, namespace=None): name = getattr(mc, '__name__', None) if name is None: return if name in ('__builtin__', 'builtins'): return if name.startswith('_'): return if namespace: name = '%s.%s' % (namespace, name) if type(mc) in (ModuleType, ClassType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc for k, v in vars(mc).items(): getdocstr(v, docstrings, name) elif type(mc) in (FunctionType, MethodDescrType, GetSetDescrType): doc = getattr(mc, '__doc__', None) docstrings[name] = doc class TestDoc(unittest.TestCase): def testDoc(self): missing = False docs = { } getdocstr(MPI, docs) for k in docs: if not k.startswith('_'): doc = docs[k] if doc is None: print ("'%s': missing docstring" % k) missing = True else: doc = doc.strip() if not doc: print ("'%s': empty docstring" % k) missing = True self.assertFalse(missing) if __name__ == '__main__': unittest.main()
07d113e4604994bf1857b3ae7201571776b65154
etl/make_feature_tsv.py
etl/make_feature_tsv.py
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') for i in range (0, len(genes)): fout.write("{} {} {}".format(i, genes[i], gene_names[i]))
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') fout.write("index\tfeature\tfeature_name\n") for i in range (0, len(genes)): fout.write("{}\t{}\t{}\n".format(i, genes[i], gene_names[i]))
Make a tsv instead of a long string
Make a tsv instead of a long string
Python
apache-2.0
david4096/celldb
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') for i in range (0, len(genes)): fout.write("{} {} {}".format(i, genes[i], gene_names[i])) Make a tsv instead of a long string
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') fout.write("index\tfeature\tfeature_name\n") for i in range (0, len(genes)): fout.write("{}\t{}\t{}\n".format(i, genes[i], gene_names[i]))
<commit_before># Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') for i in range (0, len(genes)): fout.write("{} {} {}".format(i, genes[i], gene_names[i])) <commit_msg>Make a tsv instead of a long string<commit_after>
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') fout.write("index\tfeature\tfeature_name\n") for i in range (0, len(genes)): fout.write("{}\t{}\t{}\n".format(i, genes[i], gene_names[i]))
# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') for i in range (0, len(genes)): fout.write("{} {} {}".format(i, genes[i], gene_names[i])) Make a tsv instead of a long string# Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') fout.write("index\tfeature\tfeature_name\n") for i in range (0, len(genes)): fout.write("{}\t{}\t{}\n".format(i, genes[i], gene_names[i]))
<commit_before># Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') for i in range (0, len(genes)): fout.write("{} {} {}".format(i, genes[i], gene_names[i])) <commit_msg>Make a tsv instead of a long string<commit_after># Graciously adopted from https://github.com/ucscXena/xenaH5 # # Generates a tsv compatible for making a create table statement from a # 10xgenomics HDF5 file. # # Usage # # python maketsv.py fname 0 # # Will generate a tsv file with the 0th slice of the h5 file named # `out0.tsv`. import string, sys import h5py import numpy as np hF = h5py.File(sys.argv[1]) group = "mm10" indptr = hF[group +"/indptr"] indices = hF[group + "/indices"] data = hF[group + "/data"] genes = hF[group + "/genes"] gene_names = hF[group + "/gene_names"] barcodes = hF[group + "/barcodes"] shape = hF[group + "/shape"] rowN = shape[0] colN = shape[1] counter_indptr_size = rowN fout = open("features.tsv",'w') fout.write("index\tfeature\tfeature_name\n") for i in range (0, len(genes)): fout.write("{}\t{}\t{}\n".format(i, genes[i], gene_names[i]))
8d05eddbdc6005a649d848a1cfa68afe7bda7f47
filer/__init__.py
filer/__init__.py
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.50' # pragma: nocover
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.51' # pragma: nocover
Remove "cmp" occurences improve folder and file names listing
Remove "cmp" occurences improve folder and file names listing
Python
bsd-3-clause
pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.50' # pragma: nocover Remove "cmp" occurences improve folder and file names listing
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.51' # pragma: nocover
<commit_before>#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.50' # pragma: nocover <commit_msg>Remove "cmp" occurences improve folder and file names listing<commit_after>
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.51' # pragma: nocover
#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.50' # pragma: nocover Remove "cmp" occurences improve folder and file names listing#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.51' # pragma: nocover
<commit_before>#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.50' # pragma: nocover <commit_msg>Remove "cmp" occurences improve folder and file names listing<commit_after>#-*- coding: utf-8 -*- # version string following pep-0396 and pep-0386 __version__ = '0.9pbs.51' # pragma: nocover
37d7656019d11b3b05d59f184d72e1dd6d4ccaf7
contones/srs.py
contones/srs.py
"""Spatial reference systems""" from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
"""Spatial reference systems""" __all__ = ['SpatialReference'] from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt def __eq__(self, another): return bool(self.IsSame(another)) def __ne__(self, another): return not self.__eq__(another) @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
Add equality methods to SpatialReference
Add equality methods to SpatialReference
Python
bsd-3-clause
bkg/greenwich
"""Spatial reference systems""" from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr Add equality methods to SpatialReference
"""Spatial reference systems""" __all__ = ['SpatialReference'] from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt def __eq__(self, another): return bool(self.IsSame(another)) def __ne__(self, another): return not self.__eq__(another) @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
<commit_before>"""Spatial reference systems""" from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr <commit_msg>Add equality methods to SpatialReference<commit_after>
"""Spatial reference systems""" __all__ = ['SpatialReference'] from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt def __eq__(self, another): return bool(self.IsSame(another)) def __ne__(self, another): return not self.__eq__(another) @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
"""Spatial reference systems""" from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr Add equality methods to SpatialReference"""Spatial reference systems""" __all__ = ['SpatialReference'] from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt def __eq__(self, another): return bool(self.IsSame(another)) def __ne__(self, another): return not self.__eq__(another) @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
<commit_before>"""Spatial reference systems""" from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr <commit_msg>Add equality methods to SpatialReference<commit_after>"""Spatial reference systems""" __all__ = ['SpatialReference'] from osgeo import osr class BaseSpatialReference(osr.SpatialReference): """Base class for extending osr.SpatialReference.""" def __repr__(self): return self.wkt def __eq__(self, another): return bool(self.IsSame(another)) def __ne__(self, another): return not self.__eq__(another) @property def srid(self): """Returns the EPSG ID as int if it exists.""" epsg_id = (self.GetAuthorityCode('PROJCS') or self.GetAuthorityCode('GEOGCS')) try: return int(epsg_id) except TypeError: return @property def wkt(self): """Returns this projection in WKT format.""" return self.ExportToWkt() @property def proj4(self): """Returns this projection as a proj4 string.""" return self.ExportToProj4() class SpatialReference(object): """A spatial reference.""" def __new__(cls, sref): """Returns a new BaseSpatialReference instance This allows for customized construction of osr.SpatialReference which has no init method which precludes the use of super(). """ sr = BaseSpatialReference() if isinstance(sref, int): sr.ImportFromEPSG(sref) elif isinstance(sref, str): if sref.strip().startswith('+proj='): sr.ImportFromProj4(sref) else: sr.ImportFromWkt(sref) # Add EPSG authority if applicable sr.AutoIdentifyEPSG() else: raise TypeError('Cannot create SpatialReference ' 'from {}'.format(str(sref))) return sr
d52d26b45e20d0ae7b6b4fb5ffd3c29cdf7257ba
PCbuild8/rmpyc.py
PCbuild8/rmpyc.py
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print npyc, ".pyc deleted,", npyo, ".pyo deleted"
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print(npyc, ".pyc deleted,", npyo, ".pyo deleted")
Use new print function (part of patch 1031)
Use new print function (part of patch 1031)
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print npyc, ".pyc deleted,", npyo, ".pyo deleted" Use new print function (part of patch 1031)
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print(npyc, ".pyc deleted,", npyo, ".pyo deleted")
<commit_before># Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print npyc, ".pyc deleted,", npyo, ".pyo deleted" <commit_msg>Use new print function (part of patch 1031)<commit_after>
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print(npyc, ".pyc deleted,", npyo, ".pyo deleted")
# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print npyc, ".pyc deleted,", npyo, ".pyo deleted" Use new print function (part of patch 1031)# Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print(npyc, ".pyc deleted,", npyo, ".pyo deleted")
<commit_before># Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print npyc, ".pyc deleted,", npyo, ".pyo deleted" <commit_msg>Use new print function (part of patch 1031)<commit_after># Remove all the .pyc and .pyo files under ../Lib. import sys def deltree(root): import os from os.path import join npyc = npyo = 0 for root, dirs, files in os.walk(root): for name in files: delete = False if name.endswith('.pyc'): delete = True npyc += 1 elif name.endswith('.pyo'): delete = True npyo += 1 if delete: os.remove(join(root, name)) return npyc, npyo path = "../Lib" if len(sys.argv) > 1: path = sys.argv[1] npyc, npyo = deltree(path) print(npyc, ".pyc deleted,", npyo, ".pyo deleted")
9a5b0f08dfc6fe74965e1576697697a71ece4934
dit/utils/tests/test_context.py
dit/utils/tests/test_context.py
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir))
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile1(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_named_tempfile2(): name = None # The specification of delete=True should be ignored. with named_tempfile(delete=True) as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir))
Add test to verify that named_tempfile() overrides the `delete` parameter.
Add test to verify that named_tempfile() overrides the `delete` parameter.
Python
bsd-3-clause
dit/dit,chebee7i/dit,dit/dit,dit/dit,chebee7i/dit,Autoplectic/dit,Autoplectic/dit,dit/dit,chebee7i/dit,Autoplectic/dit,Autoplectic/dit,chebee7i/dit,Autoplectic/dit,dit/dit
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir)) Add test to verify that named_tempfile() overrides the `delete` parameter.
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile1(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_named_tempfile2(): name = None # The specification of delete=True should be ignored. with named_tempfile(delete=True) as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir))
<commit_before>from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir)) <commit_msg>Add test to verify that named_tempfile() overrides the `delete` parameter.<commit_after>
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile1(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_named_tempfile2(): name = None # The specification of delete=True should be ignored. with named_tempfile(delete=True) as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir))
from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir)) Add test to verify that named_tempfile() overrides the `delete` parameter.from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile1(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_named_tempfile2(): name = None # The specification of delete=True should be ignored. with named_tempfile(delete=True) as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir))
<commit_before>from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir)) <commit_msg>Add test to verify that named_tempfile() overrides the `delete` parameter.<commit_after>from __future__ import unicode_literals from nose.tools import * import os import time from dit.utils import cd, named_tempfile, tempdir def test_cd(): with cd('/'): assert_equal(os.getcwd(), '/') def test_named_tempfile1(): name = None with named_tempfile() as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_named_tempfile2(): name = None # The specification of delete=True should be ignored. with named_tempfile(delete=True) as tempfile: name = tempfile.name assert_true(os.path.isfile(name)) tempfile.write('hello'.encode('ascii')) tempfile.close() assert_true(os.path.isfile(name)) assert_false(os.path.isfile(name)) def test_tempdir(): name = None with tempdir() as tmpdir: assert_true(os.path.isdir(tmpdir)) assert_false(os.path.isdir(tmpdir))
366d7abd63d3f70ad206336a0278a0968b04b678
panoptes_aggregation/extractors/poly_line_text_extractor.py
panoptes_aggregation/extractors/poly_line_text_extractor.py
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data)
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') # NOTE: if `words` and `points` are differnt lengths # the extract will only contain the *shorter* of the # two lists (assuming they match from the front) for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data)
Add clarification comment to extractor
Add clarification comment to extractor Add a comment about the behavior of the extractor when the length of the `words` list does not match the lenght of the `points` list. The extract will only contain the *shorter* of the two lists and assume they match from the front.
Python
apache-2.0
CKrawczyk/python-reducers-for-caesar
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data) Add clarification comment to extractor Add a comment about the behavior of the extractor when the length of the `words` list does not match the lenght of the `points` list. The extract will only contain the *shorter* of the two lists and assume they match from the front.
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') # NOTE: if `words` and `points` are differnt lengths # the extract will only contain the *shorter* of the # two lists (assuming they match from the front) for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data)
<commit_before>from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data) <commit_msg>Add clarification comment to extractor Add a comment about the behavior of the extractor when the length of the `words` list does not match the lenght of the `points` list. The extract will only contain the *shorter* of the two lists and assume they match from the front.<commit_after>
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') # NOTE: if `words` and `points` are differnt lengths # the extract will only contain the *shorter* of the # two lists (assuming they match from the front) for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data)
from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data) Add clarification comment to extractor Add a comment about the behavior of the extractor when the length of the `words` list does not match the lenght of the `points` list. The extract will only contain the *shorter* of the two lists and assume they match from the front.from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') # NOTE: if `words` and `points` are differnt lengths # the extract will only contain the *shorter* of the # two lists (assuming they match from the front) for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data)
<commit_before>from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data) <commit_msg>Add clarification comment to extractor Add a comment about the behavior of the extractor when the length of the `words` list does not match the lenght of the `points` list. The extract will only contain the *shorter* of the two lists and assume they match from the front.<commit_after>from collections import OrderedDict def classification_to_extract(classification): extract = OrderedDict([ ('points', OrderedDict([('x', []), ('y', [])])), ('text', []), ('frame', []) ]) annotation = classification['annotations'][0] for value in annotation['value']: text = value['details'][0]['value'] words = text.split(' ') # NOTE: if `words` and `points` are differnt lengths # the extract will only contain the *shorter* of the # two lists (assuming they match from the front) for word, point in zip(words, value['points']): extract['frame'].append(value['frame']) extract['text'].append(word) extract['points']['x'].append(point['x']) extract['points']['y'].append(point['y']) return extract def poly_line_text_extractor_request(request): data = request.get_json() return classification_to_extract(data)
94e70a0958f0db737ca82c5ea09528bf4e5e4fef
voteswap/wsgi.py
voteswap/wsgi.py
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application()
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() try: from google.appengine.ext import vendor vendor.add('lib') except ImportError: pass
Add vendor dir to path
Add vendor dir to path
Python
mit
sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() Add vendor dir to path
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() try: from google.appengine.ext import vendor vendor.add('lib') except ImportError: pass
<commit_before>""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() <commit_msg>Add vendor dir to path<commit_after>
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() try: from google.appengine.ext import vendor vendor.add('lib') except ImportError: pass
""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() Add vendor dir to path""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() try: from google.appengine.ext import vendor vendor.add('lib') except ImportError: pass
<commit_before>""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() <commit_msg>Add vendor dir to path<commit_after>""" WSGI config for voteswap project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "voteswap.settings") application = get_wsgi_application() try: from google.appengine.ext import vendor vendor.add('lib') except ImportError: pass
1fde16891508179e5f3774d4624b9a0b48c39903
script/jsonify-book.py
script/jsonify-book.py
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}-metadata.json", 'w') as outfile: json.dump(json_data, outfile)
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}.json", 'w') as outfile: json.dump(json_data, outfile)
Remove metadata from jsonify output name
Remove metadata from jsonify output name
Python
lgpl-2.1
Connexions/cnx-rulesets,Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-rulesets,Connexions/cnx-rulesets,Connexions/cnx-recipes,Connexions/cte,Connexions/cte,Connexions/cnx-recipes,Connexions/cnx-rulesets,Connexions/cnx-recipes
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}-metadata.json", 'w') as outfile: json.dump(json_data, outfile)Remove metadata from jsonify output name
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}.json", 'w') as outfile: json.dump(json_data, outfile)
<commit_before>import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}-metadata.json", 'w') as outfile: json.dump(json_data, outfile)<commit_msg>Remove metadata from jsonify output name<commit_after>
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}.json", 'w') as outfile: json.dump(json_data, outfile)
import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}-metadata.json", 'w') as outfile: json.dump(json_data, outfile)Remove metadata from jsonify output nameimport sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}.json", 'w') as outfile: json.dump(json_data, outfile)
<commit_before>import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}-metadata.json", 'w') as outfile: json.dump(json_data, outfile)<commit_msg>Remove metadata from jsonify output name<commit_after>import sys from glob import glob from os.path import basename import json book_dir, out_dir = sys.argv[1:3] files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")] json_data = {} for path in files: with open(f"{book_dir}/{path}.json", "r") as meta_part: json_data = json.load(meta_part) with open(f"{book_dir}/{path}.xhtml", "r") as book_part: content = book_part.read() json_data["content"] = str(content) with open(f"{out_dir}/{path}.json", 'w') as outfile: json.dump(json_data, outfile)
0c0190c9505197bd8e9671580bd6aa776bc8b04a
utils/get_message.py
utils/get_message.py
import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = __get_channel(connection) return __get_message_from_queue(channel, queue)
import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = connection.channel() return channel.basic_get(queue=queue)
Revert "Revert "Remove redundant functions (one too many levels of abstraction)@""
Revert "Revert "Remove redundant functions (one too many levels of abstraction)@"" This reverts commit 34fda0b20a87b94d7413054bfcfc81dad0ecde19.
Python
mit
jdgillespie91/trackerSpend,jdgillespie91/trackerSpend
import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = __get_channel(connection) return __get_message_from_queue(channel, queue) Revert "Revert "Remove redundant functions (one too many levels of abstraction)@"" This reverts commit 34fda0b20a87b94d7413054bfcfc81dad0ecde19.
import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = connection.channel() return channel.basic_get(queue=queue)
<commit_before>import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = __get_channel(connection) return __get_message_from_queue(channel, queue) <commit_msg>Revert "Revert "Remove redundant functions (one too many levels of abstraction)@"" This reverts commit 34fda0b20a87b94d7413054bfcfc81dad0ecde19.<commit_after>
import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = connection.channel() return channel.basic_get(queue=queue)
import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = __get_channel(connection) return __get_message_from_queue(channel, queue) Revert "Revert "Remove redundant functions (one too many levels of abstraction)@"" This reverts commit 34fda0b20a87b94d7413054bfcfc81dad0ecde19.import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = connection.channel() return channel.basic_get(queue=queue)
<commit_before>import amqp from contextlib import closing def __get_channel(connection): return connection.channel() def __get_message_from_queue(channel, queue): return channel.basic_get(queue=queue) def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = __get_channel(connection) return __get_message_from_queue(channel, queue) <commit_msg>Revert "Revert "Remove redundant functions (one too many levels of abstraction)@"" This reverts commit 34fda0b20a87b94d7413054bfcfc81dad0ecde19.<commit_after>import amqp from contextlib import closing def get_message(queue): """ Get the first message from a queue. The first message from a queue is retrieved. If there is no such message, the function exits quietly. :param queue: The name of the queue from which to get the message. Usage:: >>> from utils import get_message >>> message = get_message('queue') """ with closing(amqp.Connection()) as connection: channel = connection.channel() return channel.basic_get(queue=queue)
f6154cceaeb9d9be718df8f21153b09052bd597c
stix/ttp/victim_targeting.py
stix/ttp/victim_targeting.py
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs, VocabString from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information)
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) targeted_technical_details = fields.TypedField("Targeted_Technical_Details", Observables) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information)
Add 'targeted_technical_details' TypedField to VictimTargeting
Add 'targeted_technical_details' TypedField to VictimTargeting
Python
bsd-3-clause
STIXProject/python-stix
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs, VocabString from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information) Add 'targeted_technical_details' TypedField to VictimTargeting
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) targeted_technical_details = fields.TypedField("Targeted_Technical_Details", Observables) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information)
<commit_before># Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs, VocabString from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information) <commit_msg>Add 'targeted_technical_details' TypedField to VictimTargeting<commit_after>
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) targeted_technical_details = fields.TypedField("Targeted_Technical_Details", Observables) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information)
# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs, VocabString from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information) Add 'targeted_technical_details' TypedField to VictimTargeting# Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) targeted_technical_details = fields.TypedField("Targeted_Technical_Details", Observables) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information)
<commit_before># Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs, VocabString from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information) <commit_msg>Add 'targeted_technical_details' TypedField to VictimTargeting<commit_after># Copyright (c) 2017, The MITRE Corporation. All rights reserved. # See LICENSE.txt for complete terms. # external from cybox.core import Observables # internal import stix import stix.bindings.ttp as ttp_binding from stix.common import vocabs from stix.common.identity import Identity, IdentityFactory from mixbox import fields class VictimTargeting(stix.Entity): _binding = ttp_binding _binding_class = _binding.VictimTargetingType _namespace = "http://stix.mitre.org/TTP-1" identity = fields.TypedField("Identity", Identity, factory=IdentityFactory) targeted_systems = vocabs.VocabField("Targeted_Systems", vocabs.SystemType, multiple=True) targeted_information = vocabs.VocabField("Targeted_Information", vocabs.InformationType, multiple=True) targeted_technical_details = fields.TypedField("Targeted_Technical_Details", Observables) def __init__(self): super(VictimTargeting, self).__init__() def add_targeted_system(self, system): self.targeted_systems.append(system) def add_targeted_information(self, targeted_information): self.targeted_information.append(targeted_information)
e9f3efcc1d9a3372e97e396160ea2ecbdee778c6
rfmodbuslib/__init__.py
rfmodbuslib/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group'
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' __version__ = __lib_version__
Add a .__version__ attribute to package
Add a .__version__ attribute to package
Python
apache-2.0
Legrandgroup/robotframework-modbuslibrary
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' Add a .__version__ attribute to package
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' __version__ = __lib_version__
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' <commit_msg>Add a .__version__ attribute to package<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' __version__ = __lib_version__
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' Add a .__version__ attribute to package#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' __version__ = __lib_version__
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' <commit_msg>Add a .__version__ attribute to package<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2015 Legrand Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __append_version__ = '-alpha' __lib_version__ = '0.1' + __append_version__ __lib_name__ = 'rfmodbuslib' __lib_copyright__ = 'Copyright 2015 Legrand Group' __version__ = __lib_version__
25213d331b879a7203ccd99ccf34ad19661d1853
sublimelinter/modules/php.py
sublimelinter/modules/php.py
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:syntax error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages)
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:\w+ error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages)
Remove "Parse error, " from error messages
Remove "Parse error, " from error messages
Python
mit
uschmidt83/SublimeLinter-for-ST2,benesch/sublime-linter,tangledhelix/SublimeLinter-for-ST2,tangledhelix/SublimeLinter-for-ST2,SublimeLinter/SublimeLinter-for-ST2,biodamasceno/SublimeLinter-for-ST2,SublimeLinter/SublimeLinter-for-ST2,uschmidt83/SublimeLinter-for-ST2,benesch/sublime-linter,biodamasceno/SublimeLinter-for-ST2
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:syntax error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages) Remove "Parse error, " from error messages
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:\w+ error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages)
<commit_before># -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:syntax error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages) <commit_msg>Remove "Parse error, " from error messages<commit_after>
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:\w+ error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages)
# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:syntax error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages) Remove "Parse error, " from error messages# -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:\w+ error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages)
<commit_before># -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:syntax error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages) <commit_msg>Remove "Parse error, " from error messages<commit_after># -*- coding: utf-8 -*- # php.py - sublimelint package for checking php files import re from base_linter import BaseLinter CONFIG = { 'language': 'php', 'executable': 'php', 'lint_args': ('-l', '-d display_errors=On') } class Linter(BaseLinter): def parse_errors(self, view, errors, lines, errorUnderlines, violationUnderlines, warningUnderlines, errorMessages, violationMessages, warningMessages): for line in errors.splitlines(): match = re.match(r'^Parse error:\s*(?:\w+ error,\s*)?(?P<error>.+?)\s+in\s+.+?\s*line\s+(?P<line>\d+)', line) if match: error, line = match.group('error'), match.group('line') self.add_message(int(line), lines, error, errorMessages)
388d8413f0df3cb6069cf393e033b3d23f4b63c7
features/environment.py
features/environment.py
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) server.initialize_index() context.server = server
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) context.server = server
Remove troublesome function from behave's environ.
Remove troublesome function from behave's environ.
Python
apache-2.0
nyu-delta-squad-s17/recommendation-service
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) server.initialize_index() context.server = server Remove troublesome function from behave's environ.
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) context.server = server
<commit_before>from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) server.initialize_index() context.server = server <commit_msg>Remove troublesome function from behave's environ.<commit_after>
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) context.server = server
from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) server.initialize_index() context.server = server Remove troublesome function from behave's environ.from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) context.server = server
<commit_before>from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) server.initialize_index() context.server = server <commit_msg>Remove troublesome function from behave's environ.<commit_after>from behave import * import server def before_all(context): context.app = server.app.test_client() server.initialize_mysql(test=True) context.server = server
2f063f6dd9d10dabd967554bfcf7f6a63c979911
OpenSearchInNewTab.py
OpenSearchInNewTab.py
import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): view.set_name(DEFAULT_NAME) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME
import sublime_plugin from threading import Timer DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_default_name(view) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def apply_default_name(self, view): view.set_name(DEFAULT_NAME) t = Timer(.1, self.apply_alt_name, (view,)) t.start() def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME
Make plugin more stable by introducing async renaming to alternative name
Make plugin more stable by introducing async renaming to alternative name
Python
mit
everyonesdesign/OpenSearchInNewTab
import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): view.set_name(DEFAULT_NAME) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME Make plugin more stable by introducing async renaming to alternative name
import sublime_plugin from threading import Timer DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_default_name(view) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def apply_default_name(self, view): view.set_name(DEFAULT_NAME) t = Timer(.1, self.apply_alt_name, (view,)) t.start() def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME
<commit_before>import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): view.set_name(DEFAULT_NAME) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME <commit_msg>Make plugin more stable by introducing async renaming to alternative name<commit_after>
import sublime_plugin from threading import Timer DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_default_name(view) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def apply_default_name(self, view): view.set_name(DEFAULT_NAME) t = Timer(.1, self.apply_alt_name, (view,)) t.start() def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME
import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): view.set_name(DEFAULT_NAME) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME Make plugin more stable by introducing async renaming to alternative nameimport sublime_plugin from threading import Timer DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_default_name(view) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def apply_default_name(self, view): view.set_name(DEFAULT_NAME) t = Timer(.1, self.apply_alt_name, (view,)) t.start() def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME
<commit_before>import sublime_plugin DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): view.set_name(DEFAULT_NAME) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME <commit_msg>Make plugin more stable by introducing async renaming to alternative name<commit_after>import sublime_plugin from threading import Timer DEFAULT_NAME = 'Find Results' ALT_NAME = 'Find Results ' class OpenSearchInNewTab(sublime_plugin.EventListener): # set a bit changed name # so the tab won't be bothered # during new search def on_activated(self, view): if self.is_search_view(view): self.apply_alt_name(view) # these hooks will help other plugins # to understand that we are in search results file def on_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_default_name(view) def post_text_command(self, view, command_name, args): if self.is_search_view(view): self.apply_alt_name(view) def apply_alt_name(self, view): view.set_name(ALT_NAME) def apply_default_name(self, view): view.set_name(DEFAULT_NAME) t = Timer(.1, self.apply_alt_name, (view,)) t.start() def is_search_view(self, view): name = view.name() return name == ALT_NAME or name == DEFAULT_NAME
e5f4627845a6874aa983d2d8ea02d5bea0fab8e2
meetings/osf_oauth2_adapter/provider.py
meetings/osf_oauth2_adapter/provider.py
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=data.get('id'), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
Change username to osf uid
Change username to osf uid
Python
apache-2.0
jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,jnayak1/osf-meetings,jnayak1/osf-meetings,leodomingo/osf-meetings,leodomingo/osf-meetings
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=data.get('id'), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)Change username to osf uid
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
<commit_before>from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=data.get('id'), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)<commit_msg>Change username to osf uid<commit_after>
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=data.get('id'), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)Change username to osf uidfrom .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
<commit_before>from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=data.get('id'), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)<commit_msg>Change username to osf uid<commit_after>from .apps import OsfOauth2AdapterConfig from allauth.socialaccount import providers from allauth.socialaccount.providers.base import ProviderAccount from allauth.socialaccount.providers.oauth2.provider import OAuth2Provider class OSFAccount(ProviderAccount): def to_str(self): # default ... reserved word? dflt = super(OSFAccount, self).to_str() return next( value for value in ( # try the name first, then the id, then the super value '{} {}'.format( self.account.extra_data.get('first_name', None), self.account.extra_data.get('last_name', None) ), self.account.extra_data.get('id', None), dflt ) if value is not None ) class OSFProvider(OAuth2Provider): id = 'osf' name = 'Open Science Framework' account_class = OSFAccount def extract_common_fields(self, data): attributes = data.get('data').get('attributes') return dict( # we could put more fields here later # the api has much more available, just not sure how much we need right now username=self.extract_uid(data), first_name=attributes.get('given_name'), last_name=attributes.get('family_name'), ) def extract_uid(self, data): return str(data.get('data').get('id')) def get_default_scope(self): return OsfOauth2AdapterConfig.default_scopes providers.registry.register(OSFProvider)
1473af1b50da6390e1b4475ae63d5a28f712e791
tests/test_frijoles.py
tests/test_frijoles.py
import unittest from frijoles import app class TamalesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
import unittest from frijoles import app class FrijolesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
Fix wrong test case name
Fix wrong test case name
Python
agpl-3.0
Antojitos/frijoles
import unittest from frijoles import app class TamalesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200) Fix wrong test case name
import unittest from frijoles import app class FrijolesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
<commit_before>import unittest from frijoles import app class TamalesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200) <commit_msg>Fix wrong test case name<commit_after>
import unittest from frijoles import app class FrijolesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
import unittest from frijoles import app class TamalesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200) Fix wrong test case nameimport unittest from frijoles import app class FrijolesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
<commit_before>import unittest from frijoles import app class TamalesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200) <commit_msg>Fix wrong test case name<commit_after>import unittest from frijoles import app class FrijolesAPITestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_basic(self): res = self.app.get('/api/v1/') self.assertEqual(res.status_code, 200)
fbc5e2d52549452c2adbe58644358cf3c4eeb526
testsuite/test_util.py
testsuite/test_util.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*'])
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths([]), []) self.assertEquals(pep8.normalize_paths(None), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('foo, bar '), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*'])
Add a few more cases of "not value"
Add a few more cases of "not value"
Python
mit
ojengwa/pep8,pedros/pep8,asandyz/pep8,jayvdb/pep8,doismellburning/pep8,pandeesh/pep8,jayvdb/pep8,PyCQA/pep8,ABaldwinHunter/pep8,codeclimate/pep8,ABaldwinHunter/pep8-clone-classic,zevnux/pep8,MeteorAdminz/pep8
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*']) Add a few more cases of "not value"
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths([]), []) self.assertEquals(pep8.normalize_paths(None), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('foo, bar '), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*'])
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*']) <commit_msg>Add a few more cases of "not value"<commit_after>
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths([]), []) self.assertEquals(pep8.normalize_paths(None), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('foo, bar '), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*'])
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*']) Add a few more cases of "not value"#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths([]), []) self.assertEquals(pep8.normalize_paths(None), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('foo, bar '), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*'])
<commit_before>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*']) <commit_msg>Add a few more cases of "not value"<commit_after>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import pep8 class UtilTestCase(unittest.TestCase): def test_normalize_paths(self): cwd = os.getcwd() self.assertEquals(pep8.normalize_paths(''), []) self.assertEquals(pep8.normalize_paths([]), []) self.assertEquals(pep8.normalize_paths(None), []) self.assertEquals(pep8.normalize_paths(['foo']), ['foo']) self.assertEquals(pep8.normalize_paths('foo'), ['foo']) self.assertEquals(pep8.normalize_paths('foo,bar'), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('foo, bar '), ['foo', 'bar']) self.assertEquals(pep8.normalize_paths('/foo/bar,baz/../bat'), ['/foo/bar', cwd + '/bat']) self.assertEquals(pep8.normalize_paths(".pyc,\n build/*"), ['.pyc', cwd + '/build/*'])
03f74920a56afcbc4dbdb0370c3fab84a27bc299
openacademy/model/openacademy_course.py
openacademy/model/openacademy_course.py
from openerp import models, fields, api ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ]
from openerp import api, fields, models ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one # api.one send defaults params: cr, uid, id, context def copy(self, default=None): print "estoy pasando por la funcion heredada de copy en cursos" # default['name'] = self.name + ' (copy)' copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
Modify copy method into inherit
[REF] openacademy: Modify copy method into inherit
Python
apache-2.0
glizek/openacademy-project
from openerp import models, fields, api ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] [REF] openacademy: Modify copy method into inherit
from openerp import api, fields, models ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one # api.one send defaults params: cr, uid, id, context def copy(self, default=None): print "estoy pasando por la funcion heredada de copy en cursos" # default['name'] = self.name + ' (copy)' copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
<commit_before>from openerp import models, fields, api ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] <commit_msg>[REF] openacademy: Modify copy method into inherit<commit_after>
from openerp import api, fields, models ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one # api.one send defaults params: cr, uid, id, context def copy(self, default=None): print "estoy pasando por la funcion heredada de copy en cursos" # default['name'] = self.name + ' (copy)' copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
from openerp import models, fields, api ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] [REF] openacademy: Modify copy method into inheritfrom openerp import api, fields, models ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one # api.one send defaults params: cr, uid, id, context def copy(self, default=None): print "estoy pasando por la funcion heredada de copy en cursos" # default['name'] = self.name + ' (copy)' copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
<commit_before>from openerp import models, fields, api ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] <commit_msg>[REF] openacademy: Modify copy method into inherit<commit_after>from openerp import api, fields, models ''' This module is to create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one # api.one send defaults params: cr, uid, id, context def copy(self, default=None): print "estoy pasando por la funcion heredada de copy en cursos" # default['name'] = self.name + ' (copy)' copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
c775df0af114a332077771609d4b24a04bd6bfd2
bin/parsers/DeploysServiceLookup.py
bin/parsers/DeploysServiceLookup.py
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ]
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' alert['tags'].append('email:frontend') elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ]
Add email tag to fronted deploy failures
Add email tag to fronted deploy failures
Python
apache-2.0
skob/alerta,mrkeng/alerta,0312birdzhang/alerta,skob/alerta,mrkeng/alerta,0312birdzhang/alerta,skob/alerta,0312birdzhang/alerta,mrkeng/alerta,guardian/alerta,guardian/alerta,guardian/alerta,guardian/alerta,skob/alerta,mrkeng/alerta
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ] Add email tag to fronted deploy failures
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' alert['tags'].append('email:frontend') elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ]
<commit_before> if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ] <commit_msg>Add email tag to fronted deploy failures<commit_after>
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' alert['tags'].append('email:frontend') elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ]
if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ] Add email tag to fronted deploy failures if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' alert['tags'].append('email:frontend') elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ]
<commit_before> if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ] <commit_msg>Add email tag to fronted deploy failures<commit_after> if alert['resource'].startswith('R1'): alert['service'] = [ 'R1' ] elif alert['resource'].startswith('R2'): alert['service'] = [ 'R2' ] elif 'content-api' in alert['resource'].lower(): alert['service'] = [ 'ContentAPI' ] elif alert['resource'].startswith('frontend'): alert['service'] = [ 'Frontend' ] if alert['event'] == 'DeployFailed': alert['severity'] = 'CRITICAL' alert['tags'].append('email:frontend') elif 'flexible' in alert['resource'].lower(): alert['service'] = [ 'FlexibleContent' ] elif alert['resource'].startswith('Identity'): alert['service'] = [ 'Identity' ] elif alert['resource'].startswith('Mobile'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Android'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('iOS'): alert['service'] = [ 'Mobile' ] elif alert['resource'].startswith('Soulmates'): alert['service'] = [ 'Soulmates' ] elif alert['resource'].startswith('Microapps'): alert['service'] = [ 'MicroApp' ] elif alert['resource'].startswith('Mutualisation'): alert['service'] = [ 'Mutualisation' ] elif alert['resource'].startswith('Ophan'): alert['service'] = [ 'Ophan' ] else: alert['service'] = [ 'Unknown' ]
b7bafa86cf6e2f568e99335fa6aeb6d8f3509170
dont_tread_on_memes/__init__.py
dont_tread_on_memes/__init__.py
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase))
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs)
Allow passing arguments through dont_me to tread_on
Allow passing arguments through dont_me to tread_on
Python
mit
controversial/dont-tread-on-memes
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase)) Allow passing arguments through dont_me to tread_on
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs)
<commit_before>#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase)) <commit_msg>Allow passing arguments through dont_me to tread_on<commit_after>
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs)
#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase)) Allow passing arguments through dont_me to tread_on#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs)
<commit_before>#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase)) <commit_msg>Allow passing arguments through dont_me to tread_on<commit_after>#!python3 import os from PIL import Image, ImageDraw, ImageFont localdir = os.path.dirname(__file__) BLANK_FLAG = Image.open(os.path.join(localdir, "dont-tread-on-blank.png")) LORA_FONT = ImageFont.truetype( os.path.join(localdir, "../fonts/Lora-Regular.ttf"), 120 ) def tread_on(caption, color="black"): """Caption the "Don't Tread on Me" snake with `caption`""" flag = BLANK_FLAG.copy() draw = ImageDraw.Draw(flag) text = caption.upper() font_pos = (flag.width / 2 - LORA_FONT.getsize(text)[0] / 2, 1088) draw.text(font_pos, text, font=LORA_FONT, fill=color) return flag def dont_me(phrase, *args, **kwargs): """Caption the "Don't tread on me" flag with "Don't [phrase] me" """ return tread_on("don't {} me".format(phrase), *args, **kwargs)
3ff4aef8d130cdcbf149328d93337fa984a9a94b
dont_tread_on_memes/__main__.py
dont_tread_on_memes/__main__.py
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) def tread(message): dont_tread_on_memes.tread_on(message).show() if __name__ == "__main__": tread()
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) @click.option("--save", default=None, help="Where to save the image") def tread(message, save): flag = dont_tread_on_memes.tread_on(message) if save is not None: flag.save(save) else: flag.show() if __name__ == "__main__": tread()
Allow saving via --save CLI parameter
Allow saving via --save CLI parameter
Python
mit
controversial/dont-tread-on-memes
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) def tread(message): dont_tread_on_memes.tread_on(message).show() if __name__ == "__main__": tread() Allow saving via --save CLI parameter
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) @click.option("--save", default=None, help="Where to save the image") def tread(message, save): flag = dont_tread_on_memes.tread_on(message) if save is not None: flag.save(save) else: flag.show() if __name__ == "__main__": tread()
<commit_before>import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) def tread(message): dont_tread_on_memes.tread_on(message).show() if __name__ == "__main__": tread() <commit_msg>Allow saving via --save CLI parameter<commit_after>
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) @click.option("--save", default=None, help="Where to save the image") def tread(message, save): flag = dont_tread_on_memes.tread_on(message) if save is not None: flag.save(save) else: flag.show() if __name__ == "__main__": tread()
import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) def tread(message): dont_tread_on_memes.tread_on(message).show() if __name__ == "__main__": tread() Allow saving via --save CLI parameterimport dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) @click.option("--save", default=None, help="Where to save the image") def tread(message, save): flag = dont_tread_on_memes.tread_on(message) if save is not None: flag.save(save) else: flag.show() if __name__ == "__main__": tread()
<commit_before>import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) def tread(message): dont_tread_on_memes.tread_on(message).show() if __name__ == "__main__": tread() <commit_msg>Allow saving via --save CLI parameter<commit_after>import dont_tread_on_memes import click @click.command() @click.option("--message", prompt="Don't _____ me: ", help=("The word or phrase to substitute for 'tread' in 'don't " "tread on me'")) @click.option("--save", default=None, help="Where to save the image") def tread(message, save): flag = dont_tread_on_memes.tread_on(message) if save is not None: flag.save(save) else: flag.show() if __name__ == "__main__": tread()
4fbec4f4c0741edb6207d762cc92e48c6f249eec
dragonflow/common/extensions.py
dragonflow/common/extensions.py
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'l3_agent_scheduler', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. # NOTE (dimak): This used only for tempest's enabled network API extensions SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
Disable L3 agents scheduler extension in Tempest
Disable L3 agents scheduler extension in Tempest Change-Id: Ibc2d85bce9abb821e897693ebdade66d3b9199c3 Closes-Bug: #1707496
Python
apache-2.0
openstack/dragonflow,openstack/dragonflow,openstack/dragonflow
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'l3_agent_scheduler', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ] Disable L3 agents scheduler extension in Tempest Change-Id: Ibc2d85bce9abb821e897693ebdade66d3b9199c3 Closes-Bug: #1707496
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. # NOTE (dimak): This used only for tempest's enabled network API extensions SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
<commit_before># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'l3_agent_scheduler', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ] <commit_msg>Disable L3 agents scheduler extension in Tempest Change-Id: Ibc2d85bce9abb821e897693ebdade66d3b9199c3 Closes-Bug: #1707496<commit_after>
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. # NOTE (dimak): This used only for tempest's enabled network API extensions SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'l3_agent_scheduler', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ] Disable L3 agents scheduler extension in Tempest Change-Id: Ibc2d85bce9abb821e897693ebdade66d3b9199c3 Closes-Bug: #1707496# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. # NOTE (dimak): This used only for tempest's enabled network API extensions SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
<commit_before># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'l3_agent_scheduler', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ] <commit_msg>Disable L3 agents scheduler extension in Tempest Change-Id: Ibc2d85bce9abb821e897693ebdade66d3b9199c3 Closes-Bug: #1707496<commit_after># # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # If you update this list, please also update # doc/source/features.rst. # NOTE (dimak): This used only for tempest's enabled network API extensions SUPPORTED_API_EXTENSIONS = [ 'agent', 'quotas', 'extra_dhcp_opt', 'binding', 'dhcp_agent_scheduler', 'security-group', 'external-net', 'router', 'subnet_allocation', 'port-security', 'allowed-address-pairs', 'net-mtu', 'default-subnetpools', 'extraroute', 'bgp', 'trunk', 'flow_classifier', 'sfc', ]
97b6c8cb246e21d6bc2b0334cbf3a95588571c71
src/aimes/emgr/workloads/skeleton.py
src/aimes/emgr/workloads/skeleton.py
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['avg']) elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout)
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['max']) # TODO: Calculate stdev and avg. elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout)
Use max duration when uniform time distribution
Use max duration when uniform time distribution
Python
mit
radical-cybertools/aimes.emgr
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['avg']) elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout) Use max duration when uniform time distribution
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['max']) # TODO: Calculate stdev and avg. elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout)
<commit_before>import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['avg']) elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout) <commit_msg>Use max duration when uniform time distribution<commit_after>
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['max']) # TODO: Calculate stdev and avg. elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout)
import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['avg']) elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout) Use max duration when uniform time distributionimport sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['max']) # TODO: Calculate stdev and avg. elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout)
<commit_before>import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['avg']) elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout) <commit_msg>Use max duration when uniform time distribution<commit_after>import sys from aimes.emgr.utils import * __author__ = "Matteo Turilli" __copyright__ = "Copyright 2015, The AIMES Project" __license__ = "MIT" # ----------------------------------------------------------------------------- def write_skeleton_conf(cfg, scale, cores, uniformity, fout): '''Write a skeleton configuration file with the set number/type/duration of tasks and stages. ''' substitutes = dict() substitutes['SCALE'] = scale substitutes['CORES'] = cores[-1] if substitutes['CORES'] > 1: substitutes['TASK_TYPE'] = 'parallel' elif substitutes['CORES'] == 1: substitutes['TASK_TYPE'] = 'serial' else: print "ERROR: invalid number of cores per task: '%s'." % cores sys.exit(1) if uniformity == 'uniform': substitutes['UNIFORMITY_DURATION'] = "%s %s" % \ (uniformity, cfg['skeleton_task_duration']['max']) # TODO: Calculate stdev and avg. elif uniformity == 'gauss': substitutes['UNIFORMITY_DURATION'] = "%s [%s, %s]" % \ (uniformity, cfg['skeleton_task_duration']['avg'], cfg['skeleton_task_duration']['stdev']) else: print "ERROR: invalid task uniformity '%s' specified." % uniformity sys.exit(1) write_template(cfg['skeleton_template'], substitutes, fout)
060c5f13886191777e2709c9119d480fe0983ced
TorGTK/pref_handle.py
TorGTK/pref_handle.py
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) print objs[pref_mappings[option]] objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
Remove line for debugging which lists object type from elements of listbox
Remove line for debugging which lists object type from elements of listbox
Python
bsd-2-clause
neelchauhan/TorGTK,neelchauhan/TorNova
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) print objs[pref_mappings[option]] objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close() Remove line for debugging which lists object type from elements of listbox
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
<commit_before>import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) print objs[pref_mappings[option]] objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close() <commit_msg>Remove line for debugging which lists object type from elements of listbox<commit_after>
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) print objs[pref_mappings[option]] objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close() Remove line for debugging which lists object type from elements of listboximport ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
<commit_before>import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) print objs[pref_mappings[option]] objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close() <commit_msg>Remove line for debugging which lists object type from elements of listbox<commit_after>import ConfigParser from gi.repository import Gtk from pref_mapping import * from var import * def read_config_if_exists(filename): if os.path.isfile(filename): # Init config parser and read config Config = ConfigParser.SafeConfigParser() Config.read(filename) section = "TorGTKprefs" # Loop through options options = Config.options(section) for option in options: value = Config.get(section, option) objs[pref_mappings[option]].set_value(int(value)) def write_config(filename): # Open file config_fd = open(filename, "w") Config = ConfigParser.ConfigParser() Config.add_section("TorGTKprefs") # Write sections to file and close it for key in pref_mappings: Config.set("TorGTKprefs", key, objs[pref_mappings[key]].get_text()) Config.write(config_fd) config_fd.close()
85a26420dda32d25a3c4b214e0156aaa558158e9
src/foremast/iam/construct_policy.py
src/foremast/iam/construct_policy.py
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ] "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ], "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json
Fix example of services for IAM Policies
docs: Fix example of services for IAM Policies See also: PSOBAT-1482
Python
apache-2.0
gogoair/foremast,gogoair/foremast
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ] "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json docs: Fix example of services for IAM Policies See also: PSOBAT-1482
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ], "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json
<commit_before>"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ] "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json <commit_msg>docs: Fix example of services for IAM Policies See also: PSOBAT-1482<commit_after>
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ], "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json
"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ] "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json docs: Fix example of services for IAM Policies See also: PSOBAT-1482"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ], "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json
<commit_before>"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ] "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json <commit_msg>docs: Fix example of services for IAM Policies See also: PSOBAT-1482<commit_after>"""Construct an IAM Policy from templates. Examples: pipeline.json: { "services": { "dynamodb": [ "another_app" ], "lambda": true, "s3": true } } """ import json import logging from ..utils import get_template, get_env_credential LOG = logging.getLogger(__name__) def construct_policy(app='coreforrest', env='dev', group='forrest', region='us-east-1', pipeline_settings=None): """Assemble IAM Policy for _app_. Args: app (str): Name of Spinnaker Application. pipeline_settings (dict): Settings from *pipeline.json*. Returns: str: Custom IAM Policy for _app_. """ LOG.info('Create custom IAM Policy for %s.', app) services = pipeline_settings['services'] LOG.debug('Found requested services: %s', services) credential = get_env_credential(env=env) account_number = credential['accountId'] statements = [] for service, value in services.items(): if isinstance(value, (bool, str)): items = [value] else: items = value statement = json.loads(get_template('iam/{0}.json.j2'.format(service), account_number=account_number, app=app, env=env, group=group, region=region, items=items)) statements.append(statement) policy_json = get_template('iam/wrapper.json.j2', statements=json.dumps(statements)) return policy_json
a8e7f1161afa313e25e678a1a2c1cdc1bc443f25
src/core/urls.py
src/core/urls.py
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ]
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] try: if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] except AttributeError: pass
Handle installs not using new settings engine
Handle installs not using new settings engine
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] Handle installs not using new settings engine
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] try: if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] except AttributeError: pass
<commit_before>__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] <commit_msg>Handle installs not using new settings engine<commit_after>
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] try: if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] except AttributeError: pass
__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] Handle installs not using new settings engine__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] try: if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] except AttributeError: pass
<commit_before>__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] <commit_msg>Handle installs not using new settings engine<commit_after>__copyright__ = "Copyright 2017 Birkbeck, University of London" __author__ = "Martin Paul Eve & Andy Byers" __license__ = "AGPL v3" __maintainer__ = "Birkbeck Centre for Technology and Publishing" from django.conf.urls import include, url from django.contrib import admin from django.views.generic import TemplateView from django.conf import settings from django.views.static import serve from press import views as press_views include('events.registration') urlpatterns = [ url(r'^$', press_views.index, name='website_index'), url(r'^admin/', include(admin.site.urls)), url(r'^summernote/', include('django_summernote.urls')), url(r'', include('core.include_urls')), ] try: if settings.DEBUG or settings.IN_TEST_RUNNER: import debug_toolbar urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^404/$', TemplateView.as_view(template_name='404.html')), url(r'^500/$', TemplateView.as_view(template_name='500.html')), url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^hijack/', include('hijack.urls', namespace='hijack')), ] except AttributeError: pass
5e1fc4fbb2f363fd2116d153e735ff3322001b3a
tests/trac/test-trac-0132.py
tests/trac/test-trac-0132.py
# -*- coding: utf-8 -*- import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import sys import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) if sys.version[:2] > (2, 4): self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main()
Revise test to support Python 2.4.
Revise test to support Python 2.4. In this version, base Exception didn't have a .message field. No wonder I had added it back in 2009, resulting in trac/132 which removed it.
Python
apache-2.0
balanced/PyXB,jonfoster/pyxb2,CantemoInternal/pyxb,jonfoster/pyxb1,pabigot/pyxb,jonfoster/pyxb2,balanced/PyXB,jonfoster/pyxb2,pabigot/pyxb,jonfoster/pyxb-upstream-mirror,CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,balanced/PyXB,jonfoster/pyxb-upstream-mirror,CantemoInternal/pyxb
# -*- coding: utf-8 -*- import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main() Revise test to support Python 2.4. In this version, base Exception didn't have a .message field. No wonder I had added it back in 2009, resulting in trac/132 which removed it.
# -*- coding: utf-8 -*- import sys import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) if sys.version[:2] > (2, 4): self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main()
<commit_before># -*- coding: utf-8 -*- import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main() <commit_msg>Revise test to support Python 2.4. In this version, base Exception didn't have a .message field. No wonder I had added it back in 2009, resulting in trac/132 which removed it.<commit_after>
# -*- coding: utf-8 -*- import sys import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) if sys.version[:2] > (2, 4): self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main() Revise test to support Python 2.4. In this version, base Exception didn't have a .message field. No wonder I had added it back in 2009, resulting in trac/132 which removed it.# -*- coding: utf-8 -*- import sys import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) if sys.version[:2] > (2, 4): self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main()
<commit_before># -*- coding: utf-8 -*- import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main() <commit_msg>Revise test to support Python 2.4. In this version, base Exception didn't have a .message field. No wonder I had added it back in 2009, resulting in trac/132 which removed it.<commit_after># -*- coding: utf-8 -*- import sys import pyxb import unittest class TestTrac0132 (unittest.TestCase): message = u'bad character \u2620' def testDecode (self): e = pyxb.PyXBException(self.message) if sys.version[:2] > (2, 4): self.assertEqual(self.message, e.message) if __name__ == '__main__': unittest.main()