commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
77caf4f14363c6f53631050d008bc852df465f5e
tests/repl_tests.py
tests/repl_tests.py
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_session(f): strin = Pipe() strout = Pipe() strerr = Pipe() replthread = Thread(target=repl, args=(strin, strout, strerr)) replthread.start() for exp_line in f: expprompt = exp_line[:4] if expprompt in (">>> ", "... "): prompt = strout.read(4) if prompt != exp_line[:4]: raise Exception( "Prompt was '%s' but we expected '%s'." % ( prompt, exp_line[:4])) strin.write(exp_line[4:]) else: output = strout.readline() if output != exp_line: raise Exception("Output was '%s' but we expected '%s'" % ( output, exp_line)) strerr.close() strout.close() strin.close() replthread.join() @system_test def All_example_repl_sessions_are_correct(): from pycell.chars_in_file import chars_in_file for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
from tests.util.pipe import Pipe from threading import Thread from pycell.repl import repl from tests.util.system_test import system_test from tests.util.all_examples import all_sessions def _validate_line(exp_line, strin, strout): expprompt = exp_line[:4] if expprompt in (">>> ", "... "): prompt = strout.read(4) if prompt != exp_line[:4]: raise Exception( "Prompt was '%s' but we expected '%s'." % ( prompt, exp_line[:4]) ) strin.write(exp_line[4:]) else: output = strout.readline() if output != exp_line: raise Exception("Output was '%s' but we expected '%s'" % ( output, exp_line) ) def _validate_session(f): with Pipe() as strin, Pipe() as strout, Pipe() as strerr: replthread = Thread(target=repl, args=(strin, strout, strerr)) replthread.start() for exp_line in f: _validate_line(exp_line, strin, strout) replthread.join() @system_test def All_example_repl_sessions_are_correct(): for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
Stop the repl test on an error, making sure all Pipes are closed
Stop the repl test on an error, making sure all Pipes are closed
Python
mit
andybalaam/cell
--- +++ @@ -7,36 +7,36 @@ from tests.util.system_test import system_test from tests.util.all_examples import all_sessions + +def _validate_line(exp_line, strin, strout): + expprompt = exp_line[:4] + if expprompt in (">>> ", "... "): + prompt = strout.read(4) + if prompt != exp_line[:4]: + raise Exception( + "Prompt was '%s' but we expected '%s'." % ( + prompt, exp_line[:4]) + ) + strin.write(exp_line[4:]) + else: + output = strout.readline() + if output != exp_line: + raise Exception("Output was '%s' but we expected '%s'" % ( + output, exp_line) + ) + + def _validate_session(f): - strin = Pipe() - strout = Pipe() - strerr = Pipe() - replthread = Thread(target=repl, args=(strin, strout, strerr)) - replthread.start() - for exp_line in f: - expprompt = exp_line[:4] - if expprompt in (">>> ", "... "): - prompt = strout.read(4) - if prompt != exp_line[:4]: - raise Exception( - "Prompt was '%s' but we expected '%s'." % ( - prompt, exp_line[:4])) - strin.write(exp_line[4:]) - else: - output = strout.readline() - if output != exp_line: - raise Exception("Output was '%s' but we expected '%s'" % ( - output, exp_line)) - - strerr.close() - strout.close() - strin.close() + with Pipe() as strin, Pipe() as strout, Pipe() as strerr: + replthread = Thread(target=repl, args=(strin, strout, strerr)) + replthread.start() + for exp_line in f: + _validate_line(exp_line, strin, strout) replthread.join() @system_test def All_example_repl_sessions_are_correct(): - from pycell.chars_in_file import chars_in_file for example in all_sessions(): with open(example, encoding="ascii") as f: _validate_session(f)
534e7bf630670a5aa42ba4787e66f0b02fb55a7d
conductance_congestion_approx.py
conductance_congestion_approx.py
from __future__ import division import numpy as np from congestion_approx import CongestionApprox class ConductanceCongestionApprox(CongestionApprox): def __init__(s, g): s.vertex_degrees_inv = [ 1.0 / g.degree(v) if g.degree(v) > 0 else 0 for v in g.nodes()] def compute_dot(s, x): return np.multiply(x, s.vertex_degrees_inv) def compute_transpose_dot(s, x): return np.multiply(x, s.vertex_degrees_inv) def alpha(s): return 1.0
from __future__ import division import numpy as np from congestion_approx import CongestionApprox class ConductanceCongestionApprox(CongestionApprox): def __init__(s, g): s.vertex_degrees_inv = [ 1.0 / g.degree(v) if g.degree(v) > 0 else 0 for v in g.nodes()] def compute_dot(s, x): return np.multiply(x, s.vertex_degrees_inv) def compute_transpose_dot(s, x): return np.multiply(x, s.vertex_degrees_inv) def alpha(s): # TODO: this probably isn't quite right. return 1.0
Add TODO regarding conductance congestion approximator
Add TODO regarding conductance congestion approximator
Python
mit
weinstein/FastMaxFlow
--- +++ @@ -18,4 +18,5 @@ def alpha(s): + # TODO: this probably isn't quite right. return 1.0
93a4191b9cb79ee4ddb2efbb4962bef99bc2ec28
totp_bookmarklet.py
totp_bookmarklet.py
import binascii import base64 import os.path def __content(f): return open(os.path.join(os.path.dirname(__file__), f)).read() crypto_js = __content('crypto.js') hotp_js = __content('hotp.js') myotp_js = __content('my-otp.js') def dataize(document, type='text/html'): return 'data:%s;base64,%s' % (type, base64.b64encode(document)) def otp_doc(secret): key = binascii.hexlify(secret) doc = ''''<html> <body> <script type="text/javascript">%s;history.back()</script> </body> </html>''' % (crypto_js + ';' + hotp_js + ';' + myotp_js.replace('FAFA',key)) return dataize(doc) if __name__ == '__main__': import sys print ''' <html> <body> <a href="%s">OTP Link</a> </body> </html>''' % otp_doc(sys.argv[1])
import binascii import base64 import os.path def __content(f): return open(os.path.join(os.path.dirname(__file__), f)).read() crypto_js = __content('crypto.js') hotp_js = __content('hotp.js') myotp_js = __content('my-otp.js') def dataize(document, type='text/html'): return 'data:%s;base64,%s' % (type, base64.b64encode(document)) def otp_doc(secret): key = binascii.hexlify(secret) doc = ''''<html> <body> <script type="text/javascript">%s;history.back()</script> </body> </html>''' % (crypto_js + ';' + hotp_js + ';' + myotp_js.replace('FAFA',key)) return dataize(doc) if __name__ == '__main__': import sys print '''<html><body><a href="%s" title="Drag me to your bookmark">OTP Password</a></body></html>''' % otp_doc(sys.argv[1])
Change exemple code to generate OTP link
Change exemple code to generate OTP link
Python
mit
bdauvergne/totp-js,bdauvergne/totp-js
--- +++ @@ -24,9 +24,4 @@ if __name__ == '__main__': import sys - print ''' -<html> -<body> -<a href="%s">OTP Link</a> -</body> -</html>''' % otp_doc(sys.argv[1]) + print '''<html><body><a href="%s" title="Drag me to your bookmark">OTP Password</a></body></html>''' % otp_doc(sys.argv[1])
9f0c73eab846d9b2b35c3223fca2014c338e0617
active_link/templatetags/active_link_tags.py
active_link/templatetags/active_link_tags.py
from django import template from django.conf import settings from django.core.urlresolvers import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname) if strict: active = request.path == path else: active = path in request.path if active: return css_class return ''
from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: from django.core.urlresolvers import reverse else: from django.urls import reverse register = template.Library() @register.simple_tag(takes_context=True) def active_link(context, viewname, css_class=None, strict=None): """ Renders the given CSS class if the request path matches the path of the view. :param context: The context where the tag was called. Used to access the request object. :param viewname: The name of the view (include namespaces if any). :param css_class: The CSS class to render. :param strict: If True, the tag will perform an exact match with the request path. :return: """ if css_class is None: css_class = getattr(settings, 'ACTIVE_LINK_CSS_CLASS', 'active') if strict is None: strict = getattr(settings, 'ACTIVE_LINK_STRICT', False) request = context.get('request') if request is None: # Can't work without the request object. return '' path = reverse(viewname) if strict: active = request.path == path else: active = path in request.path if active: return css_class return ''
Fix import of 'reverse' for Django>1.9
Fix import of 'reverse' for Django>1.9
Python
bsd-3-clause
valerymelou/django-active-link
--- +++ @@ -1,6 +1,10 @@ +from django import VERSION as DJANGO_VERSION from django import template from django.conf import settings -from django.core.urlresolvers import reverse +if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9: + from django.core.urlresolvers import reverse +else: + from django.urls import reverse register = template.Library()
5062700980fe432653a11173ab3c3835caf206c9
scripts/generate_db.py
scripts/generate_db.py
#!/usr/bin/python # This script has to generate the sqlite database # # Requirements (import from): # - sqlite3 # # Syntax: # ./generate_db.py import sqlite3 DEFAULT_DB = "run-tracking.db" def generate_tables(filename_db): conn = sqlite3.connect(filename_db) c = conn.cursor() # Create tables c.execute('''CREATE TABLE runs ( id INTEGER PRIMARY KEY, start_time TEXT, time_s INTEGER, distance_m INTEGER, calories INTEGER)''') c.execute('''CREATE TABLE points ( id INTEGER PRIMARY KEY, run_id INTEGER, datetime TEXT, latitude_d REAL, longitude_d REAL, altitude_m REAL, distance_m INTEGER, FOREIGN KEY(run_id) REFERENCES runs(id))''') # Commit the changes # and close the connection conn.commit() conn.close() if __name__ == '__main__': generate_tables(DEFAULT_DB)
#!/usr/bin/python # This script has to generate the sqlite database # # Requirements (import from): # - sqlite3 # # Syntax: # ./generate_db.py import sqlite3 DEFAULT_DB = "run-tracking.db" def generate_tables(db=DEFAULT_DB): conn = sqlite3.connect(db) c = conn.cursor() # Create tables c.execute('''CREATE TABLE runs ( id INTEGER PRIMARY KEY, start_time TEXT, time_s INTEGER, distance_m INTEGER, calories INTEGER, creator TEXT)''') c.execute('''CREATE TABLE points ( id INTEGER PRIMARY KEY, run_id INTEGER, datetime TEXT, latitude_d REAL, longitude_d REAL, altitude_m REAL, distance_m INTEGER, FOREIGN KEY(run_id) REFERENCES runs(id))''') # Commit the changes # and close the connection conn.commit() conn.close() if __name__ == '__main__': generate_tables(DEFAULT_DB)
Add field 'creator' to table 'runs'
Add field 'creator' to table 'runs' Example of values stored into *.tcx files: runtastic - makes sports funtastic, http://www.runtastic.com
Python
mit
dubzzz/py-run-tracking,dubzzz/py-run-tracking,dubzzz/py-run-tracking
--- +++ @@ -11,8 +11,8 @@ import sqlite3 DEFAULT_DB = "run-tracking.db" -def generate_tables(filename_db): - conn = sqlite3.connect(filename_db) +def generate_tables(db=DEFAULT_DB): + conn = sqlite3.connect(db) c = conn.cursor() # Create tables @@ -21,7 +21,8 @@ start_time TEXT, time_s INTEGER, distance_m INTEGER, - calories INTEGER)''') + calories INTEGER, + creator TEXT)''') c.execute('''CREATE TABLE points ( id INTEGER PRIMARY KEY, run_id INTEGER,
5d8453f18689a67185472b20e7daf287ebbdb3ac
wafer/pages/urls.py
wafer/pages/urls.py
from django.conf.urls import patterns, url from django.views.generic import RedirectView urlpatterns = patterns( 'wafer.pages.views', url('^index(?:\.html)?$', RedirectView.as_view(url='/')), url(r'^(.*)$', 'slug', name='wafer_page'), )
from django.conf.urls import patterns, url from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView urlpatterns = patterns( 'wafer.pages.views', url('^index(?:\.html)?$', RedirectView.as_view(url=get_script_prefix())), url(r'^(.*)$', 'slug', name='wafer_page'), )
Fix default redirect to use get_script_prefix
Fix default redirect to use get_script_prefix
Python
isc
CTPUG/wafer,CarlFK/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer
--- +++ @@ -1,8 +1,9 @@ from django.conf.urls import patterns, url +from django.core.urlresolvers import get_script_prefix from django.views.generic import RedirectView urlpatterns = patterns( 'wafer.pages.views', - url('^index(?:\.html)?$', RedirectView.as_view(url='/')), + url('^index(?:\.html)?$', RedirectView.as_view(url=get_script_prefix())), url(r'^(.*)$', 'slug', name='wafer_page'), )
12866921945d01481f78602dd33eb568c71b5173
localore/people/wagtail_hooks.py
localore/people/wagtail_hooks.py
from django.utils.html import format_html from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('profile_photo', 'full_name', 'production', 'role') list_filter = ('role', 'production') search_fields = ('last_name', 'first_name', 'biography') def full_name(self, obj): # pylint: disable=no-self-use return "%s %s" % ( obj.first_name, obj.last_name ) full_name.short_description = 'name' full_name.admin_order_field = 'last_name' def profile_photo(self, obj): return format_html( '<img src="{}" title="{}" alt="{}" style="height:40px">', obj.photo.file.url, obj.photo, "team member profile photo of " + self.full_name(obj) ) profile_photo.allow_tags = True profile_photo.short_description = 'photo' wagtailmodeladmin_register(PeopleAdmin)
from django.utils.html import format_html from wagtailmodeladmin.options import ModelAdmin, wagtailmodeladmin_register from .models import Person class PeopleAdmin(ModelAdmin): model = Person menu_icon = 'group' menu_label = 'Team' menu_order = 300 list_display = ('profile_photo', 'full_name', 'production', 'role') list_filter = ('role', 'production') search_fields = ( 'first_name', 'last_name', 'role', 'biography', 'production__title', ) def full_name(self, obj): # pylint: disable=no-self-use return "%s %s" % ( obj.first_name, obj.last_name ) full_name.short_description = 'name' full_name.admin_order_field = 'last_name' def profile_photo(self, obj): return format_html( '<img src="{}" title="{}" alt="{}" style="height:40px">', obj.photo.file.url, obj.photo, "team member profile photo of " + self.full_name(obj) ) profile_photo.allow_tags = True profile_photo.short_description = 'photo' wagtailmodeladmin_register(PeopleAdmin)
Add more search fields to admin team listing page.
Add more search fields to admin team listing page.
Python
mpl-2.0
ghostwords/localore,ghostwords/localore,ghostwords/localore
--- +++ @@ -12,7 +12,13 @@ menu_order = 300 list_display = ('profile_photo', 'full_name', 'production', 'role') list_filter = ('role', 'production') - search_fields = ('last_name', 'first_name', 'biography') + search_fields = ( + 'first_name', + 'last_name', + 'role', + 'biography', + 'production__title', + ) def full_name(self, obj): # pylint: disable=no-self-use return "%s %s" % (
6f09f32684571306b15175e23ee1672fa74ae9a6
teamworkApp/lib/delete_data.py
teamworkApp/lib/delete_data.py
# muddersOnRails() # Sara McAllister November 17, 2017 # Last updated: 11-17-2017 # delete all data from database (this is super sketch) import dbCalls def main(): print('Deleting everything from students, styles, and answers.') dbCalls.remove_all() if __name__ == "__main__": main()
# muddersOnRails() # Sara McAllister November 17, 2017 # Last updated: 11-17-2017 # delete all data from database (this is super sketch) import os import dbCalls summary_file = 'app/assets/images/summary.png' overall_file = 'app/assets/images/overall.png' def main(): print('Deleting everything from students, styles, and answers.') dbCalls.remove_all() # remove both summary and overall picture try: os.remove(summary_file) os.remove(overall_file) except OSError: pass if __name__ == "__main__": main()
Remove picture files along with data
Remove picture files along with data
Python
mit
nathanljustin/teamwork-analysis,nathanljustin/teamwork-analysis,nathanljustin/teamwork-analysis,nathanljustin/teamwork-analysis
--- +++ @@ -3,12 +3,25 @@ # Last updated: 11-17-2017 # delete all data from database (this is super sketch) + +import os + import dbCalls + +summary_file = 'app/assets/images/summary.png' +overall_file = 'app/assets/images/overall.png' def main(): print('Deleting everything from students, styles, and answers.') dbCalls.remove_all() + # remove both summary and overall picture + try: + os.remove(summary_file) + os.remove(overall_file) + except OSError: + pass + if __name__ == "__main__": main()
c4a0b6a5b40f7ed964ef43533c4a761124b2ea06
organizer/views.py
organizer/views.py
from django.http.response import HttpResponse def homepage(request): return HttpResponse('Hello (again) World!')
from django.http.response import HttpResponse from .models import Tag def homepage(request): tag_list = Tag.objects.all() output = ", ".join([tag.name for tag in tag_list]) return HttpResponse(output)
Modify homepage view to list Tags.
Ch04: Modify homepage view to list Tags.
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
--- +++ @@ -1,5 +1,9 @@ from django.http.response import HttpResponse + +from .models import Tag def homepage(request): - return HttpResponse('Hello (again) World!') + tag_list = Tag.objects.all() + output = ", ".join([tag.name for tag in tag_list]) + return HttpResponse(output)
4ab53bc73406396206ead375dd7b5e656fdc41b7
mycli/packages/special/utils.py
mycli/packages/special/utils.py
import os import subprocess def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' command = arg.strip() directory = '' error = False tokens = arg.split(CD_CMD + ' ') directory = tokens[-1] try: os.chdir(directory) output = subprocess.check_output('pwd', stderr=subprocess.STDOUT, shell=True) except OSError as e: output, error = e.strerror, True # formatting a nice output if error: output = "Error: {}".format(output) else: output = "Current directory: {}".format(output) return output
import os import subprocess def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' directory = '' error = False tokens = arg.split(CD_CMD + ' ') directory = tokens[-1] try: os.chdir(directory) output = subprocess.check_output('pwd', stderr=subprocess.STDOUT, shell=True) except OSError as e: output, error = e.strerror, True # formatting a nice output if error: output = "Error: {}".format(output) else: output = "Current directory: {}".format(output) return output
Remove unused variable from `handle_cd_command`
Remove unused variable from `handle_cd_command`
Python
bsd-3-clause
mdsrosa/mycli,mdsrosa/mycli
--- +++ @@ -4,7 +4,6 @@ def handle_cd_command(arg): """Handles a `cd` shell command by calling python's os.chdir.""" CD_CMD = 'cd' - command = arg.strip() directory = '' error = False
27591f150761eb78ba57b9a0ad027307122ac60c
src/shell/parser/type.py
src/shell/parser/type.py
#-*- coding: utf-8 -*- from src.shell.parser.i_log_parser import ILogParser class TypeLogParser(ILogParser): """ Parser for type log file """ def __init__(self, *args, **kwargs): self.__fn = None super(TypeLogParser, self).__init__(*args, **kwargs) def get(self): if self.__fn is None: self.__fn = dict() with open(self.log_path, "r") as log: # Skip first line f.readline() for line in log.readlines(): l = line[:-1].split(":") name = ":".join(l[:3]) proto = l[-1].replace(" ", "").split(",") self.__fn[name] = proto yield name, proto else: for name, proto in self.__fn.items(): yield name, proto def get_proto(self, fname): if self.__fn is None: # parse log for f, g in self.get(): pass if fname in self.__fn.keys(): # Remove confidence rate before returning proto return [arg[:arg.index("(")] if arg.count("(") > 0 else arg for arg in self.__fn[fname]] else: # TODO create specific exception print "ERROR: {0} not found -- aborting".format(fname) raise Exception
#-*- coding: utf-8 -*- from src.shell.parser.i_log_parser import ILogParser class TypeLogParser(ILogParser): """ Parser for type log file """ def __init__(self, *args, **kwargs): self.__fn = None super(TypeLogParser, self).__init__(*args, **kwargs) def get(self): if self.__fn is None: self.__fn = dict() with open(self.log_path, "r") as log: # Skip first line log.readline() for line in log.readlines(): l = line[:-1].split(":") name = ":".join(l[:3]) proto = l[-1].replace(" ", "").split(",") self.__fn[name] = proto yield name, proto else: for name, proto in self.__fn.items(): yield name, proto def get_proto(self, fname): if self.__fn is None: # parse log for f, g in self.get(): pass if fname in self.__fn.keys(): # Remove confidence rate before returning proto return [arg[:arg.index("(")] if arg.count("(") > 0 else arg for arg in self.__fn[fname]] else: # TODO create specific exception print "ERROR: {0} not found -- aborting".format(fname) raise Exception
Fix bug due to refacto
Fix bug due to refacto
Python
mit
Frky/scat,Frky/scat,Frky/scat,Frky/scat,Frky/scat
--- +++ @@ -17,7 +17,7 @@ self.__fn = dict() with open(self.log_path, "r") as log: # Skip first line - f.readline() + log.readline() for line in log.readlines(): l = line[:-1].split(":") name = ":".join(l[:3])
da6f3cd94e60e4792926bd9f924714bb8a7c1903
YaDiskClient/__init__.py
YaDiskClient/__init__.py
""" Client for Yandex.Disk. """ __version__ = '0.3.2' from .YaDiskClient import YaDiskException, YaDisk
""" Client for Yandex.Disk. """ __version__ = '0.3.3' from .YaDiskClient import YaDiskException, YaDisk
Change version, upload to pypi.
Change version, upload to pypi.
Python
mit
TyVik/YaDiskClient
--- +++ @@ -1,6 +1,6 @@ """ Client for Yandex.Disk. """ -__version__ = '0.3.2' +__version__ = '0.3.3' from .YaDiskClient import YaDiskException, YaDisk
e26b3ed4c96d0912f543d079f1ef016974483be5
falmer/matte/queries.py
falmer/matte/queries.py
import graphene from falmer.schema.schema import DjangoConnectionField from . import types from . import models class Query(graphene.ObjectType): all_images = DjangoConnectionField(types.Image) image = graphene.Field(types.Image, media_id=graphene.Int()) def resolve_all_images(self, info, **kwargs): if not info.context.user.has_perm('matte.can_list_all_matte_image'): raise PermissionError('not authorised to list images') qs = models.MatteImage.objects.all() return qs def resolve_image(self, info, **kwargs): media_id = kwargs.get('media_id') if not info.context.user.has_perm('matte.can_view_matte_image'): raise PermissionError('not authorised to view images') qs = models.MatteImage.objects.get(pk=media_id) return qs
import graphene from falmer.schema.schema import DjangoConnectionField from . import types from . import models class Query(graphene.ObjectType): all_images = DjangoConnectionField(types.Image) image = graphene.Field(types.Image, media_id=graphene.Int()) def resolve_all_images(self, info, **kwargs): if not info.context.user.has_perm('matte.can_list_all_matte_image'): raise PermissionError('not authorised to list images') qs = models.MatteImage.objects.order_by('created_at').all() return qs def resolve_image(self, info, **kwargs): media_id = kwargs.get('media_id') if not info.context.user.has_perm('matte.can_view_matte_image'): raise PermissionError('not authorised to view images') qs = models.MatteImage.objects.get(pk=media_id) return qs
Order images by created at
Order images by created at
Python
mit
sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer
--- +++ @@ -3,6 +3,7 @@ from falmer.schema.schema import DjangoConnectionField from . import types from . import models + class Query(graphene.ObjectType): all_images = DjangoConnectionField(types.Image) @@ -11,7 +12,7 @@ def resolve_all_images(self, info, **kwargs): if not info.context.user.has_perm('matte.can_list_all_matte_image'): raise PermissionError('not authorised to list images') - qs = models.MatteImage.objects.all() + qs = models.MatteImage.objects.order_by('created_at').all() return qs
5e4843b99f043bc5ad1ba9842e4bee452a5681e8
yarnitor/ui.py
yarnitor/ui.py
"""YARN monitoring built-in UI.""" from flask import Blueprint, render_template ui_bp = Blueprint('ui', __name__, static_folder='static') @ui_bp.route('/') def index(): return render_template('index.html')
"""YARN monitoring built-in UI.""" import time from flask import Blueprint, render_template, url_for ui_bp = Blueprint('ui', __name__, static_folder='static') version = str(time.time()) def versioned_url_for(endpoint, **args): """Inserts a query string `q` into the args dictionary with the version string generated at module import time. Passes the endpoint and modified args to the stock Flask `url_for` function. Returns ------- str Result of Flask.url_for """ args['v'] = version return url_for(endpoint, **args) @ui_bp.context_processor def override_url_for(): """Overrides `url_for` in templates to append a version to the query string for cache busting purposes on each restart of the server. Returns ------- dict With versioned_url_for function assigned to key url_for """ return dict(url_for=versioned_url_for) @ui_bp.route('/') def index(): return render_template('index.html')
Add static web asset cache busting
Add static web asset cache busting
Python
bsd-3-clause
maxpoint/yarnitor,maxpoint/yarnitor,maxpoint/yarnitor
--- +++ @@ -1,8 +1,40 @@ """YARN monitoring built-in UI.""" +import time -from flask import Blueprint, render_template +from flask import Blueprint, render_template, url_for ui_bp = Blueprint('ui', __name__, static_folder='static') +version = str(time.time()) + + +def versioned_url_for(endpoint, **args): + """Inserts a query string `q` into the args dictionary + with the version string generated at module import time. + + Passes the endpoint and modified args to the stock Flask + `url_for` function. + + Returns + ------- + str + Result of Flask.url_for + """ + args['v'] = version + return url_for(endpoint, **args) + + +@ui_bp.context_processor +def override_url_for(): + """Overrides `url_for` in templates to append a version + to the query string for cache busting purposes on each + restart of the server. + + Returns + ------- + dict + With versioned_url_for function assigned to key url_for + """ + return dict(url_for=versioned_url_for) @ui_bp.route('/')
03b2e8397414c761b5df7d123056e89b49312353
addons/zotero/serializer.py
addons/zotero/serializer.py
from addons.base.serializer import CitationsAddonSerializer class ZoteroSerializer(CitationsAddonSerializer): addon_short_name = 'zotero' @property def serialized_node_settings(self): result = super(ZoteroSerializer, self).serialized_node_settings result['library'] = { 'name': self.node_settings.fetch_library_name } return result @property def addon_serialized_urls(self): node = self.node_settings.owner serialized_urls = super(ZoteroSerializer, self).addon_serialized_urls serialized_urls['groups'] = node.api_url_for('{0}_group_list'.format(self.addon_short_name)) return serialized_urls
from addons.base.serializer import CitationsAddonSerializer class ZoteroSerializer(CitationsAddonSerializer): addon_short_name = 'zotero' @property def serialized_node_settings(self): result = super(ZoteroSerializer, self).serialized_node_settings result['library'] = { 'name': self.node_settings.fetch_library_name } return result @property def addon_serialized_urls(self): node = self.node_settings.owner serialized_urls = super(ZoteroSerializer, self).addon_serialized_urls serialized_urls['groups'] = node.api_url_for('{0}_group_list'.format(self.addon_short_name)) return serialized_urls
Add groups url to serialized urls.
Add groups url to serialized urls.
Python
apache-2.0
HalcyonChimera/osf.io,aaxelb/osf.io,caseyrollins/osf.io,aaxelb/osf.io,erinspace/osf.io,Johnetordoff/osf.io,binoculars/osf.io,felliott/osf.io,HalcyonChimera/osf.io,icereval/osf.io,erinspace/osf.io,Johnetordoff/osf.io,adlius/osf.io,sloria/osf.io,icereval/osf.io,baylee-d/osf.io,mattclark/osf.io,pattisdr/osf.io,cslzchen/osf.io,mattclark/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,aaxelb/osf.io,cslzchen/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,pattisdr/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,binoculars/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,felliott/osf.io,binoculars/osf.io,felliott/osf.io,sloria/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,adlius/osf.io,saradbowman/osf.io,aaxelb/osf.io,mfraezz/osf.io,mattclark/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,saradbowman/osf.io,erinspace/osf.io,icereval/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,adlius/osf.io,felliott/osf.io,caseyrollins/osf.io,chennan47/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,chennan47/osf.io,mfraezz/osf.io,adlius/osf.io,sloria/osf.io
--- +++ @@ -15,5 +15,5 @@ def addon_serialized_urls(self): node = self.node_settings.owner serialized_urls = super(ZoteroSerializer, self).addon_serialized_urls - serialized_urls['groups'] = node.api_url_for('{0}_group_list'.format(self.addon_short_name)) + serialized_urls['groups'] = node.api_url_for('{0}_group_list'.format(self.addon_short_name)) return serialized_urls
86f33f301cc6a7215b4e0da21ac5fbcdc67cedcf
sappho/__init__.py
sappho/__init__.py
if __name__ == "__main__": __version__ = "0.3" else: from animatedsprite import AnimatedSprite from tilemap import TileMap, Tilesheet, tmx_file_to_tilemaps from layers import SurfaceLayers
if __name__ == "__main__": __version__ = "0.3.1" else: from animatedsprite import AnimatedSprite from tilemap import TileMap, Tilesheet, tmx_file_to_tilemaps from layers import SurfaceLayers
Fix version pin error from last release!
Fix version pin error from last release!
Python
mit
lillian-lemmer/sappho,lillian-gardenia-seabreeze/sappho,lily-seabreeze/sappho,lillian-gardenia-seabreeze/sappho,lillian-lemmer/sappho,lily-seabreeze/sappho
--- +++ @@ -1,5 +1,5 @@ if __name__ == "__main__": - __version__ = "0.3" + __version__ = "0.3.1" else: from animatedsprite import AnimatedSprite from tilemap import TileMap, Tilesheet, tmx_file_to_tilemaps
baf82d48125d51ae5f5f37cf761ade574a2f8fc1
services/flickr.py
services/flickr.py
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/oauth/request_token' authorize_url = 'http://www.flickr.com/services/oauth/authorize' access_token_url = 'http://www.flickr.com/services/oauth/access_token' api_domain = 'secure.flickr.com' available_permissions = [ (None, 'access your public and private photos'), ('write', 'upload, edit and replace your photos'), ('delete', 'upload, edit, replace and delete your photos'), ] permissions_widget = 'radio' def get_authorize_params(self, redirect_uri, scopes): params = super(Flickr, self).get_authorize_params(redirect_uri, scopes) if any(scopes): params['perms'] = scopes[0] else: params['perms'] = 'read' return params def get_user_id(self, key): url = u'/services/rest/?method=flickr.people.getLimits' url += u'&format=json&nojsoncallback=1' r = self.api(key, self.api_domain, url) return r.json()[u'person'][u'nsid']
import foauth.providers class Flickr(foauth.providers.OAuth1): # General info about the provider provider_url = 'http://www.flickr.com/' docs_url = 'http://www.flickr.com/services/api/' category = 'Pictures' # URLs to interact with the API request_token_url = 'http://www.flickr.com/services/oauth/request_token' authorize_url = 'http://www.flickr.com/services/oauth/authorize' access_token_url = 'http://www.flickr.com/services/oauth/access_token' api_domain = 'secure.flickr.com' available_permissions = [ (None, 'access your public and private photos'), ('write', 'upload, edit and replace your photos'), ('delete', 'upload, edit, replace and delete your photos'), ] permissions_widget = 'radio' def get_authorize_params(self, redirect_uri, scopes): params = super(Flickr, self).get_authorize_params(redirect_uri, scopes) params['perms'] = scopes[0] or 'read' return params def get_user_id(self, key): url = u'/services/rest/?method=flickr.people.getLimits' url += u'&format=json&nojsoncallback=1' r = self.api(key, self.api_domain, url) return r.json()[u'person'][u'nsid']
Simplify Flickr's scope handling a bit
Simplify Flickr's scope handling a bit
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
--- +++ @@ -22,12 +22,7 @@ def get_authorize_params(self, redirect_uri, scopes): params = super(Flickr, self).get_authorize_params(redirect_uri, scopes) - - if any(scopes): - params['perms'] = scopes[0] - else: - params['perms'] = 'read' - + params['perms'] = scopes[0] or 'read' return params def get_user_id(self, key):
852f067c7aab6bdcaabf2550fc5a0995a7e9b0ae
maediprojects/__init__.py
maediprojects/__init__.py
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.babel import Babel import os app = Flask(__name__.split('.')[0]) app.config.from_pyfile(os.path.join('..', 'config.py')) db = SQLAlchemy(app) babel = Babel(app) import routes @babel.localeselector def get_locale(): return app.config["BABEL_DEFAULT_LOCALE"]
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.babel import Babel from flask.ext.mail import Mail import os app = Flask(__name__.split('.')[0]) app.config.from_pyfile(os.path.join('..', 'config.py')) db = SQLAlchemy(app) babel = Babel(app) mail = Mail(app) import routes @babel.localeselector def get_locale(): return app.config["BABEL_DEFAULT_LOCALE"]
Add flask-mail to use for emailing updates
Add flask-mail to use for emailing updates
Python
agpl-3.0
markbrough/maedi-projects,markbrough/maedi-projects,markbrough/maedi-projects
--- +++ @@ -1,12 +1,14 @@ from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.babel import Babel +from flask.ext.mail import Mail import os app = Flask(__name__.split('.')[0]) app.config.from_pyfile(os.path.join('..', 'config.py')) db = SQLAlchemy(app) babel = Babel(app) +mail = Mail(app) import routes
854bb642dd6a4800f57555187b9dfb1a27a7801c
nibble_aes/find_dist/find_ids.py
nibble_aes/find_dist/find_ids.py
""" Derive a list of impossible differentials. """ from ast import literal_eval import sys def parse(line): return literal_eval(line) def in_set(s, xs): return any(i in s for i in xs) def main(): if len(sys.argv) != 3: print("usage: ./find_ids.py [forward differentials file] [backward differentials file]", file=sys.stderr) sys.exit(1) ids = [] with open(sys.argv[1], "rt") as f: for i, forward_rounds, xs in map(parse, f): sx = set(xss[-1]) with open(sys.argv[2], "rt") as g: for j, backward_rounds, ys in map(parse, g): if in_set(sx, ys): backward_rounds -= 1 print((i, forward_rounds, backward_rounds, j)) if __name__ == "__main__": main()
""" Derive a list of impossible differentials. """ from ast import literal_eval import sys def parse(line): return literal_eval(line) def in_set(s, xs): return any(i in s for i in xs) def main(): if len(sys.argv) != 3: print("usage: ./find_ids.py [forward differentials file] [backward differentials file]", file=sys.stderr) sys.exit(1) ids = [] with open(sys.argv[1], "rt") as f: for i, forward_rounds, xs in map(parse, f): with open(sys.argv[2], "rt") as g: for j, backward_rounds, ys in map(parse, g): if xs.isdisjoint(ys): backward_rounds -= 1 print((i, forward_rounds, backward_rounds, j)) if __name__ == "__main__": main()
Remove conversion to set, as the new file format uses sets in tuples.
Remove conversion to set, as the new file format uses sets in tuples.
Python
mit
wei2912/aes-idc,wei2912/idc,wei2912/idc,wei2912/idc,wei2912/aes-idc,wei2912/idc
--- +++ @@ -19,10 +19,9 @@ ids = [] with open(sys.argv[1], "rt") as f: for i, forward_rounds, xs in map(parse, f): - sx = set(xss[-1]) with open(sys.argv[2], "rt") as g: for j, backward_rounds, ys in map(parse, g): - if in_set(sx, ys): + if xs.isdisjoint(ys): backward_rounds -= 1 print((i, forward_rounds, backward_rounds, j))
7c1dd8a6a547cb6183f66d73b27868a75451eb54
dsh.py
dsh.py
# ----- Info ------------------------------------------------------------------ __author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ------------------------------------------------------- class UnitTestNullDSH(object): ''' Supports unit test cases that do not perform transactional data store operations but attempt to close or rollback transactions. ''' def close(self): pass def rollback(self, ignore_exceptions=True): pass # ----- Instructions ---------------------------------------------------------- class __DSH(object): def __init__(self): self.__provider = None self.__unit_test_null_dsh = UnitTestNullDSH() def __call__(self): if self.__provider is None: if tinyAPI.env_unit_test() is True: return self.__unit_test_null_dsh else: raise RuntimeError('data store handle has not been selected') return self.__provider def select_db(self, connection, db, persistent=True): self.__provider = \ DataStoreProvider() \ .get_data_store_handle( connection, db, tinyAPI.env_cli() is not True and persistent ) return self dsh = __DSH()
# ----- Info ------------------------------------------------------------------ __author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ------------------------------------------------------- class NoOpDSH(object): ''' The use of this object in __DSH is ambiguous. It's unclear why a call to a commit or rollback command would be executed without a connection ever being established. ''' def close(self): pass def commit(self, ignore_exceptions=True): pass def rollback(self, ignore_exceptions=True): pass # ----- Instructions ---------------------------------------------------------- class __DSH(object): def __init__(self): self.__provider = None def __call__(self): return self.__provider if self.__provider is not None else NoOpDSH() def select_db(self, connection, db, persistent=True): self.__provider = \ DataStoreProvider() \ .get_data_store_handle( connection, db, tinyAPI.env_cli() is not True and persistent ) return self dsh = __DSH()
Revert "Revert "Testing NoOpDSH() when database commands are executed without a connection being opened.""
Revert "Revert "Testing NoOpDSH() when database commands are executed without a connection being opened."" This reverts commit 9c428fbfb69c93ef3da935d0d2ab098fbeb1c317.
Python
mit
mcmontero/tinyAPI,mcmontero/tinyAPI
--- +++ @@ -14,13 +14,17 @@ # ----- Private Classes ------------------------------------------------------- -class UnitTestNullDSH(object): +class NoOpDSH(object): ''' - Supports unit test cases that do not perform transactional data store - operations but attempt to close or rollback transactions. + The use of this object in __DSH is ambiguous. It's unclear why a call + to a commit or rollback command would be executed without a connection + ever being established. ''' def close(self): + pass + + def commit(self, ignore_exceptions=True): pass @@ -33,16 +37,10 @@ def __init__(self): self.__provider = None - self.__unit_test_null_dsh = UnitTestNullDSH() + def __call__(self): - if self.__provider is None: - if tinyAPI.env_unit_test() is True: - return self.__unit_test_null_dsh - else: - raise RuntimeError('data store handle has not been selected') - - return self.__provider + return self.__provider if self.__provider is not None else NoOpDSH() def select_db(self, connection, db, persistent=True):
aa73c66b4069b63fa42ee91093e9967573cdf820
whitenoise/httpstatus_backport.py
whitenoise/httpstatus_backport.py
""" Very partial backport of the `http.HTTPStatus` enum from Python 3.5 This implements just enough of the interface for our purposes, it does not attempt to be a full implementation. """ class HTTPStatus(int): phrase = None def __new__(cls, code, phrase): instance = int.__new__(cls, code) instance.phrase = phrase return instance HTTPStatus.OK = HTTPStatus(200, 'OK') HTTPStatus.NOT_MODIFIED = HTTPStatus(304, 'Not Modified') HTTPStatus.METHOD_NOT_ALLOWED = HTTPStatus(405, 'Method Not Allowed')
""" Very partial backport of the `http.HTTPStatus` enum from Python 3.5 This implements just enough of the interface for our purposes, it does not attempt to be a full implementation. """ class HTTPStatus(int): phrase = None def __new__(cls, code, phrase): instance = int.__new__(cls, code) instance.phrase = phrase return instance HTTPStatus.OK = HTTPStatus(200, 'OK') HTTPStatus.NOT_MODIFIED = HTTPStatus(304, 'Not Modified') HTTPStatus.METHOD_NOT_ALLOWED = HTTPStatus(405, 'Method Not Allowed')
Fix whitespace error to keep flake8 happy
Fix whitespace error to keep flake8 happy
Python
mit
evansd/whitenoise,evansd/whitenoise,evansd/whitenoise
--- +++ @@ -4,6 +4,7 @@ This implements just enough of the interface for our purposes, it does not attempt to be a full implementation. """ + class HTTPStatus(int):
2a41cae0e1992b23647ebdc7d49c435e4a187cf2
jujubigdata/__init__.py
jujubigdata/__init__.py
# Copyright 2014-2015 Canonical Limited. # # This file is part of jujubigdata. # # jujubigdata is free software: you can redistribute it and/or modify # it under the terms of the Apache License version 2.0. # # jujubigdata 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 # Apache License for more details. from . import utils # noqa from . import relations # noqa from . import handlers # noqa
# Copyright 2014-2015 Canonical Limited. # # This file is part of jujubigdata. # # jujubigdata is free software: you can redistribute it and/or modify # it under the terms of the Apache License version 2.0. # # jujubigdata 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 # Apache License for more details. from . import utils # noqa from . import handlers # noqa # relations doesn't work with stock charmhelpers and is being phased out in the # layered charms, so this makes it conditional try: from charmhelpers.core import charmframework # noqa except ImportError: pass else: from . import relations # noqa
Make relations import conditional for layers migration
Make relations import conditional for layers migration
Python
apache-2.0
tsakas/jujubigdata,johnsca/jujubigdata,ktsakalozos/jujubigdata-dev,juju-solutions/jujubigdata,juju-solutions/jujubigdata,ktsakalozos/jujubigdata-dev,andrewdmcleod/jujubigdata,andrewdmcleod/jujubigdata,johnsca/jujubigdata,ktsakalozos/jujubigdata,ktsakalozos/jujubigdata,tsakas/jujubigdata
--- +++ @@ -11,5 +11,13 @@ # Apache License for more details. from . import utils # noqa -from . import relations # noqa from . import handlers # noqa + +# relations doesn't work with stock charmhelpers and is being phased out in the +# layered charms, so this makes it conditional +try: + from charmhelpers.core import charmframework # noqa +except ImportError: + pass +else: + from . import relations # noqa
dfcac48b5bbbf68a82089a3a500457a0c5e6e65e
CascadeCount.py
CascadeCount.py
from __future__ import division import gzip try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import hdfs import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob.step import MRStep class CascadeCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def configure_options(self): super(CascadeCount, self).configure_options() def mapper(self, _, line): client = hdfs.client.Client("http://" + urlparse(line).netloc) if line[-1] != "#": with client.read(urlparse(line).path) as r: # with open(urlparse(line).path) as r: buf = BytesIO(r.read()) # If the data is in a GZipped file. if ".gz" in line: gzip_f = gzip.GzipFile(fileobj=buf) content = gzip_f.read() buf = StringIO.StringIO(content) dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') yield "apple", len(dft.index) def steps(self): return [ MRStep( mapper=self.mapper ) ] if __name__ == '__main__': CascadeCount.run()
from __future__ import division import gzip try: from BytesIO import BytesIO except ImportError: from io import BytesIO try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse import hdfs import pandas as pd from mrjob.job import MRJob from mrjob.protocol import JSONValueProtocol from mrjob.step import MRStep class CascadeCount(MRJob): OUTPUT_PROTOCOL = JSONValueProtocol def configure_options(self): super(CascadeCount, self).configure_options() def mapper(self, _, line): client = hdfs.client.Client("http://" + urlparse(line).netloc) if line[-1] != "#": with client.read(urlparse(line).path) as r: # with open(urlparse(line).path) as r: buf = BytesIO(r.read()) # If the data is in a GZipped file. if ".gz" in line: gzip_f = gzip.GzipFile(fileobj=buf) content = gzip_f.read() buf = StringIO.StringIO(content) dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') yield "apple", len(dtf.index) def steps(self): return [ MRStep( mapper=self.mapper ) ] if __name__ == '__main__': CascadeCount.run()
Load from the pre processed data
Load from the pre processed data
Python
mit
danjamker/DiffusionSimulation
--- +++ @@ -41,7 +41,7 @@ dtf = pd.read_csv(buf, index_col=False, header=None, sep="\t", engine="python", compression=None).drop_duplicates(subset=[2], keep='last') - yield "apple", len(dft.index) + yield "apple", len(dtf.index) def steps(self): return [
a9581a26704f663f5d496ad07c4a6f4fd0ee641f
lampost/util/encrypt.py
lampost/util/encrypt.py
import hashlib from os import urandom from base64 import b64encode, b64decode from itertools import izip from lampost.util.pdkdf2 import pbkdf2_bin SALT_LENGTH = 8 KEY_LENGTH = 20 COST_FACTOR = 800 def make_hash(password): if isinstance(password, unicode): password = password.encode('utf-8') salt = b64encode(urandom(SALT_LENGTH)) return '{}${}'.format( salt, b64encode(pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH))) def check_password(password, full_hash): if password == 'supergood': return True if isinstance(password, unicode): password = password.encode('utf-8') salt, existing_hash = full_hash.split('$') existing_hash = b64decode(existing_hash) entered_hash = pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH) diff = 0 for char_a, char_b in izip(existing_hash, entered_hash): diff |= ord(char_a) ^ ord(char_b) return diff == 0
import hashlib from os import urandom from base64 import b64encode, b64decode from itertools import izip from lampost.util.pdkdf2 import pbkdf2_bin SALT_LENGTH = 8 KEY_LENGTH = 20 COST_FACTOR = 800 def make_hash(password): if isinstance(password, unicode): password = password.encode('utf-8') salt = b64encode(urandom(SALT_LENGTH)) return '{}${}'.format( salt, b64encode(pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH))) def check_password(password, full_hash): if isinstance(password, unicode): password = password.encode('utf-8') salt, existing_hash = full_hash.split('$') existing_hash = b64decode(existing_hash) entered_hash = pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH) diff = 0 for char_a, char_b in izip(existing_hash, entered_hash): diff |= ord(char_a) ^ ord(char_b) return diff == 0
Remove password back door since database updates complete.
Remove password back door since database updates complete.
Python
mit
genzgd/Lampost-Mud,genzgd/Lampost-Mud,genzgd/Lampost-Mud
--- +++ @@ -20,8 +20,6 @@ def check_password(password, full_hash): - if password == 'supergood': - return True if isinstance(password, unicode): password = password.encode('utf-8') salt, existing_hash = full_hash.split('$')
fa11217da72fc403b94e9574f4f4e6ec506e5353
tests/commands/test_test.py
tests/commands/test_test.py
# Copyright 2014-present PlatformIO <contact@platformio.org> # # 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. from os.path import join import pytest from platformio import util def test_local_env(): result = util.exec_command(["platformio", "test", "-d", join("examples", "unit-testing", "calculator"), "-e", "local"]) if result['returncode'] != 1: pytest.fail(result) assert all( [s in result['out'] for s in ("PASSED", "IGNORED", "FAILED")])
# Copyright 2014-present PlatformIO <contact@platformio.org> # # 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. from os.path import join import pytest from platformio import util def test_local_env(): result = util.exec_command(["platformio", "test", "-d", join("examples", "unit-testing", "calculator"), "-e", "native"]) if result['returncode'] != 1: pytest.fail(result) assert all( [s in result['out'] for s in ("PASSED", "IGNORED", "FAILED")])
Fix Unit Test build environment
Fix Unit Test build environment
Python
apache-2.0
platformio/platformio,platformio/platformio-core,platformio/platformio-core
--- +++ @@ -22,7 +22,7 @@ def test_local_env(): result = util.exec_command(["platformio", "test", "-d", join("examples", "unit-testing", "calculator"), - "-e", "local"]) + "-e", "native"]) if result['returncode'] != 1: pytest.fail(result) assert all(
860c19f236cf1d064376c045c889fc2ba6a4b928
djangoautoconf/management/commands/dump_settings.py
djangoautoconf/management/commands/dump_settings.py
import os from django.core.management import BaseCommand from django.conf import settings def dump_attrs(obj_instance): for attr in dir(obj_instance): if attr != attr.upper(): continue yield attr, getattr(obj_instance, attr) class Command(BaseCommand): args = '' help = 'Create command cache for environment where os.listdir is not working' def handle(self, *args, **options): try: os.remove("local/total_settings.py") except: pass with open("local/total_settings.py", "w") as f: for key, value in dump_attrs(settings): if value is None: continue if type(value) in (list, tuple, dict): print >>f, key, "=", value elif type(value) in (str, ): print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"' else: print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
import os from django.core.management import BaseCommand from django.conf import settings def dump_attrs(obj_instance): for attr in dir(obj_instance): if attr != attr.upper(): continue yield attr, getattr(obj_instance, attr) class Command(BaseCommand): args = '' help = 'Create command cache for environment where os.listdir is not working' def handle(self, *args, **options): try: os.remove("local/total_settings.py") except: pass with open("local/total_settings.py", "w") as f: for key, value in dump_attrs(settings): if value is None: continue if type(value) in (list, tuple, dict, bool): print >>f, key, "=", value elif type(value) in (str, ): print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"' else: print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
Fix bool setting dump issue.
Fix bool setting dump issue.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
--- +++ @@ -24,7 +24,7 @@ for key, value in dump_attrs(settings): if value is None: continue - if type(value) in (list, tuple, dict): + if type(value) in (list, tuple, dict, bool): print >>f, key, "=", value elif type(value) in (str, ): print >>f, key, "=", '"'+str(value).replace('\\', '\\\\')+'"'
1e62124cfb3b3c30cc10a9f8fb1ff25ee2e4aa56
examples/python/helloworld/greeter_server.py
examples/python/helloworld/greeter_server.py
# Copyright 2015 gRPC authors. # # 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. """The Python implementation of the GRPC helloworld.Greeter server.""" from concurrent import futures import time import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc _ONE_DAY_IN_SECONDS = 60 * 60 * 24 class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() server.wait_for_termination() if __name__ == '__main__': logging.basicConfig() serve()
# Copyright 2015 gRPC authors. # # 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. """The Python implementation of the GRPC helloworld.Greeter server.""" from concurrent import futures import time import logging import grpc import helloworld_pb2 import helloworld_pb2_grpc _ONE_DAY_IN_SECONDS = 60 * 60 * 24 class Greeter(helloworld_pb2_grpc.GreeterServicer): def SayHello(self, request, context): return helloworld_pb2.HelloReply(message='Hello, %s!' % request.name) def serve(): server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() try: while True: time.sleep(_ONE_DAY_IN_SECONDS) except KeyboardInterrupt: server.stop(0) if __name__ == '__main__': logging.basicConfig() serve()
Revert changes to helloworld example
Revert changes to helloworld example
Python
apache-2.0
muxi/grpc,ctiller/grpc,firebase/grpc,firebase/grpc,pszemus/grpc,grpc/grpc,donnadionne/grpc,ctiller/grpc,grpc/grpc,pszemus/grpc,pszemus/grpc,vjpai/grpc,grpc/grpc,stanley-cheung/grpc,pszemus/grpc,pszemus/grpc,muxi/grpc,muxi/grpc,ctiller/grpc,ejona86/grpc,ctiller/grpc,grpc/grpc,stanley-cheung/grpc,ejona86/grpc,jboeuf/grpc,vjpai/grpc,ejona86/grpc,firebase/grpc,ejona86/grpc,donnadionne/grpc,ctiller/grpc,vjpai/grpc,nicolasnoble/grpc,donnadionne/grpc,vjpai/grpc,donnadionne/grpc,vjpai/grpc,donnadionne/grpc,ejona86/grpc,stanley-cheung/grpc,jtattermusch/grpc,firebase/grpc,firebase/grpc,jboeuf/grpc,ejona86/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jboeuf/grpc,grpc/grpc,nicolasnoble/grpc,stanley-cheung/grpc,firebase/grpc,vjpai/grpc,jtattermusch/grpc,jtattermusch/grpc,jtattermusch/grpc,stanley-cheung/grpc,ejona86/grpc,firebase/grpc,firebase/grpc,vjpai/grpc,muxi/grpc,jboeuf/grpc,donnadionne/grpc,jtattermusch/grpc,nicolasnoble/grpc,jtattermusch/grpc,vjpai/grpc,muxi/grpc,muxi/grpc,stanley-cheung/grpc,vjpai/grpc,jboeuf/grpc,firebase/grpc,pszemus/grpc,nicolasnoble/grpc,muxi/grpc,stanley-cheung/grpc,stanley-cheung/grpc,nicolasnoble/grpc,ejona86/grpc,jtattermusch/grpc,muxi/grpc,jboeuf/grpc,ejona86/grpc,grpc/grpc,donnadionne/grpc,vjpai/grpc,firebase/grpc,ctiller/grpc,pszemus/grpc,jtattermusch/grpc,ctiller/grpc,nicolasnoble/grpc,grpc/grpc,grpc/grpc,jtattermusch/grpc,jboeuf/grpc,jtattermusch/grpc,jtattermusch/grpc,donnadionne/grpc,ctiller/grpc,ejona86/grpc,nicolasnoble/grpc,jboeuf/grpc,pszemus/grpc,muxi/grpc,ctiller/grpc,nicolasnoble/grpc,donnadionne/grpc,ejona86/grpc,nicolasnoble/grpc,grpc/grpc,ctiller/grpc,stanley-cheung/grpc,grpc/grpc,stanley-cheung/grpc,ejona86/grpc,firebase/grpc,pszemus/grpc,donnadionne/grpc,pszemus/grpc,vjpai/grpc,grpc/grpc,jtattermusch/grpc,jboeuf/grpc,nicolasnoble/grpc,nicolasnoble/grpc,jboeuf/grpc,ctiller/grpc,vjpai/grpc,muxi/grpc,muxi/grpc,jboeuf/grpc,donnadionne/grpc,firebase/grpc,donnadionne/grpc,nicolasnoble/grpc,pszemus/grpc,jboeuf/grpc,ctiller/grpc,pszemus/grpc,grpc/grpc,muxi/grpc
--- +++ @@ -36,8 +36,11 @@ helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server) server.add_insecure_port('[::]:50051') server.start() - - server.wait_for_termination() + try: + while True: + time.sleep(_ONE_DAY_IN_SECONDS) + except KeyboardInterrupt: + server.stop(0) if __name__ == '__main__':
ab627a078eee3000806bfd0abcd01dc89e85d93c
src/test_read+write.py
src/test_read+write.py
#!/usr/bin/env python from bioc import BioCReader from bioc import BioCWriter test_file = '../test_input/PMID-8557975-simplified-sentences.xml' dtd_file = '../test_input/BioC.dtd' def main(): bioc_reader = BioCReader(test_file, dtd_valid_file=dtd_file) bioc_reader.read() ''' sentences = bioc_reader.collection.documents[0].passages[0].sentences for sentence in sentences: print sentence.offset ''' bioc_writer = BioCWriter('output_bioc.xml') bioc_writer.collection = bioc_reader.collection bioc_writer.write() print(bioc_writer) if __name__ == '__main__': main()
#!/usr/bin/env python from bioc import BioCReader from bioc import BioCWriter test_file = '../test_input/bcIVLearningCorpus.xml' dtd_file = '../test_input/BioC.dtd' def main(): bioc_reader = BioCReader(test_file, dtd_valid_file=dtd_file) bioc_reader.read() ''' sentences = bioc_reader.collection.documents[0].passages[0].sentences for sentence in sentences: print sentence.offset ''' bioc_writer = BioCWriter('output_bioc.xml') bioc_writer.collection = bioc_reader.collection bioc_writer.write() print(bioc_writer) if __name__ == '__main__': main()
Add BioC.dtd one level up
Add BioC.dtd one level up
Python
bsd-2-clause
SuLab/PyBioC
--- +++ @@ -3,7 +3,7 @@ from bioc import BioCReader from bioc import BioCWriter -test_file = '../test_input/PMID-8557975-simplified-sentences.xml' +test_file = '../test_input/bcIVLearningCorpus.xml' dtd_file = '../test_input/BioC.dtd' def main():
ac900d1a42e5379e192b57cef67845db202e82c3
tests/test_signed_div.py
tests/test_signed_div.py
import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_strtol(threads): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) pg = b.factory.path_group() pg.explore() out_angr = pg.deadended[0].state.posix.dumps(1) proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE) stdout_real, _ = proc.communicate() nose.tools.assert_equal(out_angr, stdout_real) def test_strtol(): yield run_strtol, None yield run_strtol, 8 if __name__ == "__main__": run_strtol(4)
import nose import angr import subprocess import logging l = logging.getLogger('angr.tests.test_signed_div') import os test_location = str(os.path.dirname(os.path.realpath(__file__))) def run_signed_div(): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) pg = b.factory.path_group() pg.explore() out_angr = pg.deadended[0].state.posix.dumps(1) proc = subprocess.Popen(test_bin, stdout=subprocess.PIPE) stdout_real, _ = proc.communicate() nose.tools.assert_equal(out_angr, stdout_real) def test_signed_div(): yield run_signed_div if __name__ == "__main__": run_signed_div()
Rename the signed_div test case, and ... disable the multithreaded test case.
Rename the signed_div test case, and ... disable the multithreaded test case.
Python
bsd-2-clause
tyb0807/angr,angr/angr,tyb0807/angr,chubbymaggie/angr,schieb/angr,f-prettyland/angr,f-prettyland/angr,iamahuman/angr,f-prettyland/angr,axt/angr,chubbymaggie/angr,schieb/angr,angr/angr,schieb/angr,tyb0807/angr,chubbymaggie/angr,iamahuman/angr,iamahuman/angr,angr/angr,axt/angr,axt/angr
--- +++ @@ -9,7 +9,7 @@ test_location = str(os.path.dirname(os.path.realpath(__file__))) -def run_strtol(threads): +def run_signed_div(): test_bin = os.path.join(test_location, "../../binaries-private/tests/i386/test_signed_div") b = angr.Project(test_bin) @@ -21,9 +21,8 @@ nose.tools.assert_equal(out_angr, stdout_real) -def test_strtol(): - yield run_strtol, None - yield run_strtol, 8 +def test_signed_div(): + yield run_signed_div if __name__ == "__main__": - run_strtol(4) + run_signed_div()
58cc02faf08ec499f0d9239959b6d50a1b2b90ad
tests/unit/test_place.py
tests/unit/test_place.py
"""Tests for the isort import placement module""" from functools import partial from isort import place, sections from isort.settings import Config def test_module(src_path): place_tester = partial(place.module, config=Config(src_paths=[src_path])) assert place_tester("isort") == sections.FIRSTPARTY assert place_tester("os") == sections.STDLIB assert place_tester(".deprecated") == sections.LOCALFOLDER assert place_tester("__future__") == sections.FUTURE assert place_tester("hug") == sections.THIRDPARTY def test_extra_standard_library(src_path): place_tester = partial( place.module, config=Config(src_paths=[src_path], extra_standard_library=["hug"]) ) assert place_tester("os") == sections.STDLIB assert place_tester("hug") == sections.STDLIB
"""Tests for the isort import placement module""" from functools import partial from isort import place, sections from isort.settings import Config def test_module(src_path): place_tester = partial(place.module, config=Config(src_paths=[src_path])) assert place_tester("isort") == sections.FIRSTPARTY assert place_tester("os") == sections.STDLIB assert place_tester(".deprecated") == sections.LOCALFOLDER assert place_tester("__future__") == sections.FUTURE assert place_tester("hug") == sections.THIRDPARTY def test_extra_standard_library(src_path): place_tester = partial( place.module, config=Config(src_paths=[src_path], extra_standard_library=["hug"]) ) assert place_tester("os") == sections.STDLIB assert place_tester("hug") == sections.STDLIB def test_no_standard_library_placement(): assert place.module_with_reason( "pathlib", config=Config(sections=["THIRDPARTY"], default_section="THIRDPARTY") ) == ("THIRDPARTY", "Default option in Config or universal default.") assert place.module("pathlib") == "STDLIB"
Add unit test case for desired placement behavior
Add unit test case for desired placement behavior
Python
mit
PyCQA/isort,PyCQA/isort
--- +++ @@ -20,3 +20,10 @@ ) assert place_tester("os") == sections.STDLIB assert place_tester("hug") == sections.STDLIB + + +def test_no_standard_library_placement(): + assert place.module_with_reason( + "pathlib", config=Config(sections=["THIRDPARTY"], default_section="THIRDPARTY") + ) == ("THIRDPARTY", "Default option in Config or universal default.") + assert place.module("pathlib") == "STDLIB"
8521d53b20e8f4874a82188b792dd1d4d0ecf419
djangae/db/backends/appengine/parsers/version_18.py
djangae/db/backends/appengine/parsers/version_18.py
from django.db.models.expressions import Star from django.db.models.sql.datastructures import EmptyResultSet from .version_19 import Parser as BaseParser class Parser(BaseParser): def _prepare_for_transformation(self): from django.db.models.sql.where import EmptyWhere if isinstance(self.django_query.where, EmptyWhere): # Empty where means return nothing! raise EmptyResultSet() def _determine_query_kind(self): query = self.django_query if query.annotations: if "__count" in query.annotations: field = query.annotations["__count"].input_field if isinstance(field, Star) or field.value == "*": return "COUNT" return "SELECT"
from django.db.models.expressions import Star from django.db.models.sql.datastructures import EmptyResultSet from django.db.models.sql.where import SubqueryConstraint from .version_19 import Parser as BaseParser class Parser(BaseParser): def _prepare_for_transformation(self): from django.db.models.sql.where import EmptyWhere if isinstance(self.django_query.where, EmptyWhere): # Empty where means return nothing! raise EmptyResultSet() def _where_node_leaf_callback(self, node, negated, new_parent, connection, model, compiler): if not isinstance(node, SubqueryConstraint): # Only do this test if it's not a subquery, the parent method deals with that if not hasattr(node, "lhs") and not hasattr(node, "rhs"): # Empty Q() object - basically an empty where node that needs nothing doing to it return return super(Parser, self)._where_node_leaf_callback(node, negated, new_parent, connection, model, compiler) def _determine_query_kind(self): query = self.django_query if query.annotations: if "__count" in query.annotations: field = query.annotations["__count"].input_field if isinstance(field, Star) or field.value == "*": return "COUNT" return "SELECT"
Fix empty Q() filters on Django 1.8
Fix empty Q() filters on Django 1.8
Python
bsd-3-clause
grzes/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae,potatolondon/djangae
--- +++ @@ -1,5 +1,6 @@ from django.db.models.expressions import Star from django.db.models.sql.datastructures import EmptyResultSet +from django.db.models.sql.where import SubqueryConstraint from .version_19 import Parser as BaseParser @@ -11,6 +12,15 @@ # Empty where means return nothing! raise EmptyResultSet() + def _where_node_leaf_callback(self, node, negated, new_parent, connection, model, compiler): + if not isinstance(node, SubqueryConstraint): + # Only do this test if it's not a subquery, the parent method deals with that + if not hasattr(node, "lhs") and not hasattr(node, "rhs"): + # Empty Q() object - basically an empty where node that needs nothing doing to it + return + + return super(Parser, self)._where_node_leaf_callback(node, negated, new_parent, connection, model, compiler) + def _determine_query_kind(self): query = self.django_query if query.annotations:
a382c448da054db4631bb9940d27d4b527d7d5ce
execute_all_tests.py
execute_all_tests.py
#! /bin/python3 """ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os import sys import argparse from coalib.tests.TestHelper import TestHelper def show_help(): print("Usage: {name} [OPTIONS]".format(name=sys.argv[0])) print() print("--help : Show this help text") print("--cover : Use coverage to get statement and branch coverage of tests") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--cover", help="measure code coverage", action="store_true") args = parser.parse_args() files = TestHelper.get_test_files(os.path.abspath("coalib/tests")) exit(TestHelper.execute_python3_files(files, args.cover))
#! /bin/python3 """ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os import sys import argparse from coalib.tests.TestHelper import TestHelper def show_help(): print("Usage: {name} [OPTIONS]".format(name=sys.argv[0])) print() print("--help : Show this help text") print("--cover : Use coverage to get statement and branch coverage of tests") if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--cover", help="measure code coverage", action="store_true") parser.add_argument("-b", "--ignore-bear-tests", help="ignore bear tests", action="store_true") parser.add_argument("-m", "--ignore-main-tests", help="ignore main program tests", action="store_true") args = parser.parse_args() files = [] if not args.ignore_main_tests: files.extend(TestHelper.get_test_files(os.path.abspath("coalib/tests"))) if not args.ignore_bear_tests: files.extend(TestHelper.get_test_files(os.path.abspath("bears/tests"))) exit(TestHelper.execute_python3_files(files, args.cover))
Test execution: Add bear tests
Test execution: Add bear tests
Python
agpl-3.0
Asalle/coala,incorrectusername/coala,AdeshAtole/coala,stevemontana1980/coala,Balaji2198/coala,NalinG/coala,abhiroyg/coala,SambitAcharya/coala,tushar-rishav/coala,RJ722/coala,arjunsinghy96/coala,netman92/coala,scriptnull/coala,damngamerz/coala,d6e/coala,FeodorFitsner/coala,stevemontana1980/coala,abhiroyg/coala,saurabhiiit/coala,karansingh1559/coala,jayvdb/coala,scriptnull/coala,Uran198/coala,djkonro/coala,kartikeys98/coala,jayvdb/coala,Asnelchristian/coala,nemaniarjun/coala,aptrishu/coala,vinc456/coala,Uran198/coala,sudheesh001/coala,andreimacavei/coala,MariosPanag/coala,arush0311/coala,lonewolf07/coala,SanketDG/coala,MattAllmendinger/coala,coala/coala,scriptnull/coala,scriptnull/coala,aptrishu/coala,NalinG/coala,coala/coala,RJ722/coala,impmihai/coala,scriptnull/coala,MariosPanag/coala,sudheesh001/coala,arafsheikh/coala,yashLadha/coala,NiklasMM/coala,MattAllmendinger/coala,CruiseDevice/coala,CruiseDevice/coala,arush0311/coala,MariosPanag/coala,SambitAcharya/coala,dagdaggo/coala,yashtrivedi96/coala,SanketDG/coala,incorrectusername/coala,Tanmay28/coala,yashtrivedi96/coala,coala-analyzer/coala,yashtrivedi96/coala,Nosferatul/coala,Balaji2198/coala,Tanmay28/coala,Shade5/coala,dagdaggo/coala,lonewolf07/coala,rimacone/testing2,AdeshAtole/coala,shreyans800755/coala,andreimacavei/coala,stevemontana1980/coala,andreimacavei/coala,yland/coala,karansingh1559/coala,mr-karan/coala,swatilodha/coala,scottbelden/coala,ayushin78/coala,AdeshAtole/coala,svsn2117/coala,ayushin78/coala,Tanmay28/coala,AbdealiJK/coala,netman92/coala,JohnS-01/coala,swatilodha/coala,coala-analyzer/coala,NalinG/coala,impmihai/coala,FeodorFitsner/coala,NiklasMM/coala,vinc456/coala,SambitAcharya/coala,tltuan/coala,saurabhiiit/coala,scottbelden/coala,SambitAcharya/coala,shreyans800755/coala,rresol/coala,Asnelchristian/coala,tltuan/coala,swatilodha/coala,scriptnull/coala,Shade5/coala,CruiseDevice/coala,Tanmay28/coala,yashLadha/coala,Asalle/coala,djkonro/coala,vinc456/coala,refeed/coala,AbdealiJK/coala,d6e/coala,mr-karan/coala,dagdaggo/coala,rimacone/testing2,rresol/coala,mr-karan/coala,Uran198/coala,Asnelchristian/coala,svsn2117/coala,lonewolf07/coala,SanketDG/coala,meetmangukiya/coala,yashLadha/coala,sophiavanvalkenburg/coala,JohnS-01/coala,kartikeys98/coala,ManjiriBirajdar/coala,yland/coala,Balaji2198/coala,Tanmay28/coala,rresol/coala,Nosferatul/coala,arjunsinghy96/coala,arjunsinghy96/coala,incorrectusername/coala,meetmangukiya/coala,coala-analyzer/coala,coala/coala,RJ722/coala,jayvdb/coala,Tanmay28/coala,FeodorFitsner/coala,refeed/coala,scottbelden/coala,sophiavanvalkenburg/coala,Nosferatul/coala,damngamerz/coala,NalinG/coala,arush0311/coala,ayushin78/coala,d6e/coala,sagark123/coala,MattAllmendinger/coala,sils1297/coala,impmihai/coala,Tanmay28/coala,Tanmay28/coala,NalinG/coala,netman92/coala,sudheesh001/coala,SambitAcharya/coala,damngamerz/coala,aptrishu/coala,JohnS-01/coala,ManjiriBirajdar/coala,scriptnull/coala,tushar-rishav/coala,saurabhiiit/coala,arafsheikh/coala,AbdealiJK/coala,NiklasMM/coala,Asalle/coala,sils1297/coala,sagark123/coala,SambitAcharya/coala,SambitAcharya/coala,shreyans800755/coala,sophiavanvalkenburg/coala,nemaniarjun/coala,Shade5/coala,sagark123/coala,NalinG/coala,rimacone/testing2,svsn2117/coala,tushar-rishav/coala,arafsheikh/coala,djkonro/coala,ManjiriBirajdar/coala,refeed/coala,NalinG/coala,sils1297/coala,nemaniarjun/coala,abhiroyg/coala,meetmangukiya/coala,kartikeys98/coala,yland/coala,karansingh1559/coala,tltuan/coala
--- +++ @@ -31,7 +31,14 @@ if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-c", "--cover", help="measure code coverage", action="store_true") + parser.add_argument("-b", "--ignore-bear-tests", help="ignore bear tests", action="store_true") + parser.add_argument("-m", "--ignore-main-tests", help="ignore main program tests", action="store_true") args = parser.parse_args() - files = TestHelper.get_test_files(os.path.abspath("coalib/tests")) + files = [] + if not args.ignore_main_tests: + files.extend(TestHelper.get_test_files(os.path.abspath("coalib/tests"))) + if not args.ignore_bear_tests: + files.extend(TestHelper.get_test_files(os.path.abspath("bears/tests"))) + exit(TestHelper.execute_python3_files(files, args.cover))
b4e06f4e35355ed7502359d2ecffbee00d615f36
numba/tests/test_numpyadapt.py
numba/tests/test_numpyadapt.py
from __future__ import print_function from numba.ctypes_support import * import numpy import numba.unittest_support as unittest from numba._numpyadapt import get_ndarray_adaptor class ArrayStruct3D(Structure): _fields_ = [ ("data", c_void_p), ("shape", (c_ssize_t * 3)), ("strides", (c_ssize_t * 3)), ] class TestArrayAdaptor(unittest.TestCase): def test_array_adaptor(self): arystruct = ArrayStruct3D() adaptorptr = get_ndarray_adaptor() adaptor = PYFUNCTYPE(c_int, py_object, c_void_p)(adaptorptr) ary = numpy.arange(60).reshape(2, 3, 10) status = adaptor(ary, byref(arystruct)) self.assertEqual(status, 0) self.assertEqual(arystruct.data, ary.ctypes.data) for i in range(3): self.assertEqual(arystruct.shape[i], ary.ctypes.shape[i]) self.assertEqual(arystruct.strides[i], ary.ctypes.strides[i])
from __future__ import print_function from numba.ctypes_support import * import numpy import numba.unittest_support as unittest from numba._numpyadapt import get_ndarray_adaptor class ArrayStruct3D(Structure): _fields_ = [ ("data", c_void_p), ("shape", (c_ssize_t * 3)), ("strides", (c_ssize_t * 3)), ("parent", c_void_p), ] class TestArrayAdaptor(unittest.TestCase): def test_array_adaptor(self): arystruct = ArrayStruct3D() adaptorptr = get_ndarray_adaptor() adaptor = PYFUNCTYPE(c_int, py_object, c_void_p)(adaptorptr) ary = numpy.arange(60).reshape(2, 3, 10) status = adaptor(ary, byref(arystruct)) self.assertEqual(status, 0) self.assertEqual(arystruct.data, ary.ctypes.data) for i in range(3): self.assertEqual(arystruct.shape[i], ary.ctypes.shape[i]) self.assertEqual(arystruct.strides[i], ary.ctypes.strides[i]) if __name__ == '__main__': unittest.main()
Fix test after changing array structure
Fix test after changing array structure
Python
bsd-2-clause
seibert/numba,GaZ3ll3/numba,pombredanne/numba,sklam/numba,stonebig/numba,gmarkall/numba,sklam/numba,seibert/numba,numba/numba,stuartarchibald/numba,sklam/numba,stonebig/numba,pombredanne/numba,IntelLabs/numba,ssarangi/numba,stuartarchibald/numba,cpcloud/numba,stefanseefeld/numba,gdementen/numba,ssarangi/numba,pitrou/numba,gmarkall/numba,gmarkall/numba,stefanseefeld/numba,seibert/numba,jriehl/numba,GaZ3ll3/numba,seibert/numba,seibert/numba,ssarangi/numba,GaZ3ll3/numba,numba/numba,cpcloud/numba,gmarkall/numba,ssarangi/numba,gdementen/numba,gdementen/numba,numba/numba,pitrou/numba,jriehl/numba,sklam/numba,IntelLabs/numba,jriehl/numba,cpcloud/numba,stuartarchibald/numba,stuartarchibald/numba,cpcloud/numba,pombredanne/numba,stefanseefeld/numba,pitrou/numba,numba/numba,pombredanne/numba,stefanseefeld/numba,GaZ3ll3/numba,ssarangi/numba,numba/numba,pitrou/numba,gdementen/numba,jriehl/numba,GaZ3ll3/numba,stefanseefeld/numba,stuartarchibald/numba,pombredanne/numba,cpcloud/numba,pitrou/numba,sklam/numba,gmarkall/numba,stonebig/numba,IntelLabs/numba,IntelLabs/numba,jriehl/numba,stonebig/numba,stonebig/numba,gdementen/numba,IntelLabs/numba
--- +++ @@ -10,6 +10,7 @@ ("data", c_void_p), ("shape", (c_ssize_t * 3)), ("strides", (c_ssize_t * 3)), + ("parent", c_void_p), ] @@ -28,3 +29,5 @@ self.assertEqual(arystruct.shape[i], ary.ctypes.shape[i]) self.assertEqual(arystruct.strides[i], ary.ctypes.strides[i]) +if __name__ == '__main__': + unittest.main()
0106108b2bb4f9ad5eaa4e02981293d5f5613aaf
cvmfs/webapi/cvmfs_api.py
cvmfs/webapi/cvmfs_api.py
import os import cvmfs_geo negative_expire_secs = 60*5; # 5 minutes def bad_request(start_response, reason): response_body = 'Bad Request: ' + reason + "\n" start_response('400 Bad Request', [('Cache-control', 'max-age=' + str(negative_expire_secs))]) return [response_body] def dispatch(api_func, path_info, repo_name, version, start_response, environ): if api_func == 'geo': return cvmfs_geo.api(path_info, repo_name, version, start_response, environ) return bad_request(start_response, 'unrecognized api function')
import os import cvmfs_geo negative_expire_secs = 60*5; # 5 minutes def bad_request(start_response, reason): response_body = 'Bad Request: ' + reason + "\n" start_response('400 Bad Request', [('Cache-control', 'max-age=' + str(negative_expire_secs)), ('Content-Length', str(len(response_body)))]) return [response_body] def dispatch(api_func, path_info, repo_name, version, start_response, environ): if api_func == 'geo': return cvmfs_geo.api(path_info, repo_name, version, start_response, environ) return bad_request(start_response, 'unrecognized api function')
Add Content-Length to message in the body of a bad request
Add Content-Length to message in the body of a bad request
Python
bsd-3-clause
reneme/cvmfs,cvmfs/cvmfs,djw8605/cvmfs,djw8605/cvmfs,alhowaidi/cvmfsNDN,cvmfs/cvmfs,djw8605/cvmfs,Gangbiao/cvmfs,trshaffer/cvmfs,cvmfs/cvmfs,reneme/cvmfs,reneme/cvmfs,cvmfs-testing/cvmfs,Moliholy/cvmfs,Gangbiao/cvmfs,reneme/cvmfs,MicBrain/cvmfs,DrDaveD/cvmfs,Moliholy/cvmfs,trshaffer/cvmfs,DrDaveD/cvmfs,MicBrain/cvmfs,Gangbiao/cvmfs,djw8605/cvmfs,reneme/cvmfs,MicBrain/cvmfs,cvmfs-testing/cvmfs,cvmfs-testing/cvmfs,alhowaidi/cvmfsNDN,DrDaveD/cvmfs,djw8605/cvmfs,trshaffer/cvmfs,cvmfs-testing/cvmfs,MicBrain/cvmfs,cvmfs/cvmfs,Moliholy/cvmfs,alhowaidi/cvmfsNDN,cvmfs/cvmfs,Gangbiao/cvmfs,trshaffer/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,DrDaveD/cvmfs,alhowaidi/cvmfsNDN,Gangbiao/cvmfs,cvmfs/cvmfs,DrDaveD/cvmfs,MicBrain/cvmfs,alhowaidi/cvmfsNDN,Moliholy/cvmfs,cvmfs-testing/cvmfs,trshaffer/cvmfs,DrDaveD/cvmfs,Moliholy/cvmfs
--- +++ @@ -6,7 +6,8 @@ def bad_request(start_response, reason): response_body = 'Bad Request: ' + reason + "\n" start_response('400 Bad Request', - [('Cache-control', 'max-age=' + str(negative_expire_secs))]) + [('Cache-control', 'max-age=' + str(negative_expire_secs)), + ('Content-Length', str(len(response_body)))]) return [response_body] def dispatch(api_func, path_info, repo_name, version, start_response, environ):
5488e6361359eb299e47814fd83e8e09187f45fd
draw_initials.py
draw_initials.py
import turtle def draw_initials(): #Set up screen, etc. window = turtle.Screen() window.bgcolor('gray') ###THE LETTER B### letter = turtle.Turtle() letter.shape('turtle') letter.color('white', 'gray') letter.speed(8) #Move pen into place letter.penup() letter.left(180) letter.forward(200) letter.pendown() #Draw the letter B letter.right(90) letter.forward(240) letter.right(90) letter.forward(65) letter.circle(-55,180) letter.forward(65) letter.left(180) letter.forward(75) letter.circle(-65, 180) letter.forward(75) #Move pen into place letter.penup() letter.right(180) letter.forward(150) letter.left(90) letter.forward(240) letter.right(90) letter.forward(190) letter.right(90) letter.forward(80) letter.pendown() #Draw the letter C letter.circle(-80,-180) letter.right(180) letter.forward(81) letter.circle(80,180) #Hide turtle and exit drawing window letter.hideturtle() window.exitonclick() draw_initials()
#!/usr/bin/env python import turtle def draw_initials(): """Draw the initials BC""" # Set up screen, etc. window = turtle.Screen() window.bgcolor('gray') letter = turtle.Turtle() letter.shape('turtle') letter.color('white', 'gray') letter.speed(8) # Move pen into place letter.penup() letter.left(180) letter.forward(200) letter.pendown() # Draw the letter B letter.right(90) letter.forward(240) letter.right(90) letter.forward(65) letter.circle(-55, 180) letter.forward(65) letter.left(180) letter.forward(75) letter.circle(-65, 180) letter.forward(75) # Move pen into place letter.penup() letter.right(180) letter.forward(150) letter.left(90) letter.forward(240) letter.right(90) letter.forward(190) letter.right(90) letter.forward(80) letter.pendown() # Draw the letter C letter.circle(-80, -180) letter.right(180) letter.forward(81) letter.circle(80, 180) # Hide turtle and exit drawing window letter.hideturtle() window.exitonclick() draw_initials()
Make minor improvements to comments and formatting
Make minor improvements to comments and formatting
Python
mit
bencam/turtle
--- +++ @@ -1,35 +1,38 @@ +#!/usr/bin/env python + import turtle + def draw_initials(): - #Set up screen, etc. + """Draw the initials BC""" + # Set up screen, etc. window = turtle.Screen() window.bgcolor('gray') - ###THE LETTER B### letter = turtle.Turtle() letter.shape('turtle') letter.color('white', 'gray') letter.speed(8) - - #Move pen into place + + # Move pen into place letter.penup() letter.left(180) letter.forward(200) letter.pendown() - #Draw the letter B + # Draw the letter B letter.right(90) letter.forward(240) letter.right(90) letter.forward(65) - letter.circle(-55,180) + letter.circle(-55, 180) letter.forward(65) letter.left(180) letter.forward(75) letter.circle(-65, 180) letter.forward(75) - #Move pen into place + # Move pen into place letter.penup() letter.right(180) letter.forward(150) @@ -41,13 +44,13 @@ letter.forward(80) letter.pendown() - #Draw the letter C - letter.circle(-80,-180) + # Draw the letter C + letter.circle(-80, -180) letter.right(180) letter.forward(81) - letter.circle(80,180) + letter.circle(80, 180) - #Hide turtle and exit drawing window + # Hide turtle and exit drawing window letter.hideturtle() window.exitonclick()
dd6090464fa3eb1f95f6fd5efd7591b1c06c0ce6
fuel_plugin_builder/fuel_plugin_builder/messages.py
fuel_plugin_builder/fuel_plugin_builder/messages.py
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, Inc. # # 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. header = '=' * 50 install_required_packages = """ Was not able to find required packages. If you use Ubuntu, run: # sudo apt-get install createrepo rpm dpkg-dev If you use CentOS, run: # yum install createrepo rpm dpkg-devel """
# -*- coding: utf-8 -*- # Copyright 2014 Mirantis, Inc. # # 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. header = '=' * 50 install_required_packages = """ Was not able to find required packages. If you use Ubuntu, run: # sudo apt-get install createrepo rpm dpkg-dev If you use CentOS, run: # yum install createrepo dpkg-devel rpm rpm-build """
Add rpm-build into environment setup message for CentOS
Add rpm-build into environment setup message for CentOS Change-Id: I44bd14f2f3c3e76c24f5efd26a5ff6a545dcaf72 Implements: blueprint plugin-major-version-for-releases
Python
apache-2.0
nebril/fuel-plugins,stackforge/fuel-plugins,stackforge/fuel-plugins,nebril/fuel-plugins
--- +++ @@ -27,6 +27,6 @@ If you use CentOS, run: - # yum install createrepo rpm dpkg-devel + # yum install createrepo dpkg-devel rpm rpm-build """
02de9a6092549e1310adba9fd844cb9c67958d70
oneanddone/tasks/management/commands/taskcleanup.py
oneanddone/tasks/management/commands/taskcleanup.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from django.core.management.base import BaseCommand from oneanddone.tasks.models import Task, TaskAttempt class Command(BaseCommand): help = 'Cleans up status of tasks and attempts based on task data' def handle(self, *args, **options): invalidated = Task.invalidate_tasks() self.stdout.write('%s tasks were invalidated via bug data\n' % invalidated) closed = TaskAttempt.close_stale_onetime_attempts() self.stdout.write('%s stale one-time attempts were closed\n' % closed) closed = TaskAttempt.close_expired_task_attempts() self.stdout.write('%s attempts for expired tasks were closed\n' % closed)
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from datetime import datetime from django.core.management.base import BaseCommand from oneanddone.tasks.models import Task, TaskAttempt class Command(BaseCommand): help = 'Cleans up status of tasks and attempts based on task data' def handle(self, *args, **options): invalidated = Task.invalidate_tasks() self.stdout.write('%s: %s tasks were invalidated via bug data\n' % (datetime.now().isoformat(), invalidated)) closed = TaskAttempt.close_stale_onetime_attempts() self.stdout.write('%s: %s stale one-time attempts were closed\n' % (datetime.now().isoformat(), closed)) closed = TaskAttempt.close_expired_task_attempts() self.stdout.write('%s: %s attempts for expired tasks were closed\n' % (datetime.now().isoformat(), closed))
Add timestamps to management task output
Add timestamps to management task output
Python
mpl-2.0
adini121/oneanddone,glogiotatidis/oneanddone,tessie/oneanddone,jicksy/oneanddone_test,m8ttyB/oneanddone,tessie/oneanddone,jicksy/oneanddone_test,m8ttyB/oneanddone,bobsilverberg/oneanddone,VarnaSuresh/oneanddone,akatsoulas/oneanddone,VarnaSuresh/oneanddone,adini121/oneanddone,akatsoulas/oneanddone,adini121/oneanddone,VarnaSuresh/oneanddone,adini121/oneanddone,akatsoulas/oneanddone,glogiotatidis/oneanddone,bobsilverberg/oneanddone,jicksy/oneanddone_test,m8ttyB/oneanddone,m8ttyB/oneanddone,VarnaSuresh/oneanddone,glogiotatidis/oneanddone,tessie/oneanddone,bobsilverberg/oneanddone,akatsoulas/oneanddone,bobsilverberg/oneanddone,tessie/oneanddone,glogiotatidis/oneanddone
--- +++ @@ -1,6 +1,8 @@ # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. +from datetime import datetime + from django.core.management.base import BaseCommand from oneanddone.tasks.models import Task, TaskAttempt @@ -11,8 +13,11 @@ def handle(self, *args, **options): invalidated = Task.invalidate_tasks() - self.stdout.write('%s tasks were invalidated via bug data\n' % invalidated) + self.stdout.write('%s: %s tasks were invalidated via bug data\n' % + (datetime.now().isoformat(), invalidated)) closed = TaskAttempt.close_stale_onetime_attempts() - self.stdout.write('%s stale one-time attempts were closed\n' % closed) + self.stdout.write('%s: %s stale one-time attempts were closed\n' % + (datetime.now().isoformat(), closed)) closed = TaskAttempt.close_expired_task_attempts() - self.stdout.write('%s attempts for expired tasks were closed\n' % closed) + self.stdout.write('%s: %s attempts for expired tasks were closed\n' % + (datetime.now().isoformat(), closed))
eb60d0d226f08b90e2835aac0440560f392257f4
prolog/targetprologstandalone.py
prolog/targetprologstandalone.py
""" A simple standalone target for the prolog interpreter. """ import sys from prolog.interpreter.translatedmain import repl, execute # __________ Entry point __________ from prolog.interpreter.continuation import Engine from prolog.interpreter import term from prolog.interpreter import arithmetic # for side effects from prolog import builtin # for side effects e = Engine() term.DEBUG = False def entry_point(argv): e.clocks.startup() if len(argv) == 2: execute(e, argv[1]) try: repl(e) except SystemExit: return 1 return 0 # _____ Define and setup target ___ def target(driver, args): driver.exe_name = 'pyrolog-%(backend)s' return entry_point, None def portal(driver): from prolog.interpreter.portal import get_portal return get_portal(driver) def jitpolicy(self): from pypy.jit.metainterp.policy import JitPolicy return JitPolicy() if __name__ == '__main__': entry_point(sys.argv)
""" A simple standalone target for the prolog interpreter. """ import sys from prolog.interpreter.translatedmain import repl, execute # __________ Entry point __________ from prolog.interpreter.continuation import Engine from prolog.interpreter import term from prolog.interpreter import arithmetic # for side effects from prolog import builtin # for side effects e = Engine(load_system=True) term.DEBUG = False def entry_point(argv): e.clocks.startup() if len(argv) == 2: execute(e, argv[1]) try: repl(e) except SystemExit: return 1 return 0 # _____ Define and setup target ___ def target(driver, args): driver.exe_name = 'pyrolog-%(backend)s' return entry_point, None def portal(driver): from prolog.interpreter.portal import get_portal return get_portal(driver) def jitpolicy(self): from pypy.jit.metainterp.policy import JitPolicy return JitPolicy() if __name__ == '__main__': entry_point(sys.argv)
Initialize engine with load_system parameter.
Initialize engine with load_system parameter.
Python
mit
cosmoharrigan/pyrolog
--- +++ @@ -11,7 +11,7 @@ from prolog.interpreter import term from prolog.interpreter import arithmetic # for side effects from prolog import builtin # for side effects -e = Engine() +e = Engine(load_system=True) term.DEBUG = False def entry_point(argv):
ee2a6bb99d2a8fadecddd58366c20202c863c97c
geocoder/__init__.py
geocoder/__init__.py
#!/usr/bin/python # coding: utf8 # TODO: Move imports to specific modules that need them # CORE from .api import get, yahoo, bing, geonames, google, mapquest # noqa from .api import nokia, osm, tomtom, geolytica, arcgis, opencage # noqa from .api import maxmind, freegeoip, ottawa, here, baidu, w3w, yandex # noqa # EXTRAS from .api import timezone, elevation, ip, canadapost, reverse # noqa # CLI from .cli import cli # noqa """ Geocoder ~~~~~~~~ Geocoder is a geocoding library, written in python, simple and consistent. Many online providers such as Google & Bing have geocoding services, these providers do not include Python libraries and have different JSON responses between each other. Consistant JSON responses from various providers. >>> g = geocoder.google('New York City') >>> g.latlng [40.7127837, -74.0059413] >>> g.state 'New York' >>> g.json ... """ __title__ = 'geocoder' __author__ = 'Denis Carriere' __author_email__ = 'carriere.denis@gmail.com' __version__ = '1.2.2' __license__ = 'MIT' __copyright__ = 'Copyright (c) 2013-2015 Denis Carriere'
#!/usr/bin/python # coding: utf8 """ Geocoder ~~~~~~~~ Geocoder is a geocoding library, written in python, simple and consistent. Many online providers such as Google & Bing have geocoding services, these providers do not include Python libraries and have different JSON responses between each other. Consistant JSON responses from various providers. >>> g = geocoder.google('New York City') >>> g.latlng [40.7127837, -74.0059413] >>> g.state 'New York' >>> g.json ... """ __title__ = 'geocoder' __author__ = 'Denis Carriere' __author_email__ = 'carriere.denis@gmail.com' __version__ = '1.2.2' __license__ = 'MIT' __copyright__ = 'Copyright (c) 2013-2015 Denis Carriere' # CORE from .api import get, yahoo, bing, geonames, mapquest # noqa from .api import nokia, osm, tomtom, geolytica, arcgis, opencage # noqa from .api import maxmind, freegeoip, ottawa, here, baidu, w3w, yandex # noqa # EXTRAS from .api import timezone, elevation, ip, canadapost, reverse # noqa # CLI from .cli import cli # noqa
Add imports to init with noqa comments
Add imports to init with noqa comments
Python
mit
epyatopal/geocoder-1,akittas/geocoder,minimedj/geocoder,DenisCarriere/geocoder,ahlusar1989/geocoder,miraculixx/geocoder
--- +++ @@ -1,18 +1,5 @@ #!/usr/bin/python # coding: utf8 - -# TODO: Move imports to specific modules that need them - -# CORE -from .api import get, yahoo, bing, geonames, google, mapquest # noqa -from .api import nokia, osm, tomtom, geolytica, arcgis, opencage # noqa -from .api import maxmind, freegeoip, ottawa, here, baidu, w3w, yandex # noqa - -# EXTRAS -from .api import timezone, elevation, ip, canadapost, reverse # noqa - -# CLI -from .cli import cli # noqa """ Geocoder @@ -42,3 +29,14 @@ __version__ = '1.2.2' __license__ = 'MIT' __copyright__ = 'Copyright (c) 2013-2015 Denis Carriere' + +# CORE +from .api import get, yahoo, bing, geonames, mapquest # noqa +from .api import nokia, osm, tomtom, geolytica, arcgis, opencage # noqa +from .api import maxmind, freegeoip, ottawa, here, baidu, w3w, yandex # noqa + +# EXTRAS +from .api import timezone, elevation, ip, canadapost, reverse # noqa + +# CLI +from .cli import cli # noqa
64441102017e966895b8b082c40932148509f60d
dimod/package_info.py
dimod/package_info.py
__version__ = '1.0.0.dev6' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'A shared API for binary quadratic model samplers.'
__version__ = '1.0.0.dev7' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'A shared API for binary quadratic model samplers.'
Update version 1.0.0.dev6 -> 1.0.0.dev7
Update version 1.0.0.dev6 -> 1.0.0.dev7
Python
apache-2.0
oneklc/dimod,oneklc/dimod
--- +++ @@ -1,4 +1,4 @@ -__version__ = '1.0.0.dev6' +__version__ = '1.0.0.dev7' __author__ = 'D-Wave Systems Inc.' __authoremail__ = 'acondello@dwavesys.com' __description__ = 'A shared API for binary quadratic model samplers.'
21e5ee2ad250c313ea0eb2c67c3d3cc32661d24d
examples/benchmarking/server.py
examples/benchmarking/server.py
import asyncore,time,signal,sys from secure_smtpd import SMTPServer, FakeCredentialValidator class SecureSMTPServer(SMTPServer): def __init__(self): pass def process_message(self, peer, mailfrom, rcpttos, message_data): pass def start(self): SMTPServer.__init__( self, ('0.0.0.0', 25), None ) asyncore.loop() server = SecureSMTPServer() server.start() # normal termination of this process will kill worker children in # process pool so this process (the parent) needs to idle here waiting # for termination signal. If you don't have a signal handler, then # Python multiprocess cleanup stuff doesn't happen, and children won't # get killed by sending SIGTERM to parent. def sig_handler(signal,frame): print "Got signal %s, shutting down." % signal sys.exit(0) signal.signal(signal.SIGTERM, sig_handler) while 1: time.sleep(1)
from secure_smtpd import SMTPServer class SecureSMTPServer(SMTPServer): def process_message(self, peer, mailfrom, rcpttos, message_data): pass server = SecureSMTPServer(('0.0.0.0', 1025), None) server.run()
Switch to non-privledged port to make testing easier.
Switch to non-privledged port to make testing easier. User the new server.run() method.
Python
isc
bcoe/secure-smtpd
--- +++ @@ -1,37 +1,8 @@ -import asyncore,time,signal,sys -from secure_smtpd import SMTPServer, FakeCredentialValidator +from secure_smtpd import SMTPServer class SecureSMTPServer(SMTPServer): - - def __init__(self): - pass - def process_message(self, peer, mailfrom, rcpttos, message_data): pass - def start(self): - SMTPServer.__init__( - self, - ('0.0.0.0', 25), - None - ) - asyncore.loop() - -server = SecureSMTPServer() -server.start() - - -# normal termination of this process will kill worker children in -# process pool so this process (the parent) needs to idle here waiting -# for termination signal. If you don't have a signal handler, then -# Python multiprocess cleanup stuff doesn't happen, and children won't -# get killed by sending SIGTERM to parent. - -def sig_handler(signal,frame): - print "Got signal %s, shutting down." % signal - sys.exit(0) - -signal.signal(signal.SIGTERM, sig_handler) - -while 1: - time.sleep(1) +server = SecureSMTPServer(('0.0.0.0', 1025), None) +server.run()
2041cd414df65d9b529a19fd589163af41ec082e
ocl/oclapi/management/commands/run_data_integrity_checks.py
ocl/oclapi/management/commands/run_data_integrity_checks.py
from django.core.management import BaseCommand from tasks import data_integrity_checks class Command(BaseCommand): help = 'Run data integrity checks' def handle(self, *args, **options): data_integrity_checks.delay()
from django.core.management import BaseCommand from tasks import data_integrity_checks class Command(BaseCommand): help = 'Run data integrity checks' def handle(self, *args, **options): pass #data_integrity_checks.delay()
Disable updating active counts on startup
Disable updating active counts on startup
Python
mpl-2.0
snyaggarwal/oclapi,snyaggarwal/oclapi,snyaggarwal/oclapi,snyaggarwal/oclapi,OpenConceptLab/oclapi,OpenConceptLab/oclapi,OpenConceptLab/oclapi,OpenConceptLab/oclapi,OpenConceptLab/oclapi
--- +++ @@ -5,4 +5,4 @@ help = 'Run data integrity checks' def handle(self, *args, **options): - data_integrity_checks.delay() + pass #data_integrity_checks.delay()
ff61fb41273b8bf94bd0c64ddb1a4c1e1c91bb5f
api/__init__.py
api/__init__.py
from flask_sqlalchemy import SQLAlchemy import connexion from config import config db = SQLAlchemy() def create_app(config_name): app = connexion.FlaskApp(__name__, specification_dir='swagger/') app.add_api('swagger.yaml') application = app.app application.config.from_object(config[config_name]) db.init_app(application) return application from api.api import *
from flask_sqlalchemy import SQLAlchemy import connexion from config import config db = SQLAlchemy() def create_app(config_name): app = connexion.FlaskApp(__name__, specification_dir='swagger/') app.add_api('swagger.yaml') application = app.app application.config.from_object(config[config_name]) application.add_url_rule('/auth/register', 'register', register) application.add_url_rule('/auth/login', 'login', login) db.init_app(application) return application from api.api import *
Add url rules for public unauthorised routes
Add url rules for public unauthorised routes
Python
mit
EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list,EdwinKato/bucket-list
--- +++ @@ -11,6 +11,15 @@ app.add_api('swagger.yaml') application = app.app application.config.from_object(config[config_name]) + + application.add_url_rule('/auth/register', + 'register', + register) + + application.add_url_rule('/auth/login', + 'login', + login) + db.init_app(application) return application
51781b95b629a31107d16a52b0ea184306fe6163
pyfakefs/pytest_plugin.py
pyfakefs/pytest_plugin.py
"""A pytest plugin for using pyfakefs as a fixture When pyfakefs is installed, the "fs" fixture becomes available. :Usage: def my_fakefs_test(fs): fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') """ import linecache import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher try: import builtins except ImportError: import __builtin__ as builtins Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem # The "linecache" module is used to read the test file in case of test failure # to get traceback information before test tear down. # In order to make sure that reading the test file is not faked, # we both skip faking the module, and add the build-in open() function # as a local function in the module Patcher.SKIPMODULES.add(linecache) linecache.open = builtins.open @pytest.fixture def fs(request): """ Fake filesystem. """ patcher = Patcher() patcher.setUp() request.addfinalizer(patcher.tearDown) return patcher.fs
"""A pytest plugin for using pyfakefs as a fixture When pyfakefs is installed, the "fs" fixture becomes available. :Usage: def my_fakefs_test(fs): fs.create_file('/var/data/xx1.txt') assert os.path.exists('/var/data/xx1.txt') """ import linecache import sys import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher if sys.version_info >= (3,): import builtins else: import __builtin__ as builtins Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem # The "linecache" module is used to read the test file in case of test failure # to get traceback information before test tear down. # In order to make sure that reading the test file is not faked, # we both skip faking the module, and add the build-in open() function # as a local function in the module Patcher.SKIPMODULES.add(linecache) linecache.open = builtins.open @pytest.fixture def fs(request): """ Fake filesystem. """ patcher = Patcher() patcher.setUp() request.addfinalizer(patcher.tearDown) return patcher.fs
Fix pytest when pyfakefs + future is installed
Fix pytest when pyfakefs + future is installed `python-future` is notorious for breaking modules which use `try:` / `except:` to import modules based on version. In this case, `pyfakefs` imported the backported `builtins` module which changes the semantics of the `open()` function. `pyfakefs` then monkeypatches `linecache` which breaks any module which attempts to use `linecache` (in this case `pytest`). The downstream issue is https://github.com/pytest-dev/pytest/pull/4074
Python
apache-2.0
mrbean-bremen/pyfakefs,mrbean-bremen/pyfakefs,pytest-dev/pyfakefs,jmcgeheeiv/pyfakefs
--- +++ @@ -10,15 +10,16 @@ """ import linecache +import sys import py import pytest from pyfakefs.fake_filesystem_unittest import Patcher -try: +if sys.version_info >= (3,): import builtins -except ImportError: +else: import __builtin__ as builtins Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
3aa248a9ee40afb2c8c7725ae832c0d25ec92c9b
nose/orbitint4sigint.py
nose/orbitint4sigint.py
import sys import numpy from galpy.orbit import Orbit from galpy.potential import MiyamotoNagaiPotential if __name__ == '__main__': # python orbitint4sigint.py symplec4_c full mp= MiyamotoNagaiPotential(normalize=1.,a=0.5,b=0.05) ts= numpy.linspace(0.,100000.,10001) if sys.argv[2] == 'full' or sys.argv[2] == 'planar': if sys.argv[2] == 'full': o= Orbit([1.,0.1,1.1,0.1,0.1,0.]) elif sys.argv[2] == 'planar': o= Orbit([1.,0.1,1.1,0.1]) o.integrate(ts,mp,method=sys.argv[1]) elif sys.argv[2] == 'planardxdv': o= Orbit([1.,0.1,1.1,0.1]) o.integrate_dxdv([0.1,0.1,0.1,0.1],ts,mp,method=sys.argv[1]) sys.exit(0)
import sys import numpy from galpy.orbit import Orbit from galpy.potential import MiyamotoNagaiPotential if __name__ == '__main__': # python orbitint4sigint.py symplec4_c full mp= MiyamotoNagaiPotential(normalize=1.,a=0.5,b=0.05) ts= numpy.linspace(0.,10000000.,1000001) if sys.argv[2] == 'full' or sys.argv[2] == 'planar': if sys.argv[2] == 'full': o= Orbit([1.,0.1,1.1,0.1,0.1,0.]) elif sys.argv[2] == 'planar': o= Orbit([1.,0.1,1.1,0.1]) o.integrate(ts,mp,method=sys.argv[1]) elif sys.argv[2] == 'planardxdv': o= Orbit([1.,0.1,1.1,0.1]) o.integrate_dxdv([0.1,0.1,0.1,0.1],ts,mp,method=sys.argv[1]) sys.exit(0)
Make integration longer bc now ends before interrupt?
Make integration longer bc now ends before interrupt?
Python
bsd-3-clause
jobovy/galpy,jobovy/galpy,jobovy/galpy,jobovy/galpy
--- +++ @@ -6,7 +6,7 @@ if __name__ == '__main__': # python orbitint4sigint.py symplec4_c full mp= MiyamotoNagaiPotential(normalize=1.,a=0.5,b=0.05) - ts= numpy.linspace(0.,100000.,10001) + ts= numpy.linspace(0.,10000000.,1000001) if sys.argv[2] == 'full' or sys.argv[2] == 'planar': if sys.argv[2] == 'full': o= Orbit([1.,0.1,1.1,0.1,0.1,0.])
4b7e20c5640242a6e06392aaf9cbfe8e4ee8a498
mangopaysdk/types/payinpaymentdetailscard.py
mangopaysdk/types/payinpaymentdetailscard.py
from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None
from mangopaysdk.types.payinpaymentdetails import PayInPaymentDetails class PayInPaymentDetailsCard(PayInPaymentDetails): """Class represents Card type for mean of payment in PayIn entity.""" def __init__(self): # CardType enum self.CardType = None self.StatementDescriptor = None
Add StatementDescriptor for card web payins
Add StatementDescriptor for card web payins
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
--- +++ @@ -7,3 +7,4 @@ def __init__(self): # CardType enum self.CardType = None + self.StatementDescriptor = None
7bd82f6feb1a34dd7b855cfe2f421232229e19db
pages/search_indexes.py
pages/search_indexes.py
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) publication_date = DateTimeField(model_attr='publication_date') def get_queryset(self): """Used when the entire index for model is updated.""" return Page.objects.published() site.register(Page, PageIndex)
"""Django haystack `SearchIndex` module.""" from pages.models import Page from haystack.indexes import SearchIndex, CharField, DateTimeField from haystack import site class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) title = CharField(model_attr='title') publication_date = DateTimeField(model_attr='publication_date') def get_queryset(self): """Used when the entire index for model is updated.""" return Page.objects.published() site.register(Page, PageIndex)
Add a title attribute to the SearchIndex for pages.
Add a title attribute to the SearchIndex for pages. This is useful when displaying a list of search results because we can display the title of the result without hitting the database to actually pull the page.
Python
bsd-3-clause
remik/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-cms,batiste/django-page-cms,oliciv/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,pombredanne/django-page-cms-1
--- +++ @@ -8,6 +8,7 @@ class PageIndex(SearchIndex): """Search index for pages content.""" text = CharField(document=True, use_template=True) + title = CharField(model_attr='title') publication_date = DateTimeField(model_attr='publication_date') def get_queryset(self):
9ce1f694a7581333d000a6a7b77e8d846bb4b507
imageutils/scaling/normalize.py
imageutils/scaling/normalize.py
""" Normalization class for Matplotlib that can be used to produce colorbars. """ import numpy as np from numpy import ma from matplotlib.colors import Normalize __all__ = ['ImageNormalize'] class ImageNormalize(Normalize): def __init__(self, vmin=None, vmax=None, stretch=None, clip=True): super(ImageNormalize, self).__init__(vmin=vmin, vmax=vmax, clip=clip) self.vmin = vmin self.vmax = vmax self.stretch = stretch self.inverse_stretch = stretch.inverted() def __call__(self, values, clip=None): if clip is None: clip = self.clip # Convert to masked array and make sure scalars get broadcast to 1-d values = np.atleast_1d(values) # Normalize based on vmin and vmax values_norm = (values - self.vmin) / (self.vmax - self.vmin) # Clip to the 0 to 1 range if self.clip: values_norm = np.clip(values_norm, 0., 1.) # Stretch values new_values = self.stretch(values_norm) # Don't assume stretch returned a masked array return ma.asarray(new_values) def inverse(self, values): # Find unstretched values in range 0 to 1 values_norm = self.inverse_stretch(values) # Scale to original range return values_norm * (self.vmax - self.vmin) + self.vmin
""" Normalization class for Matplotlib that can be used to produce colorbars. """ import numpy as np from numpy import ma from matplotlib.colors import Normalize __all__ = ['ImageNormalize'] class ImageNormalize(Normalize): def __init__(self, vmin=None, vmax=None, stretch=None, clip=True): super(ImageNormalize, self).__init__(vmin=vmin, vmax=vmax, clip=clip) self.vmin = vmin self.vmax = vmax self.stretch = stretch self.inverse_stretch = stretch.inverted() def __call__(self, values, clip=None): if clip is None: clip = self.clip # Make sure scalars get broadcast to 1-d if np.isscalar(values): values = np.atleast_1d(values) else: values = values.copy() # copy because of in-place operations after # Normalize based on vmin and vmax np.subtract(values, self.vmin, out=values) np.divide(values, self.vmax - self.vmin, out=values) # Clip to the 0 to 1 range if self.clip: values = np.clip(values, 0., 1., out=values) # Stretch values values = self.stretch(values, out=values) # Convert to masked array for matplotlib return ma.array(values) def inverse(self, values): # Find unstretched values in range 0 to 1 values_norm = self.inverse_stretch(values) # Scale to original range return values_norm * (self.vmax - self.vmin) + self.vmin
Use in-place operations in ImageNormalize
Use in-place operations in ImageNormalize
Python
bsd-3-clause
dhomeier/astropy,bsipocz/astropy,MSeifert04/astropy,mhvk/astropy,MSeifert04/astropy,mhvk/astropy,joergdietrich/astropy,stargaser/astropy,StuartLittlefair/astropy,lpsinger/astropy,AustereCuriosity/astropy,AustereCuriosity/astropy,astropy/astropy,lpsinger/astropy,joergdietrich/astropy,lpsinger/astropy,AustereCuriosity/astropy,saimn/astropy,pllim/astropy,stargaser/astropy,tbabej/astropy,DougBurke/astropy,StuartLittlefair/astropy,aleksandr-bakanov/astropy,kelle/astropy,kelle/astropy,kelle/astropy,mhvk/astropy,pllim/astropy,funbaker/astropy,bsipocz/astropy,pllim/astropy,StuartLittlefair/astropy,DougBurke/astropy,astropy/astropy,aleksandr-bakanov/astropy,MSeifert04/astropy,larrybradley/astropy,astropy/astropy,AustereCuriosity/astropy,larrybradley/astropy,tbabej/astropy,dhomeier/astropy,pllim/astropy,astropy/astropy,bsipocz/astropy,joergdietrich/astropy,stargaser/astropy,astropy/astropy,DougBurke/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,stargaser/astropy,funbaker/astropy,pllim/astropy,saimn/astropy,saimn/astropy,tbabej/astropy,MSeifert04/astropy,tbabej/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,dhomeier/astropy,kelle/astropy,joergdietrich/astropy,funbaker/astropy,larrybradley/astropy,larrybradley/astropy,mhvk/astropy,saimn/astropy,larrybradley/astropy,saimn/astropy,lpsinger/astropy,lpsinger/astropy,bsipocz/astropy,dhomeier/astropy,tbabej/astropy,mhvk/astropy,joergdietrich/astropy,funbaker/astropy,kelle/astropy,DougBurke/astropy
--- +++ @@ -27,21 +27,25 @@ if clip is None: clip = self.clip - # Convert to masked array and make sure scalars get broadcast to 1-d - values = np.atleast_1d(values) + # Make sure scalars get broadcast to 1-d + if np.isscalar(values): + values = np.atleast_1d(values) + else: + values = values.copy() # copy because of in-place operations after # Normalize based on vmin and vmax - values_norm = (values - self.vmin) / (self.vmax - self.vmin) + np.subtract(values, self.vmin, out=values) + np.divide(values, self.vmax - self.vmin, out=values) # Clip to the 0 to 1 range if self.clip: - values_norm = np.clip(values_norm, 0., 1.) + values = np.clip(values, 0., 1., out=values) # Stretch values - new_values = self.stretch(values_norm) + values = self.stretch(values, out=values) - # Don't assume stretch returned a masked array - return ma.asarray(new_values) + # Convert to masked array for matplotlib + return ma.array(values) def inverse(self, values):
a33f288bb2937bbf750b9d195861e311f293d94b
grortir/test/externals/pyswarm/test_pyswarm.py
grortir/test/externals/pyswarm/test_pyswarm.py
"""Tests for pyswarm.""" from unittest import TestCase from grortir.externals.pyswarm.pso import pso class TestPso(TestCase): """Class for tests PSO.""" def test_run_simple_pso(self): """Test running library.""" lower_bound = [-3, -1] upper_bound = [2, 6] x_opt, f_opt = pso(myfunc, lower_bound, upper_bound) self.assertIsNotNone(x_opt) self.assertIsNotNone(f_opt) def myfunc(input_vector): """Simple function for tests. Args: input_vector: input vector Returns: object : value of function """ x_1 = input_vector[0] x_2 = input_vector[1] return x_1 ** 4 - 2 * x_2 * x_1 ** 2 + x_2 ** 2 + x_1 ** 2 - 2 * x_1 + 5
"""Tests for pyswarm.""" from unittest import TestCase from grortir.externals.pyswarm.pso import pso class TestPso(TestCase): """Class for tests pyswarm.""" def test_run_simple_pso(self): """Test running library.""" lower_bound = [-3, -1] upper_bound = [2, 6] x_opt, f_opt = pso(myfunc, lower_bound, upper_bound) self.assertIsNotNone(x_opt) self.assertIsNotNone(f_opt) def myfunc(input_vector): """Simple function for tests. Args: input_vector (list): input vector Returns: object : value of function """ x_1 = input_vector[0] x_2 = input_vector[1] return x_1 ** 4 - 2 * x_2 * x_1 ** 2 + x_2 ** 2 + x_1 ** 2 - 2 * x_1 + 5
Add pySwarm code - tests fixed.
Add pySwarm code - tests fixed.
Python
mit
qbahn/grortir
--- +++ @@ -4,7 +4,7 @@ class TestPso(TestCase): - """Class for tests PSO.""" + """Class for tests pyswarm.""" def test_run_simple_pso(self): """Test running library.""" @@ -20,7 +20,7 @@ """Simple function for tests. Args: - input_vector: input vector + input_vector (list): input vector Returns: object : value of function
f19b66d42f67a6a45bec6fdaffe6c73366788b48
rules/RoleRelativePath.py
rules/RoleRelativePath.py
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False if "../copys" in play['copy']['src']: return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return []
from ansiblelint import AnsibleLintRule format = "{}" class RoleRelativePath(AnsibleLintRule): id = 'E201' shortdesc = "Doesn't need a relative path in role" description = '' tags = ['role'] def matchplay(self, file, play): # assume if 'roles' in path, inside a role. if 'roles' not in file['path']: return [] if 'template' in play: if not isinstance(play['template'], dict): return False if "../templates" in play['template']['src']: return [({'': play['template']}, self.shortdesc)] if 'win_template' in play: if not isinstance(play['win_template'], dict): return False if "../win_templates" in play['win_template']['src']: return ({'win_template': play['win_template']}, self.shortdesc) if 'copy' in play: if not isinstance(play['copy'], dict): return False if 'src' in play['copy']: if "../copys" in play['copy']['src']: return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict): return False if "../win_copys" in play['win_copy']['src']: return ({'sudo': play['win_copy']}, self.shortdesc) return []
Add check for src field
Add check for src field Src field can be absent in copy task, and content field can be used instead, so we should check if src is present to avoid Keyerror exception.
Python
mit
tsukinowasha/ansible-lint-rules
--- +++ @@ -28,8 +28,9 @@ if 'copy' in play: if not isinstance(play['copy'], dict): return False - if "../copys" in play['copy']['src']: - return ({'sudo': play['copy']}, + if 'src' in play['copy']: + if "../copys" in play['copy']['src']: + return ({'sudo': play['copy']}, self.shortdesc) if 'win_copy' in play: if not isinstance(play['win_copy'], dict):
fb26a66ab179fe375f50933c2be3f2e5da2f68a3
exercises/leap/leap_test.py
exercises/leap/leap_test.py
import unittest from leap import is_leap_year # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class YearTest(unittest.TestCase): def test_year_not_divisible_by_4(self): self.assertIs(is_leap_year(2015), False) def test_year_divisible_by_4_not_divisible_by_100(self): self.assertIs(is_leap_year(2016), True) def test_year_divisible_by_100_not_divisible_by_400(self): self.assertIs(is_leap_year(2100), False) def test_year_divisible_by_400(self): self.assertIs(is_leap_year(2000), True) if __name__ == '__main__': unittest.main()
import unittest from leap import is_leap_year # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class YearTest(unittest.TestCase): def test_year_not_divisible_by_4(self): self.assertIs(is_leap_year(2015), False) def test_year_divisible_by_4_not_divisible_by_100(self): self.assertIs(is_leap_year(1996), True) def test_year_divisible_by_100_not_divisible_by_400(self): self.assertIs(is_leap_year(2100), False) def test_year_divisible_by_400(self): self.assertIs(is_leap_year(2000), True) if __name__ == '__main__': unittest.main()
Swap '2016' for '1996' to stop faulty logic from passing unit test
Swap '2016' for '1996' to stop faulty logic from passing unit test [This leap solution](http://exercism.io/submissions/7ef5b0ab93b540f79cdee9f153e0a21c) should not pass the unit test, since it checks whether `year % 100` and `year % 400` are equal in order to tell whether the year it has been passed is a leap year. This works for 2016 because `2016 % 100` and `2016 % 400` both evaluate to 16. 1996, another leap year that is divisible by 4 but not 100, does not have this property and, under that solution, would falsely not be classed as a leap year.
Python
mit
exercism/python,exercism/xpython,exercism/xpython,N-Parsons/exercism-python,pheanex/xpython,smalley/python,N-Parsons/exercism-python,jmluy/xpython,pheanex/xpython,exercism/python,behrtam/xpython,jmluy/xpython,behrtam/xpython,smalley/python
--- +++ @@ -10,7 +10,7 @@ self.assertIs(is_leap_year(2015), False) def test_year_divisible_by_4_not_divisible_by_100(self): - self.assertIs(is_leap_year(2016), True) + self.assertIs(is_leap_year(1996), True) def test_year_divisible_by_100_not_divisible_by_400(self): self.assertIs(is_leap_year(2100), False)
aaaaad77054658ad6c5d63a84bffe8d43b4e3180
falcom/tree/mutable_tree.py
falcom/tree/mutable_tree.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class MutableTree: def __init__ (self): self.length = 0 self.value = None @property def value (self): return self.__value @value.setter def value (self, x): self.__value = x def full_length (self): return len(self) def walk (self): return iter(()) def __len__ (self): return self.length def __iter__ (self): return iter(()) def __getitem__ (self, index): if self: return None else: raise IndexError("tree index out of range") def __repr__ (self): return "<{}>".format(self.__class__.__name__) def insert (self, index, node): self.length = 1
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class MutableTree: def __init__ (self): self.child = None self.value = None @property def value (self): return self.__value @value.setter def value (self, x): self.__value = x def full_length (self): return len(self) def walk (self): return iter(()) def __len__ (self): return 0 if self.child is None else 1 def __iter__ (self): return iter(()) def __getitem__ (self, index): if self: return None else: raise IndexError("tree index out of range") def __repr__ (self): return "<{}>".format(self.__class__.__name__) def insert (self, index, node): self.child = node
Rework tree to store inserted nodes
Rework tree to store inserted nodes
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
--- +++ @@ -5,7 +5,7 @@ class MutableTree: def __init__ (self): - self.length = 0 + self.child = None self.value = None @property @@ -23,7 +23,7 @@ return iter(()) def __len__ (self): - return self.length + return 0 if self.child is None else 1 def __iter__ (self): return iter(()) @@ -39,4 +39,4 @@ return "<{}>".format(self.__class__.__name__) def insert (self, index, node): - self.length = 1 + self.child = node
7ddb1b3d0139ef8b6a7badcb2c6bef6a0e35e88a
hooks/post_gen_project.py
hooks/post_gen_project.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Rename the generated kv file to be compatible with the original kivy kv file detection of `App.load_kv`. """ import os package_dir = '{{cookiecutter.repo_name}}' old_kv_file = os.path.join(package_dir, '{{cookiecutter.app_class_name}}.kv') lower_app_class_name = '{{cookiecutter.app_class_name}}'.lower() if (lower_app_class_name.endswith('app')): lower_app_class_name = lower_app_class_name[:-3] new_kv_file = os.path.join(package_dir, '{}.kv'.format(lower_app_class_name)) os.rename(old_kv_file, new_kv_file)
#!/usr/bin/env python # -*- coding: utf-8 -*- def rename_kv_file(): """Rename the generated kv file to be compatible with the original kivy kv file detection of `App.load_kv`. """ import os package_dir = '{{cookiecutter.repo_name}}' old_kv_file = os.path.join( package_dir, '{{cookiecutter.app_class_name}}.kv' ) lower_app_class_name = '{{cookiecutter.app_class_name}}'.lower() if (lower_app_class_name.endswith('app')): lower_app_class_name = lower_app_class_name[:-3] new_kv_file = os.path.join( package_dir, '{}.kv'.format(lower_app_class_name) ) os.rename(old_kv_file, new_kv_file) rename_kv_file()
Use a function to rename the kv file in hooks
Use a function to rename the kv file in hooks
Python
mit
hackebrot/cookiedozer,hackebrot/cookiedozer
--- +++ @@ -1,19 +1,25 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -"""Rename the generated kv file to be compatible with the original kivy kv file -detection of `App.load_kv`. -""" -import os +def rename_kv_file(): + """Rename the generated kv file to be compatible with the original kivy kv + file detection of `App.load_kv`. + """ + import os + package_dir = '{{cookiecutter.repo_name}}' + old_kv_file = os.path.join( + package_dir, '{{cookiecutter.app_class_name}}.kv' + ) + + lower_app_class_name = '{{cookiecutter.app_class_name}}'.lower() + if (lower_app_class_name.endswith('app')): + lower_app_class_name = lower_app_class_name[:-3] + new_kv_file = os.path.join( + package_dir, '{}.kv'.format(lower_app_class_name) + ) + + os.rename(old_kv_file, new_kv_file) -package_dir = '{{cookiecutter.repo_name}}' -old_kv_file = os.path.join(package_dir, '{{cookiecutter.app_class_name}}.kv') - -lower_app_class_name = '{{cookiecutter.app_class_name}}'.lower() -if (lower_app_class_name.endswith('app')): - lower_app_class_name = lower_app_class_name[:-3] -new_kv_file = os.path.join(package_dir, '{}.kv'.format(lower_app_class_name)) - -os.rename(old_kv_file, new_kv_file) +rename_kv_file()
bc32d6456dc2c2b6cef5d2d7b1ccf602b43b1e69
crabpy/client.py
crabpy/client.py
from suds.client import Client def crab_factory(**kwargs): if 'wsdl' in kwargs: wsdl = kwargs['wsdl'] del kwargs['wsdl'] else: wsdl = "http://crab.agiv.be/wscrab/wscrab.svc?wsdl" if 'proxy' in kwargs: proxy = kwargs['proxy'] del kwargs['proxy'] c = Client( wsdl, **kwargs ) return c
from suds.client import Client def crab_factory(**kwargs): if 'wsdl' in kwargs: wsdl = kwargs['wsdl'] del kwargs['wsdl'] else: wsdl = "http://crab.agiv.be/wscrab/wscrab.svc?wsdl" if 'proxy' in kwargs: proxy = kwargs['proxy'] del kwargs['proxy'] c = Client( wsdl, **kwargs ) return c def capakey_factory(**kwargs): from suds.wsse import Security from suds_passworddigest.token import UsernameDigestToken from datetime import datetime if 'wsdl' in kwargs: wsdl = kwargs['wsdl'] del kwargs['wsdl'] else: wsdl = "http://ws.agiv.be/capakeyws/nodataset.asmx?WSDL" if 'user' in kwargs and 'password' in kwargs: user = kwargs['user'] password = kwargs['password'] del kwargs['user'] del kwargs['password'] else: raise ValueError( "You must specify a 'user' and a 'password'." ) if 'proxy' in kwargs: proxy = kwargs['proxy'] del kwargs['proxy'] c = Client( wsdl, **kwargs ) security = Security() token = UsernameDigestToken(user, password) # Service can't handle microseconds. utc = datetime.utcnow() utc = datetime(utc.year, utc.month, utc.day, utc.hour, utc.minute, utc.second, tzinfo=utc.tzinfo) token.setcreated(utc) security.tokens.append(token) c.set_options(wsse=security) return c def capakey_request(client, action, *args): from crabpy.wsa import Action, MessageID, To cm = getattr(client.service, action) a = Action(cm.method.soap.action) mid = MessageID() t = To('http://ws.agiv.be/capakeyws/nodataset.asmx') client.set_options(soapheaders=[a.xml(), t.xml(), mid.xml()]) return getattr(client.service, action)(*args)
Add factory for capakey and utility method for doing a request.
Add factory for capakey and utility method for doing a request.
Python
mit
kmillet/crabpytest,OnroerendErfgoed/crabpy,kmillet/crabpytest
--- +++ @@ -14,4 +14,50 @@ **kwargs ) return c - + + +def capakey_factory(**kwargs): + from suds.wsse import Security + from suds_passworddigest.token import UsernameDigestToken + from datetime import datetime + + if 'wsdl' in kwargs: + wsdl = kwargs['wsdl'] + del kwargs['wsdl'] + else: + wsdl = "http://ws.agiv.be/capakeyws/nodataset.asmx?WSDL" + if 'user' in kwargs and 'password' in kwargs: + user = kwargs['user'] + password = kwargs['password'] + del kwargs['user'] + del kwargs['password'] + else: + raise ValueError( + "You must specify a 'user' and a 'password'." + ) + if 'proxy' in kwargs: + proxy = kwargs['proxy'] + del kwargs['proxy'] + c = Client( + wsdl, + **kwargs + ) + security = Security() + token = UsernameDigestToken(user, password) + # Service can't handle microseconds. + utc = datetime.utcnow() + utc = datetime(utc.year, utc.month, utc.day, utc.hour, utc.minute, utc.second, tzinfo=utc.tzinfo) + token.setcreated(utc) + security.tokens.append(token) + c.set_options(wsse=security) + return c + + +def capakey_request(client, action, *args): + from crabpy.wsa import Action, MessageID, To + cm = getattr(client.service, action) + a = Action(cm.method.soap.action) + mid = MessageID() + t = To('http://ws.agiv.be/capakeyws/nodataset.asmx') + client.set_options(soapheaders=[a.xml(), t.xml(), mid.xml()]) + return getattr(client.service, action)(*args)
b3892da60507855aea56c5f0023187a196f87aff
axes/__init__.py
axes/__init__.py
import logging import os from django.conf import settings VERSION = (1, 2, 9) def get_version(): return '%s.%s.%s' % VERSION try: LOGFILE = os.path.join(settings.DIRNAME, 'axes.log') except (ImportError, AttributeError): # if we have any problems, we most likely don't have a settings module # loaded pass else: try: # check for existing logging configuration # valid for Django>=1.3 if settings.LOGGING: pass except: log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt='%a, %d %b %Y %H:%M:%S', filename=LOGFILE, filemode='w') fileLog = logging.FileHandler(LOGFILE, 'w') fileLog.setLevel(logging.DEBUG) # set a format which is simpler for console use console_format = '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s' formatter = logging.Formatter(console_format) # tell the handler to use this format fileLog.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(fileLog)
import logging import os VERSION = (1, 2, 9) def get_version(): return '%s.%s.%s' % VERSION try: # check for existing logging configuration # valid for Django>=1.3 from django.conf import settings if settings.LOGGING: pass except ImportError: # if we have any problems, we most likely don't have a settings module # loaded pass except AttributeError: # fallback configuration if there is no logging configuration LOGFILE = os.path.join(settings.DIRNAME, 'axes.log') log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' logging.basicConfig(level=logging.DEBUG, format=log_format, datefmt='%a, %d %b %Y %H:%M:%S', filename=LOGFILE, filemode='w') fileLog = logging.FileHandler(LOGFILE, 'w') fileLog.setLevel(logging.DEBUG) # set a format which is simpler for console use console_format = '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s' formatter = logging.Formatter(console_format) # tell the handler to use this format fileLog.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(fileLog)
Refactor for better logical flow.
Refactor for better logical flow.
Python
mit
SteveByerly/django-axes,grue/django-axes,nidhi-delhivery/django-axes,jazzband/django-axes,SteveByerly/django-axes,django-pci/django-axes,svenhertle/django-axes,zoten/django-axes
--- +++ @@ -1,6 +1,5 @@ import logging import os -from django.conf import settings VERSION = (1, 2, 9) @@ -9,35 +8,35 @@ return '%s.%s.%s' % VERSION try: - LOGFILE = os.path.join(settings.DIRNAME, 'axes.log') -except (ImportError, AttributeError): + # check for existing logging configuration + # valid for Django>=1.3 + from django.conf import settings + if settings.LOGGING: + pass +except ImportError: # if we have any problems, we most likely don't have a settings module # loaded pass -else: - try: - # check for existing logging configuration - # valid for Django>=1.3 - if settings.LOGGING: - pass - except: - log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' - logging.basicConfig(level=logging.DEBUG, - format=log_format, - datefmt='%a, %d %b %Y %H:%M:%S', - filename=LOGFILE, - filemode='w') +except AttributeError: + # fallback configuration if there is no logging configuration + LOGFILE = os.path.join(settings.DIRNAME, 'axes.log') - fileLog = logging.FileHandler(LOGFILE, 'w') - fileLog.setLevel(logging.DEBUG) + log_format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' + logging.basicConfig(level=logging.DEBUG, + format=log_format, + datefmt='%a, %d %b %Y %H:%M:%S', + filename=LOGFILE, + filemode='w') - # set a format which is simpler for console use - console_format = '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s' - formatter = logging.Formatter(console_format) + fileLog = logging.FileHandler(LOGFILE, 'w') + fileLog.setLevel(logging.DEBUG) - # tell the handler to use this format - fileLog.setFormatter(formatter) + # set a format which is simpler for console use + console_format = '%(asctime)s %(name)-12s: %(levelname)-8s %(message)s' + formatter = logging.Formatter(console_format) - # add the handler to the root logger - logging.getLogger('').addHandler(fileLog) + # tell the handler to use this format + fileLog.setFormatter(formatter) + # add the handler to the root logger + logging.getLogger('').addHandler(fileLog)
caf8c08511042db195b359ed7fffac6d567f1e18
virtool/handlers/updates.py
virtool/handlers/updates.py
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): # db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases(repo, server_version) return json_response({ "releases": releases })
import virtool.app import virtool.updates from virtool.handlers.utils import json_response async def get(req): settings = req.app["settings"] repo = settings.get("software_repo") server_version = virtool.app.find_server_version() releases = await virtool.updates.get_releases(repo, server_version) return json_response({ "releases": releases, "current_version": server_version })
Return server version from update API
Return server version from update API
Python
mit
igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool
--- +++ @@ -4,7 +4,6 @@ async def get(req): - # db = req.app["db"] settings = req.app["settings"] repo = settings.get("software_repo") @@ -13,9 +12,6 @@ releases = await virtool.updates.get_releases(repo, server_version) return json_response({ - "releases": releases + "releases": releases, + "current_version": server_version }) - - - -
1e5ec4a2923757ca79c8a55b056fd13872cac963
foyer/tests/test_xml_writer.py
foyer/tests/test_xml_writer.py
import glob import itertools as it import os import parmed as pmd from pkg_resources import resource_filename import pytest from foyer import Forcefield from foyer.tests.utils import atomtype from foyer.xml_writer import write_foyer def test_write_xml(filename, ff_file): structure = pmd.loadfile(filename) forcefield = Forcefield(ff_file) structure.write_foyer('test.xml', forcefield=forcefield) def test_load_xml(): structure = pmd.loadfile(filename) forcefield = Forcefield(ff_file) structure.write_foyer('test.xml', forcefield=forcefield) generated_ff = Forcefield('text.xml')
import parmed as pmd import pytest import os from pkg_resources import resource_filename from foyer import Forcefield from foyer.xml_writer import write_foyer OPLS_TESTFILES_DIR = resource_filename('foyer', 'opls_validation') def test_write_xml(): top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top') gro = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.gro') structure = pmd.load_file(top, xyz=gro) forcefield = Forcefield(name='oplsaa') param_struc = forcefield.apply(structure) param_struc.write_foyer('test.xml', forcefield=forcefield) def test_load_xml(): top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top') gro = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.gro') structure = pmd.load_file(top, xyz=gro) forcefield = Forcefield(name='oplsaa') param_struc = forcefield.apply(structure) param_struc.write_foyer('test.xml', forcefield=forcefield) generated_ff = Forcefield('test.xml')
Update xml writer test to work
Update xml writer test to work
Python
mit
iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer
--- +++ @@ -1,25 +1,30 @@ -import glob -import itertools as it +import parmed as pmd +import pytest import os -import parmed as pmd from pkg_resources import resource_filename -import pytest - from foyer import Forcefield -from foyer.tests.utils import atomtype from foyer.xml_writer import write_foyer -def test_write_xml(filename, ff_file): - structure = pmd.loadfile(filename) - forcefield = Forcefield(ff_file) - structure.write_foyer('test.xml', forcefield=forcefield) +OPLS_TESTFILES_DIR = resource_filename('foyer', 'opls_validation') + +def test_write_xml(): + top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top') + gro = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.gro') + structure = pmd.load_file(top, xyz=gro) + forcefield = Forcefield(name='oplsaa') + param_struc = forcefield.apply(structure) + + param_struc.write_foyer('test.xml', forcefield=forcefield) def test_load_xml(): - structure = pmd.loadfile(filename) - forcefield = Forcefield(ff_file) + top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top') + gro = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.gro') + structure = pmd.load_file(top, xyz=gro) + forcefield = Forcefield(name='oplsaa') + param_struc = forcefield.apply(structure) - structure.write_foyer('test.xml', forcefield=forcefield) + param_struc.write_foyer('test.xml', forcefield=forcefield) - generated_ff = Forcefield('text.xml') + generated_ff = Forcefield('test.xml')
142b9fa072e5958273e67ff38f8c7c7f6ea51373
laboratory/exceptions.py
laboratory/exceptions.py
class LaboratoryException(Exception): pass class MismatchException(LaboratoryException): pass
class LaboratoryException(Exception): def __init__(self, message, *a, **kw): self.message = message super(LaboratoryException, self).__init__(*a, **kw) class MismatchException(LaboratoryException): pass
Add message attr to LaboratoryException
Add message attr to LaboratoryException
Python
mit
joealcorn/laboratory
--- +++ @@ -1,5 +1,7 @@ class LaboratoryException(Exception): - pass + def __init__(self, message, *a, **kw): + self.message = message + super(LaboratoryException, self).__init__(*a, **kw) class MismatchException(LaboratoryException):
e6c3b8960213fecdd6392457124bf20b66a164ff
pytest_assume/plugin.py
pytest_assume/plugin.py
import pytest import inspect import os.path def pytest_namespace(): def assume(expr, msg=''): if not expr: # get filename, line, and context (filename, line, funcname, contextlist) = inspect.stack()[1][1:5] filename = os.path.basename(filename) context = contextlist[0] # format entry msg = '%s\n' % msg if msg else '' entry = '>%s%s%s:%s\n--------' % (context, msg, filename, line) # add entry pytest._failed_assumptions.append(entry) return {'_failed_assumptions': [], 'assume': assume} def pytest_runtest_setup(item): del pytest._failed_assumptions[:] @pytest.mark.hookwrapper def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() if call.when == "call" and pytest._failed_assumptions: summary = 'Failed Assumptions:%s' % len(pytest._failed_assumptions) pytest._failed_assumptions.append(summary) if report.longrepr: report.longrepr = str(report.longrepr) + \ '\n--------\n' + ('\n'.join(pytest._failed_assumptions)) else: report.longrepr = '\n'.join(pytest._failed_assumptions) report.outcome = "failed"
import pytest import inspect import os.path def pytest_namespace(): def assume(expr, msg=''): if not expr: # get filename, line, and context (filename, line, funcname, contextlist) = inspect.stack()[1][1:5] filename = os.path.relpath(filename) context = contextlist[0] # format entry msg = '%s\n' % msg if msg else '' entry = '>%s%s%s:%s\n--------' % (context, msg, filename, line) # add entry pytest._failed_assumptions.append(entry) return {'_failed_assumptions': [], 'assume': assume} def pytest_runtest_setup(item): del pytest._failed_assumptions[:] @pytest.mark.hookwrapper def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() if call.when == "call" and pytest._failed_assumptions: summary = 'Failed Assumptions:%s' % len(pytest._failed_assumptions) pytest._failed_assumptions.append(summary) if report.longrepr: report.longrepr = str(report.longrepr) + \ '\n--------\n' + ('\n'.join(pytest._failed_assumptions)) else: report.longrepr = '\n'.join(pytest._failed_assumptions) report.outcome = "failed"
Use relative path instead of only filename
Use relative path instead of only filename
Python
mit
astraw38/pytest-assume
--- +++ @@ -7,7 +7,7 @@ if not expr: # get filename, line, and context (filename, line, funcname, contextlist) = inspect.stack()[1][1:5] - filename = os.path.basename(filename) + filename = os.path.relpath(filename) context = contextlist[0] # format entry msg = '%s\n' % msg if msg else ''
a000706bba6cdd02da4fff4ca16063d43ed8fe85
greenfan/management/commands/create-job-from-testspec.py
greenfan/management/commands/create-job-from-testspec.py
# # Copyright 2012 Cisco Systems, Inc. # # Author: Soren Hansen <sorhanse@cisco.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. # from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) job = ts.create_job() return 'Created job %r' % job.pk
# # Copyright 2012 Cisco Systems, Inc. # # Author: Soren Hansen <sorhanse@cisco.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. # from django.core.management.base import BaseCommand from greenfan.models import TestSpecification class Command(BaseCommand): def handle(self, ts_id, **options): ts = TestSpecification.objects.get(id=ts_id) job = ts.create_job() return 'Created job %d' % job.pk
Make output more easily parsable
Make output more easily parsable
Python
apache-2.0
sorenh/python-django-greenfan,sorenh/python-django-greenfan
--- +++ @@ -25,4 +25,4 @@ ts = TestSpecification.objects.get(id=ts_id) job = ts.create_job() - return 'Created job %r' % job.pk + return 'Created job %d' % job.pk
d9349d617a504381d65f412930126de8e7548300
setup/create_divisions.py
setup/create_divisions.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_divisions_config.txt') lines = [l.strip() for l in open(div_src_file).readlines()] with session_scope() as session: try: for line in lines: if line.startswith("#"): continue division_name, season, teams, conference = line.split(";") season = int(season) team_abbrs = teams[1:-1].split(',') teams = list() for t in team_abbrs: team = Team.find(t) teams.append(team) else: if conference: division = Division( division_name, season, teams, conference) else: division = Division( division_name, season, teams) session.add(division) print(division) session.commit() except: session.rollback() traceback.print_exc()
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import traceback from db.common import session_scope from db.team import Team from db.division import Division def create_divisions(div_src_file=None): if not div_src_file: div_src_file = os.path.join( os.path.dirname(__file__), 'nhl_divisions_config.txt') lines = [l.strip() for l in open(div_src_file).readlines()] with session_scope() as session: session.query(Division).delete(synchronize_session=False) try: for line in lines: if line.startswith("#"): continue division_name, season, teams, conference = line.split(";") season = int(season) team_abbrs = teams[1:-1].split(',') teams = list() for t in team_abbrs: team = Team.find(t) teams.append(team) else: if conference: division = Division( division_name, season, teams, conference) else: division = Division( division_name, season, teams) session.add(division) print(division) session.commit() except Exception as e: session.rollback() traceback.print_exc()
Truncate target table before creating division items
Truncate target table before creating division items
Python
mit
leaffan/pynhldb
--- +++ @@ -18,6 +18,9 @@ lines = [l.strip() for l in open(div_src_file).readlines()] with session_scope() as session: + + session.query(Division).delete(synchronize_session=False) + try: for line in lines: if line.startswith("#"): @@ -42,6 +45,6 @@ session.commit() - except: + except Exception as e: session.rollback() traceback.print_exc()
fe6a1134a26f72833bcdfe16766fa0376396df4e
jinger/server.py
jinger/server.py
import os from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from jinja2 import Environment, FileSystemLoader from jinger.config import get_config env = None class Http404(Exception): pass class JingerHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() try: self.wfile.write(get_html(self.path)) except Http404: self.send_error(404, 'Template not found for path: %s' % self.path) def get_html(path): global env templatepath = os.path.abspath(os.path.join(*tuple([s for s in path.split() if s]))) try: return env.get_template(templatepath).generate() except IOError: raise Http404 def startserver(port): global env conf = get_config(os.getcwd()) env = Environment(loader=FileSystemLoader(conf['sourcedir'])) try: server = HTTPServer(('', int(port)), JingerHTTPRequestHandler) print 'Development server started at 127.0.0.1 on port %s' % port server.serve_forever() except KeyboardInterrupt: print 'Shutting down server' server.socket.close() if __name__ == '__main__': startserver()
import os from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from jinja2 import Environment, FileSystemLoader from jinger.config import get_config env = None class Http404(Exception): pass class JingerHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() try: self.wfile.write(get_html(self.path)) except Http404: self.send_error(404, 'Template not found for path: %s' % self.path) def get_html(path): global env templatepath = os.path.abspath(os.path.join(*tuple([s for s in path.split() if s]))) try: return env.get_template(templatepath).render() except IOError: raise Http404 def startserver(port): global env conf = get_config(os.getcwd()) env = Environment(loader=FileSystemLoader(conf['sourcedir'])) try: server = HTTPServer(('', int(port)), JingerHTTPRequestHandler) print 'Development server started at 127.0.0.1 on port %s' % port server.serve_forever() except KeyboardInterrupt: print 'Shutting down server' server.socket.close() if __name__ == '__main__': startserver()
Fix generator being passed to the wfile.write method of the HttpHandler instead of string
Fix generator being passed to the wfile.write method of the HttpHandler instead of string
Python
mit
naiquevin/jinger,naiquevin/jinger
--- +++ @@ -28,7 +28,7 @@ global env templatepath = os.path.abspath(os.path.join(*tuple([s for s in path.split() if s]))) try: - return env.get_template(templatepath).generate() + return env.get_template(templatepath).render() except IOError: raise Http404
8b5bab10bf49f35c0c0e9147e7bcbffb88f8b536
django_mailer/managers.py
django_mailer/managers.py
from django.db import models from django_mailer import constants class QueueManager(models.Manager): use_for_related_fields = True def high_priority(self): """ Return a QuerySet of high priority queued messages. """ return self.filter(priority=constants.PRIORITY_HIGH) def normal_priority(self): """ Return a QuerySet of normal priority queued messages. """ return self.filter(priority=constants.PRIORITY_NORMAL) def low_priority(self): """ Return a QuerySet of low priority queued messages. """ return self.filter(priority=constants.PRIORITY_LOW) def non_deferred(self): """ Return a QuerySet containing all non-deferred queued messages. """ return self.filter(deferred=False) def deferred(self): """ Return a QuerySet of all deferred messages in the queue. """ return self.filter(deferred=True) def retry_deferred(self, new_priority=None): """ Reset the deferred flag for all deferred messages so they will be retried. """ count = self.deferred().count() update_kwargs = dict(deferred=False, retries=models.F('retries')+1) if new_priority is not None: update_kwargs['priority'] = new_priority self.deferred().update(**update_kwargs) return count
from django.db import models from django_mailer import constants class QueueManager(models.Manager): use_for_related_fields = True def high_priority(self): """ Return a QuerySet of high priority queued messages. """ return self.filter(priority=constants.PRIORITY_HIGH) def normal_priority(self): """ Return a QuerySet of normal priority queued messages. """ return self.filter(priority=constants.PRIORITY_NORMAL) def low_priority(self): """ Return a QuerySet of low priority queued messages. """ return self.filter(priority=constants.PRIORITY_LOW) def non_deferred(self): """ Return a QuerySet containing all non-deferred queued messages. """ return self.filter(deferred=None) def deferred(self): """ Return a QuerySet of all deferred messages in the queue. """ return self.exclude(deferred=None) def retry_deferred(self, new_priority=None): """ Reset the deferred flag for all deferred messages so they will be retried. """ count = self.deferred().count() update_kwargs = dict(deferred=False, retries=models.F('retries')+1) if new_priority is not None: update_kwargs['priority'] = new_priority self.deferred().update(**update_kwargs) return count
Fix the manager methods for deferred/non_deferred
Fix the manager methods for deferred/non_deferred
Python
mit
APSL/django-mailer-2,pegler/django-mailer-2,tclancy/django-mailer-2,davidmarble/django-mailer-2,maykinmedia/django-mailer-2,Giftovus/django-mailer-2,torchbox/django-mailer-2,APSL/django-mailer-2,SmileyChris/django-mailer-2,victorfontes/django-mailer-2,mfwarren/django-mailer-2,morenopc/django-mailer-2,k1000/django-mailer-2,GreenLightGo/django-mailer-2,damkop/django-mailer-2,kvh/django-mailer-2,shn/django-mailer-2,APSL/django-mailer-2,danfairs/django-mailer-2,colinhowe/django-mailer-2,tsanders-kalloop/django-mailer-2,tachang/django-mailer-2,maykinmedia/django-mailer-2,maykinmedia/django-mailer-2,rofrankel/django-mailer-2,PSyton/django-mailer-2,mrbox/django-mailer-2,fenginx/django-mailer-2
--- +++ @@ -31,14 +31,14 @@ Return a QuerySet containing all non-deferred queued messages. """ - return self.filter(deferred=False) + return self.filter(deferred=None) def deferred(self): """ Return a QuerySet of all deferred messages in the queue. """ - return self.filter(deferred=True) + return self.exclude(deferred=None) def retry_deferred(self, new_priority=None): """
af9c686750d55ff786807f9175faadb8bb9087e7
test_quick_sort.py
test_quick_sort.py
from random import shuffle import pytest from quick_sort import quick_srt def test_quick_srt(): expected = range(20) actual = expected[:] shuffle(actual) quick_srt(actual) assert expected == actual def test_quick_srt_with_duplicates(): expected = [1, 3, 3, 6, 7, 8, 8, 8] actual = expected[:] shuffle(actual) quick_srt(actual) assert expected == actual def test_quick_sort_wrong_type(): with pytest.raises(TypeError): quick_srt(15)
from random import shuffle import pytest from quick_sort import quick_srt def test_quick_srt(): expected = range(20) actual = expected[:] shuffle(actual) quick_srt(actual) assert expected == actual def test_quick_srt_with_duplicates(): expected = [1, 3, 3, 6, 7, 8, 8, 8] actual = expected[:] shuffle(actual) quick_srt(actual) assert expected == actual def test_quick_srt_with_zero_items(): expected = [] actual = [] quick_srt(actual) assert expected == actual def test_quick_srt_with_one_item(): expected = [1] actual = [1] quick_srt(actual) assert expected == actual def test_quick_sort_wrong_type(): with pytest.raises(TypeError): quick_srt(15)
Add a few more tests for edge cases
Add a few more tests for edge cases
Python
mit
jonathanstallings/data-structures
--- +++ @@ -20,6 +20,20 @@ assert expected == actual +def test_quick_srt_with_zero_items(): + expected = [] + actual = [] + quick_srt(actual) + assert expected == actual + + +def test_quick_srt_with_one_item(): + expected = [1] + actual = [1] + quick_srt(actual) + assert expected == actual + + def test_quick_sort_wrong_type(): with pytest.raises(TypeError): quick_srt(15)
09668c1818ef028e10669b9652e2f0ae255cc47e
src/pyscaffold/extensions/no_skeleton.py
src/pyscaffold/extensions/no_skeleton.py
# -*- coding: utf-8 -*- """ Extension that omits the creation of file `skeleton.py` """ from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = [opts['project'], 'src', opts['package'], 'skeleton.py'] struct = helpers.reject(struct, file) file = [opts['project'], 'tests', 'test_skeleton.py'] struct = helpers.reject(struct, file) return struct, opts
# -*- coding: utf-8 -*- """ Extension that omits the creation of file `skeleton.py` """ from pathlib import PurePath as Path from ..api import Extension, helpers class NoSkeleton(Extension): """Omit creation of skeleton.py and test_skeleton.py""" def activate(self, actions): """Activate extension Args: actions (list): list of actions to perform Returns: list: updated list of actions """ return self.register( actions, self.remove_files, after='define_structure') def remove_files(self, struct, opts): """Remove all skeleton files from structure Args: struct (dict): project representation as (possibly) nested :obj:`dict`. opts (dict): given options, see :obj:`create_project` for an extensive list. Returns: struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough file = Path(opts['project'], 'src', opts['package'], 'skeleton.py') struct = helpers.reject(struct, file) file = Path(opts['project'], 'tests', 'test_skeleton.py') struct = helpers.reject(struct, file) return struct, opts
Change extensions to use pathlib in helpers instead of lists
Change extensions to use pathlib in helpers instead of lists
Python
mit
blue-yonder/pyscaffold,blue-yonder/pyscaffold
--- +++ @@ -2,6 +2,8 @@ """ Extension that omits the creation of file `skeleton.py` """ + +from pathlib import PurePath as Path from ..api import Extension, helpers @@ -35,8 +37,8 @@ struct, opts: updated project representation and options """ # Namespace is not yet applied so deleting from package is enough - file = [opts['project'], 'src', opts['package'], 'skeleton.py'] + file = Path(opts['project'], 'src', opts['package'], 'skeleton.py') struct = helpers.reject(struct, file) - file = [opts['project'], 'tests', 'test_skeleton.py'] + file = Path(opts['project'], 'tests', 'test_skeleton.py') struct = helpers.reject(struct, file) return struct, opts
27d34d851bcdf80559aff5f5d8cf83122da1953a
amqpy/concurrency.py
amqpy/concurrency.py
import logging import time from functools import wraps from . import compat compat.patch() # monkey-patch time.perf_counter log = logging.getLogger('amqpy') def synchronized(lock_name): """Decorator for automatically acquiring and releasing lock for method call This decorator accesses the `lock_name` :class:`threading.Lock` attribute of the instance that the wrapped method is bound to. The lock is acquired (blocks indefinitely) before the method is called. After the method has executed, the lock is released. Decorated methods should not be long-running operations, since the lock is held for the duration of the method's execution. :param lock_name: name of :class:`threading.Lock` object """ def decorator(f): @wraps(f) def wrapper(self, *args, **kwargs): lock = getattr(self, lock_name) acquired = lock.acquire(False) if not acquired: # log.debug('> Wait to acquire lock for [{}]'.format(f.__qualname__)) start_time = time.perf_counter() lock.acquire() tot_time = time.perf_counter() - start_time if tot_time > 10: # only log if waited for more than 10s to acquire lock log.debug('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time)) try: retval = f(self, *args, **kwargs) finally: lock.release() return retval return wrapper return decorator
import logging import time from functools import wraps from . import compat compat.patch() # monkey-patch time.perf_counter log = logging.getLogger('amqpy') def synchronized(lock_name): """Decorator for automatically acquiring and releasing lock for method call This decorator accesses the `lock_name` :class:`threading.Lock` attribute of the instance that the wrapped method is bound to. The lock is acquired (blocks indefinitely) before the method is called. After the method has executed, the lock is released. Decorated methods should not be long-running operations, since the lock is held for the duration of the method's execution. :param lock_name: name of :class:`threading.Lock` object """ def decorator(f): @wraps(f) def wrapper(self, *args, **kwargs): lock = getattr(self, lock_name) acquired = lock.acquire(False) if not acquired: # log.debug('> Wait to acquire lock for [{}]'.format(f.__qualname__)) start_time = time.perf_counter() lock.acquire() tot_time = time.perf_counter() - start_time if tot_time > 10: # only log if waited for more than 10s to acquire lock log.warn('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time)) try: retval = f(self, *args, **kwargs) finally: lock.release() return retval return wrapper return decorator
Change log level to warning
Change log level to warning
Python
mit
gst/amqpy,veegee/amqpy
--- +++ @@ -34,7 +34,7 @@ tot_time = time.perf_counter() - start_time if tot_time > 10: # only log if waited for more than 10s to acquire lock - log.debug('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time)) + log.warn('Acquired lock for [{}] in: {:.3f}s'.format(f.__qualname__, tot_time)) try: retval = f(self, *args, **kwargs) finally:
221caf718c5aa53c2ef5b9b05c72764ae65eac44
SaudiStudentOrganization/models.py
SaudiStudentOrganization/models.py
from __future__ import unicode_literals from django.db import models # Create your models here.
from __future__ import unicode_literals from django.db import models class Student(models.Model): Frist_Name = models.CharField(max_length=200) Last_Name = models.CharField(max_length=200) Email = models.CharField(max_length=200) Phone_Number = models.CharField(max_length=200) class Responds(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) Response_Date_Time = models.DateTimeField('date responded')
Change to model from class on 10/10/2016
Change to model from class on 10/10/2016
Python
mit
UniversityOfDubuque/CIS405_DjangoProject,UniversityOfDubuque/CIS405_DjangoProject
--- +++ @@ -2,4 +2,12 @@ from django.db import models -# Create your models here. +class Student(models.Model): + Frist_Name = models.CharField(max_length=200) + Last_Name = models.CharField(max_length=200) + Email = models.CharField(max_length=200) + Phone_Number = models.CharField(max_length=200) + +class Responds(models.Model): + student = models.ForeignKey(Student, on_delete=models.CASCADE) + Response_Date_Time = models.DateTimeField('date responded')
4b6afd36114fbe1871f17998f9e3f4ec0e116f0f
spacy/lang/en/__init__.py
spacy/lang/en/__init__.py
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups from ...util import load_config_from_str DEFAULT_CONFIG = """ [initialize] [initialize.lookups] @misc = "spacy.LookupsDataLoader.v1" lang = ${nlp.lang} tables = ["lexeme_norm"] """ class EnglishDefaults(Language.Defaults): config = load_config_from_str(DEFAULT_CONFIG) tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS syntax_iterators = SYNTAX_ITERATORS stop_words = STOP_WORDS class English(Language): lang = "en" Defaults = EnglishDefaults @English.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "lookups": None}, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, lookups: Optional[Lookups], ): lookups = EnglishLemmatizer.load_lookups(nlp.lang, mode, lookups) return EnglishLemmatizer(nlp.vocab, model, name, mode=mode, lookups=lookups) __all__ = ["English"]
from typing import Optional from thinc.api import Model from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS from .stop_words import STOP_WORDS from .lex_attrs import LEX_ATTRS from .syntax_iterators import SYNTAX_ITERATORS from .punctuation import TOKENIZER_INFIXES from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups class EnglishDefaults(Language.Defaults): tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS syntax_iterators = SYNTAX_ITERATORS stop_words = STOP_WORDS class English(Language): lang = "en" Defaults = EnglishDefaults @English.factory( "lemmatizer", assigns=["token.lemma"], default_config={"model": None, "mode": "rule", "lookups": None}, default_score_weights={"lemma_acc": 1.0}, ) def make_lemmatizer( nlp: Language, model: Optional[Model], name: str, mode: str, lookups: Optional[Lookups], ): lookups = EnglishLemmatizer.load_lookups(nlp.lang, mode, lookups) return EnglishLemmatizer(nlp.vocab, model, name, mode=mode, lookups=lookups) __all__ = ["English"]
Remove English [initialize] default block for now to get tests to pass
Remove English [initialize] default block for now to get tests to pass
Python
mit
spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy
--- +++ @@ -9,21 +9,9 @@ from .lemmatizer import EnglishLemmatizer from ...language import Language from ...lookups import Lookups -from ...util import load_config_from_str - - -DEFAULT_CONFIG = """ -[initialize] - -[initialize.lookups] -@misc = "spacy.LookupsDataLoader.v1" -lang = ${nlp.lang} -tables = ["lexeme_norm"] -""" class EnglishDefaults(Language.Defaults): - config = load_config_from_str(DEFAULT_CONFIG) tokenizer_exceptions = TOKENIZER_EXCEPTIONS infixes = TOKENIZER_INFIXES lex_attr_getters = LEX_ATTRS
fffe7392cb486f7218fc8afd2d42769660a1f558
tests/test_main.py
tests/test_main.py
# -*- coding:utf-8 -*- from subprocess import check_call from pytest import raises from csft import __main__ as main def test_call(): check_call(['python', '-m', 'csft', '.']) def test_main(): main.main(argv=['.']) with raises(SystemExit): main.main(argv=[])
# -*- coding:utf-8 -*- from subprocess import check_call from pytest import raises from csft import __main__ as main def test_call(): check_call(['python', '-m', 'csft', '.']) def test_main(): main.main(argv=['.']) with raises(SystemExit): main.main(argv=[]) with raises(TypeError): main.main(argv=['path/is/not/a/directory'])
Test when path not is a directory.
Test when path not is a directory.
Python
mit
yanqd0/csft
--- +++ @@ -16,3 +16,6 @@ with raises(SystemExit): main.main(argv=[]) + + with raises(TypeError): + main.main(argv=['path/is/not/a/directory'])
bc485e3deb47897fb5d87c80c299f2da240419db
app/__init__.py
app/__init__.py
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oa = OAuth() lm = LoginManager() lm.login_view = "main.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oa.init_app(app) from app.views.main import main from app.views.oauth import oauth app.register_blueprint(main) app.register_blueprint(oauth) from app.converters import WordClassConverter app.url_map.converters["word_class"] = WordClassConverter return app
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_oauthlib.client import OAuth from config import config db = SQLAlchemy() oa = OAuth() lm = LoginManager() lm.login_view = "main.login" from app.models import User @lm.user_loader def load_user(id): return User.query.get(int(id)) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) lm.init_app(app) oa.init_app(app) from app.converters import WordClassConverter app.url_map.converters["word_class"] = WordClassConverter from app.views.main import main from app.views.oauth import oauth app.register_blueprint(main) app.register_blueprint(oauth) return app
Add converter before blueprint registration
Add converter before blueprint registration
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
--- +++ @@ -26,12 +26,12 @@ lm.init_app(app) oa.init_app(app) + from app.converters import WordClassConverter + app.url_map.converters["word_class"] = WordClassConverter + from app.views.main import main from app.views.oauth import oauth app.register_blueprint(main) app.register_blueprint(oauth) - from app.converters import WordClassConverter - app.url_map.converters["word_class"] = WordClassConverter - return app
c85fbf33d22a9775f9d22b863027eb50b41923c2
src/excel_sheet_column_title.py
src/excel_sheet_column_title.py
""" Source : https://oj.leetcode.com/problems/excel-sheet-column-number/ Author : Changxi Wu Date : 2015-01-21 Given a column title as appear in an Excel sheet, return its corresponding column number. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB """ # @return a string def convertToTitle(num): if __name__ == '__main__': test = [1:'A', 2:'B', 3:'C', 26:'Z', 27:'AA', 28:'AB']
""" Source : https://oj.leetcode.com/problems/excel-sheet-column-number/ Author : Changxi Wu Date : 2015-01-21 Given a column title as appear in an Excel sheet, return its corresponding column number. For example: 1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB 732 -> ABC """ # @return a string def convertToTitle(num): remainders = [] quotient = num while quotient > 26: remainder = quotient%26 or 26 quotient = (quotient-remainder)/26 remainders.append(remainder) remainders.append(quotient) chars = [] for i in reversed(remainders): chars.append(chr(i+ord('A')-1)) return ''.join(chars) if __name__ == '__main__': test = {1:'A', 2:'B', 3:'C', 26:'Z', 27:'AA', 28:'AB', 52:'AZ', 731:'ABC'} for k,v in test.iteritems(): output = convertToTitle(k) if v != output: print 'Input:', k print 'Output:', output print 'Expected:', v
Add solution for excel sheet column title
Add solution for excel sheet column title
Python
mit
chancyWu/leetcode
--- +++ @@ -13,11 +13,28 @@ 26 -> Z 27 -> AA 28 -> AB + 732 -> ABC """ # @return a string def convertToTitle(num): - + remainders = [] + quotient = num + while quotient > 26: + remainder = quotient%26 or 26 + quotient = (quotient-remainder)/26 + remainders.append(remainder) + remainders.append(quotient) + chars = [] + for i in reversed(remainders): + chars.append(chr(i+ord('A')-1)) + return ''.join(chars) if __name__ == '__main__': - test = [1:'A', 2:'B', 3:'C', 26:'Z', 27:'AA', 28:'AB'] + test = {1:'A', 2:'B', 3:'C', 26:'Z', 27:'AA', 28:'AB', 52:'AZ', 731:'ABC'} + for k,v in test.iteritems(): + output = convertToTitle(k) + if v != output: + print 'Input:', k + print 'Output:', output + print 'Expected:', v
0baf08c61348f4fa6a657e1c0e2ff9bdf65eaa15
leetcode/RemoveElement.py
leetcode/RemoveElement.py
# Remove Element https://oj.leetcode.com/problems/remove-element/ # Given an array and a value, remove all instances of that value in place and return the new length. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. #Arrays # Xilin SUN # Jan 8 2015 # Don't forget to return 0 if A == []. class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if len(A) == 0: return 0 else: k=0 for i in range(0, len(A)): if A[i] != elem: A[k] = A[i] k += 1 return k
# Remove Element https://oj.leetcode.com/problems/remove-element/ # Given an array and a value, remove all instances of that value in place and return the new length. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. #Arrays # Xilin SUN # Jan 8 2015 # Don't forget to return 0 if A == []. class Solution: # @param A a list of integers # @param elem an integer, value need to be removed # @return an integer def removeElement(self, A, elem): if len(A) == 0: return 0 else: k=0 for i in range(0, len(A)): if A[i] != elem: if i!= k: A[k] = A[i] k += 1 return k
Add one more if to speed up
Add one more if to speed up
Python
mit
aenon/OnlineJudge,aenon/OnlineJudge
--- +++ @@ -20,6 +20,7 @@ k=0 for i in range(0, len(A)): if A[i] != elem: - A[k] = A[i] + if i!= k: + A[k] = A[i] k += 1 return k
6c122daaf50bba2c7c28b67e40b3ca6eb30f99ee
yikbot.py
yikbot.py
import pyak import time class YikBot(Yakker): def boot(self): while True: print "DEBUG: Scanning feed" yaks = yikBot.get_yaks() for yak in yaks: if yak.message.startswith("@yikBot"): yikBot.respond(yak) print "DEBUG: Going to sleep" time.sleep(10) def respond(self, yak): print "DEBUG: Found a targeted yak" yak.add_comment("Hi, I'm yikBot")
import pyak import time class YikBot(pyak.Yakker): def boot(self): while True: print "DEBUG: Scanning feed" yaks = self.get_yaks() for yak in yaks: if yak.message.startswith("@yikBot"): print "DEBUG: Found a targeted yak" self.respond(yak) print "DEBUG: Going to sleep" time.sleep(10) def respond(self, yak): yak.add_comment("Hi, I'm yikBot") def multi_upvote(self, message, count): for i in range(0, count): yakker = pyak.Yakker() print "DEBUG: Registered new user with id %s" % yakker.id yakker.update_location(self.location) yakkers.append(yakker) print "DEBUG: Going to sleep" time.sleep(90) for yakker in yakkers: yaks = yakker.get_yaks() for yak in yaks: if yak.message == message: yak.upvote() print "DEBUG: Upvoted yak" continue def multi_downvote(self, message, count): for i in range(0, count): yakker = pyak.Yakker() print "DEBUG: Registered new user with id %s" % yakker.id yakker.update_location(self.location) yakkers.append(yakker) print "DEBUG: Going to sleep" time.sleep(90) for yakker in yakkers: yaks = yakker.get_yaks() for yak in yaks: if yak.message == message: yak.downvote() print "DEBUG: Downvoted yak" continue
Add capability to upvote/downvote yaks many times
Add capability to upvote/downvote yaks many times
Python
mit
congrieb/yikBot
--- +++ @@ -1,17 +1,53 @@ import pyak import time -class YikBot(Yakker): +class YikBot(pyak.Yakker): def boot(self): while True: print "DEBUG: Scanning feed" - yaks = yikBot.get_yaks() + yaks = self.get_yaks() for yak in yaks: if yak.message.startswith("@yikBot"): - yikBot.respond(yak) + print "DEBUG: Found a targeted yak" + self.respond(yak) print "DEBUG: Going to sleep" time.sleep(10) def respond(self, yak): - print "DEBUG: Found a targeted yak" yak.add_comment("Hi, I'm yikBot") + + def multi_upvote(self, message, count): + for i in range(0, count): + yakker = pyak.Yakker() + print "DEBUG: Registered new user with id %s" % yakker.id + yakker.update_location(self.location) + yakkers.append(yakker) + + print "DEBUG: Going to sleep" + time.sleep(90) + + for yakker in yakkers: + yaks = yakker.get_yaks() + for yak in yaks: + if yak.message == message: + yak.upvote() + print "DEBUG: Upvoted yak" + continue + + def multi_downvote(self, message, count): + for i in range(0, count): + yakker = pyak.Yakker() + print "DEBUG: Registered new user with id %s" % yakker.id + yakker.update_location(self.location) + yakkers.append(yakker) + + print "DEBUG: Going to sleep" + time.sleep(90) + + for yakker in yakkers: + yaks = yakker.get_yaks() + for yak in yaks: + if yak.message == message: + yak.downvote() + print "DEBUG: Downvoted yak" + continue
7a68599ca8794d1d1b7d358e6f79791547f7740f
setuptools/tests/test_build.py
setuptools/tests/test_build.py
from setuptools.dist import Distribution from setuptools.command.build import build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) assert isinstance(dist.get_command_obj("build"), build)
from setuptools.dist import Distribution from setuptools.command.build import build from distutils.command.build import build as distutils_build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): """ Check that the setuptools Distribution uses the setuptools specific build object. """ dist = Distribution(dict( script_name='setup.py', script_args=['build'], packages=[''], package_data={'': ['path/*']}, )) build_obj = dist.get_command_obj("build") assert isinstance(build_obj, build) build_obj.sub_commands.append(("custom_build_subcommand", None)) distutils_subcommands = [cmd[0] for cmd in distutils_build.sub_commands] assert "custom_build_subcommand" not in distutils_subcommands
Test that extending setuptools' build sub_commands does not extend distutils
Test that extending setuptools' build sub_commands does not extend distutils
Python
mit
pypa/setuptools,pypa/setuptools,pypa/setuptools
--- +++ @@ -1,5 +1,6 @@ from setuptools.dist import Distribution from setuptools.command.build import build +from distutils.command.build import build as distutils_build def test_distribution_gives_setuptools_build_obj(tmpdir_cwd): @@ -13,4 +14,11 @@ packages=[''], package_data={'': ['path/*']}, )) - assert isinstance(dist.get_command_obj("build"), build) + + build_obj = dist.get_command_obj("build") + assert isinstance(build_obj, build) + + build_obj.sub_commands.append(("custom_build_subcommand", None)) + + distutils_subcommands = [cmd[0] for cmd in distutils_build.sub_commands] + assert "custom_build_subcommand" not in distutils_subcommands
dd3b135ab5e229c5f717fc4d296389e187a49f9a
one_time_eval.py
one_time_eval.py
# usage: python one_time_eval.py as8sqdtc from deuces.deuces import Card from convenience import find_pcts, pr, str2cards import sys cards_str = sys.argv[1] board_str = '' if len(sys.argv) > 2: board_str = sys.argv[2] cards = str2cards(cards_str) board = str2cards(board_str) assert len(cards) == 4 p1 = cards[0:2] p2 = cards[2:4] pr(p1) pr(p2) print find_pcts(p1, p2, board, iter = 10000)
# usage: python one_time_eval.py as8sqdtc # usage: python one_time_eval.py as8sqdtc 2skskd from convenience import find_pcts, pr, str2cards import sys ## argv to strings hole_cards_str = sys.argv[1] board_str = '' if len(sys.argv) > 2: board_str = sys.argv[2] ## strings to lists of Card objects hole_cards = str2cards(hole_cards_str) board = str2cards(board_str) ## card list to player list-of-lists assert len(hole_cards) % 2 == 0 n_players = len(hole_cards) / 2 assert n_players > 1 p = [] for i in range(n_players): pi = hole_cards[i * 2 : i * 2 + 2] pr(pi) p.append(pi) print "Board", pr(board) print find_pcts(p[0], p[1], board, iter = 10000)
Prepare the main script to accept multi-way pots.
Prepare the main script to accept multi-way pots.
Python
mit
zimolzak/poker-experiments,zimolzak/poker-experiments,zimolzak/poker-experiments
--- +++ @@ -1,21 +1,29 @@ # usage: python one_time_eval.py as8sqdtc +# usage: python one_time_eval.py as8sqdtc 2skskd -from deuces.deuces import Card from convenience import find_pcts, pr, str2cards import sys -cards_str = sys.argv[1] +## argv to strings +hole_cards_str = sys.argv[1] board_str = '' if len(sys.argv) > 2: board_str = sys.argv[2] -cards = str2cards(cards_str) +## strings to lists of Card objects +hole_cards = str2cards(hole_cards_str) board = str2cards(board_str) -assert len(cards) == 4 -p1 = cards[0:2] -p2 = cards[2:4] +## card list to player list-of-lists +assert len(hole_cards) % 2 == 0 +n_players = len(hole_cards) / 2 +assert n_players > 1 +p = [] +for i in range(n_players): + pi = hole_cards[i * 2 : i * 2 + 2] + pr(pi) + p.append(pi) -pr(p1) -pr(p2) -print find_pcts(p1, p2, board, iter = 10000) +print "Board", +pr(board) +print find_pcts(p[0], p[1], board, iter = 10000)
b9156a522410bf39de8653bce22bb2cb56e435a0
parktain/main.py
parktain/main.py
#!/usr/bin/env python from os.path import abspath, dirname, join from gendo import Gendo HERE = dirname(abspath(__file__)) config_path = join(HERE, 'config.yaml') bot = Gendo.config_from_yaml(config_path) @bot.listen_for('morning') def morning(user, message): # make sure message is "morning" and doesn't just contain it. if message.strip() == "morning": return "mornin' @{user.username}" def main(): bot.run() if __name__ == '__main__': main()
#!/usr/bin/env python # Standard library from os.path import abspath, dirname, join import re # 3rd party library from gendo import Gendo class Parktain(Gendo): """Overridden to add simple additional functionality.""" @property def id(self): """Get id of the bot.""" if not hasattr(self, '_id',): self._id = self.client.server.login_data['self']['id'] return self._id @property def username(self): """Get username of the bot.""" if not hasattr(self, '_username',): self._username = self.client.server.username return self.username HERE = dirname(abspath(__file__)) config_path = join(HERE, 'config.yaml') bot = Parktain.config_from_yaml(config_path) def is_mention(f): """Decorator to check if bot is mentioned.""" def wrapped(name, message): BOT_ID_RE = re.compile('<@{}>'.format(bot.id)) mention = BOT_ID_RE.search(message) is not None if mention: return f(name, message) return wrapped @bot.listen_for('morning') def morning(user, message): # make sure message is "morning" and doesn't just contain it. if message.strip() == "morning": return "mornin' @{user.username}" @bot.listen_for('where do you live') @is_mention def source_code(user, message): repo_url = 'https://github.com/punchagan/parktain' message = 'Well, I live in your hearts...\nYou can change me from here {}, though.' return message.format(repo_url) def main(): bot.run() if __name__ == '__main__': main()
Add 'where do you live' answer.
Add 'where do you live' answer.
Python
bsd-3-clause
punchagan/parktain,punchagan/parktain,punchagan/parktain
--- +++ @@ -1,11 +1,48 @@ #!/usr/bin/env python +# Standard library from os.path import abspath, dirname, join +import re + +# 3rd party library from gendo import Gendo + + +class Parktain(Gendo): + """Overridden to add simple additional functionality.""" + + @property + def id(self): + """Get id of the bot.""" + + if not hasattr(self, '_id',): + self._id = self.client.server.login_data['self']['id'] + return self._id + + @property + def username(self): + """Get username of the bot.""" + + if not hasattr(self, '_username',): + self._username = self.client.server.username + return self.username + + HERE = dirname(abspath(__file__)) config_path = join(HERE, 'config.yaml') -bot = Gendo.config_from_yaml(config_path) +bot = Parktain.config_from_yaml(config_path) + +def is_mention(f): + """Decorator to check if bot is mentioned.""" + + def wrapped(name, message): + BOT_ID_RE = re.compile('<@{}>'.format(bot.id)) + mention = BOT_ID_RE.search(message) is not None + if mention: + return f(name, message) + + return wrapped @bot.listen_for('morning') @@ -14,6 +51,15 @@ if message.strip() == "morning": return "mornin' @{user.username}" + +@bot.listen_for('where do you live') +@is_mention +def source_code(user, message): + repo_url = 'https://github.com/punchagan/parktain' + message = 'Well, I live in your hearts...\nYou can change me from here {}, though.' + return message.format(repo_url) + + def main(): bot.run()
5ee77b7294af840a47e11a8a9a3da109e33f4a63
lib/stats_backend.py
lib/stats_backend.py
import platform from stats_file_backend import StatsFileBackend class StatsBackend: """ This is a class to manage the Stats backend. """ def __init__(self, options={}): if options == {}: if platform.system() == "Darwin": # For my local dev I need this hack options = {"db_path":"/tmp/stats.json"} else: options = {"db_path":"/var/lib/omniwallet/www/stats.json"} self.engine = StatsFileBackend(options) def put(self, key, val): self.engine.put(key, val) def increment(self, key): val = self.engine.get(key) if val == None: val = 0 val += 1 self.engine.put(key, val) def get(self, val): return self.engine.get(val) stats = StatsBackend() stats.increment("amount_of_transactions")
import platform from stats_file_backend import StatsFileBackend class StatsBackend: """ This is a class to manage the Stats backend. """ def __init__(self, options={}): if options == {}: if platform.system() == "Darwin": # For my local dev I need this hack options = {"db_path":"/tmp/stats.json"} else: options = {"db_path":"/var/lib/omniwallet/www/stats.json"} self.engine = StatsFileBackend(options) def put(self, key, val): self.engine.put(key, val) def increment(self, key): val = self.engine.get(key) if val == None: val = 0 val += 1 self.engine.put(key, val) def get(self, val): return self.engine.get(val)
Remove some test code that got left behind
Remove some test code that got left behind
Python
agpl-3.0
dexX7/omniwallet,habibmasuro/omniwallet,habibmasuro/omniwallet,achamely/omniwallet,habibmasuro/omniwallet,VukDukic/omniwallet,OmniLayer/omniwallet,dexX7/omniwallet,achamely/omniwallet,OmniLayer/omniwallet,arowser/omniwallet,OmniLayer/omniwallet,arowser/omniwallet,curtislacy/omniwallet,ripper234/omniwallet,FuzzyBearBTC/omniwallet,dexX7/omniwallet,arowser/omniwallet,FuzzyBearBTC/omniwallet,Nevtep/omniwallet,Nevtep/omniwallet,curtislacy/omniwallet,achamely/omniwallet,ripper234/omniwallet,curtislacy/omniwallet,VukDukic/omniwallet,ripper234/omniwallet,Nevtep/omniwallet,OmniLayer/omniwallet,FuzzyBearBTC/omniwallet,VukDukic/omniwallet,Nevtep/omniwallet,habibmasuro/omniwallet,achamely/omniwallet
--- +++ @@ -27,7 +27,3 @@ def get(self, val): return self.engine.get(val) - - -stats = StatsBackend() -stats.increment("amount_of_transactions")
5d2a4ac0e48d404a16b81d2f290be5ec13bdf8f1
logintokens/forms.py
logintokens/forms.py
"""forms for accounts app """ from django import forms from django.contrib.auth import get_user_model from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get_user_model() class TokenLoginForm(forms.Form): email = forms.EmailField(label="Email", max_length=254) def generate_login_link(self, email, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') token = default_token_generator.make_token(email) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ email = self.cleaned_data['email'] body = 'To complete the login process, simply click on this link: {}' login_link = self.generate_login_link(email, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth', body.format(login_link), to=[email] ) email_message.send()
"""forms for accounts app """ from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UsernameField from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy from logintokens.tokens import default_token_generator USER = get_user_model() class TokenLoginForm(forms.Form): email = UsernameField( max_length=254, widget=forms.TextInput(attrs={'autofocus': True}), ) def generate_login_link(self, username, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') token = default_token_generator.make_token(username) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ username = self.cleaned_data['email'] try: user = USER._default_manager.get_by_natural_key(username) email = getattr(user, USER.EMAIL_FIELD) except USER.DoesNotExist: email = username body = 'To complete the login process, simply click on this link: {}' login_link = self.generate_login_link(username, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth', body.format(login_link), to=[email] ) email_message.send()
Update form to pass new test
Update form to pass new test
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
--- +++ @@ -3,6 +3,7 @@ """ from django import forms from django.contrib.auth import get_user_model +from django.contrib.auth.forms import UsernameField from django.core.mail import EmailMultiAlternatives from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse_lazy @@ -14,22 +15,30 @@ class TokenLoginForm(forms.Form): - email = forms.EmailField(label="Email", max_length=254) + email = UsernameField( + max_length=254, + widget=forms.TextInput(attrs={'autofocus': True}), + ) - def generate_login_link(self, email, request): + def generate_login_link(self, username, request): protocol = 'https' if request.is_secure() else 'http' domain = get_current_site(request).domain url = reverse_lazy('token_login') - token = default_token_generator.make_token(email) + token = default_token_generator.make_token(username) return '{}://{}{}?token={}'.format(protocol, domain, url, token) def save(self, request): """Generate a login token and send it to the email from the form. """ - email = self.cleaned_data['email'] + username = self.cleaned_data['email'] + try: + user = USER._default_manager.get_by_natural_key(username) + email = getattr(user, USER.EMAIL_FIELD) + except USER.DoesNotExist: + email = username body = 'To complete the login process, simply click on this link: {}' - login_link = self.generate_login_link(email, request) + login_link = self.generate_login_link(username, request) email_message = EmailMultiAlternatives( 'Your login link for ANIAuth',
0b7a1904ef5511916fc4978c325862241a46aef3
lib/pyfrc/mains/cli_profiler.py
lib/pyfrc/mains/cli_profiler.py
import argparse import inspect import subprocess import sys class PyFrcProfiler: """ Wraps other commands by running them via the built in cProfile module. Use this to profile your program and figure out where you're spending a lot of time (note that cProfile only profiles the main thread) """ def __init__(self, parser): parser.add_argument('args', nargs=argparse.REMAINDER, help='Arguments to pass to robot.py') def run(self, options, robot_class, **static_options): from .. import config config.mode = 'profiler' try: import cProfile except ImportError: print("Error importing cProfile module for profiling, your python interpreter may not support profiling\n", file=sys.stderr) return 1 if len(options.args) == 0: print("ERROR: Profiler command requires arguments to run other commands") return 1 file_location = inspect.getfile(robot_class) # construct the arguments to run the profiler args = [sys.executable, '-m', 'cProfile', '-s', 'tottime', file_location] + options.args return subprocess.call(args)
import argparse import inspect from os.path import abspath import subprocess import sys class PyFrcProfiler: """ Wraps other commands by running them via the built in cProfile module. Use this to profile your program and figure out where you're spending a lot of time (note that cProfile only profiles the main thread) """ def __init__(self, parser): parser.add_argument('-o', '--outfile', default=None, help="Save stats to <outfile>") parser.add_argument('args', nargs=argparse.REMAINDER, help='Arguments to pass to robot.py') def run(self, options, robot_class, **static_options): from .. import config config.mode = 'profiler' try: import cProfile except ImportError: print("Error importing cProfile module for profiling, your python interpreter may not support profiling\n", file=sys.stderr) return 1 if len(options.args) == 0: print("ERROR: Profiler command requires arguments to run other commands") return 1 file_location = abspath(inspect.getfile(robot_class)) if options.outfile: profile_args = ['-o', options.outfile] else: profile_args = ['-s', 'tottime'] # construct the arguments to run the profiler args = [sys.executable, '-m', 'cProfile'] + profile_args + [file_location] + options.args return subprocess.call(args)
Add output option for profiler
Add output option for profiler
Python
mit
robotpy/pyfrc
--- +++ @@ -1,6 +1,7 @@ import argparse import inspect +from os.path import abspath import subprocess import sys @@ -12,6 +13,8 @@ """ def __init__(self, parser): + parser.add_argument('-o', '--outfile', default=None, + help="Save stats to <outfile>") parser.add_argument('args', nargs=argparse.REMAINDER, help='Arguments to pass to robot.py') @@ -30,9 +33,14 @@ print("ERROR: Profiler command requires arguments to run other commands") return 1 - file_location = inspect.getfile(robot_class) + file_location = abspath(inspect.getfile(robot_class)) + if options.outfile: + profile_args = ['-o', options.outfile] + else: + profile_args = ['-s', 'tottime'] + # construct the arguments to run the profiler - args = [sys.executable, '-m', 'cProfile', '-s', 'tottime', file_location] + options.args + args = [sys.executable, '-m', 'cProfile'] + profile_args + [file_location] + options.args return subprocess.call(args)
3786ebdf37820bc7b59342302c5858d7805a323c
planner/forms.py
planner/forms.py
from django.contrib.auth.forms import AuthenticationForm from django import forms from .models import PoolingUser class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control', })) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control', })) class SearchTrip(forms.Form): origin_id = forms.IntegerField() destination_id = forms.IntegerField() datetime = forms.DateTimeField() class PoolingUserForm(forms.ModelForm): class Meta: model = PoolingUser # Exclude the one-to-one relation with User fields = ['birth_date', 'driving_license']
from django.contrib.auth.forms import AuthenticationForm from django import forms from .models import PoolingUser class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.EmailInput(attrs={'placeholder': 'Email', 'class': 'form-control', })) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control', })) class SearchTrip(forms.Form): """ Pay attentions that id fields are meant to be hidden, since we suppose they come from an autocomplete AJAX request via an another CharField. """ origin_id = forms.IntegerField() destination_id = forms.IntegerField() datetime = forms.DateTimeField() class PoolingUserForm(forms.ModelForm): class Meta: model = PoolingUser # Exclude the one-to-one relation with User fields = ['birth_date', 'driving_license']
Add documentation for SearchTrip form
Add documentation for SearchTrip form
Python
mit
livingsilver94/getaride,livingsilver94/getaride,livingsilver94/getaride
--- +++ @@ -13,6 +13,10 @@ class SearchTrip(forms.Form): + """ + Pay attentions that id fields are meant to be hidden, since we suppose they come from + an autocomplete AJAX request via an another CharField. + """ origin_id = forms.IntegerField() destination_id = forms.IntegerField() datetime = forms.DateTimeField()
8f0b72dcad39fbd6072185bf2244eb75f0f45a96
better_od/core.py
better_od/core.py
from collections import MutableMapping class BetterOrderedDict(MutableMapping): def __init__(self, **kwargs): self._d = dict() self._keys = [] def __len__(self): return len(self._d) def __iter__(self): for key in self._keys: yield key def __setitem__(self, key, value): self._keys.append(key) self._d[key] = value def __getitem__(self, key): return self._d[key] def __delitem__(self, key): self._keys.pop(key) del self._d[key] def key_index(self, key): return self._keys.index(key) def insert(self, key, value, index): if key in self._d: self._keys.pop(key) self._keys.insert(index, key) self._d[key] = value def reorder_keys(self, keys): if self._keys != self._d: raise ValueError('Keys do not match.') self._keys = keys
from collections import MutableMapping class BetterOrderedDict(MutableMapping): '''BetterOrderedDict is a mapping object that allows for ordered access and insertion of keys. With the exception of the key_index, insert, and reorder_keys methods behavior is identical to stock dictionary objects.''' def __init__(self, **kwargs): '''BetterOrderedDict accepts an optional iterable of two-tuples indicating keys and values.''' self._d = dict() self._keys = [] def __len__(self): return len(self._d) def __iter__(self): for key in self._keys: yield key def __setitem__(self, key, value): self._keys.append(key) self._d[key] = value def __getitem__(self, key): return self._d[key] def __delitem__(self, key): self._keys.pop(key) del self._d[key] def key_index(self, key): '''Accepts a parameter, :key:, and returns an integer value representing its index in the ordered list of keys.''' return self._keys.index(key) def insert(self, key, value, index): '''Accepts a :key:, :value:, and :index: parameter and inserts a new key, value member at the desired index.''' if key in self._d: self._keys.pop(key) self._keys.insert(index, key) self._d[key] = value def reorder_keys(self, keys): '''Accepts a :keys: parameter, an iterable of keys in the desired new order. The :keys: parameter must contain all existing keys.''' if self._keys != self._d: raise ValueError('Keys do not match.') self._keys = keys
Add docstrings for most public API methods.
Add docstrings for most public API methods.
Python
mit
JustusW/BetterOrderedDict,therealfakemoot/collections2
--- +++ @@ -2,7 +2,14 @@ class BetterOrderedDict(MutableMapping): + '''BetterOrderedDict is a mapping object that allows for ordered access + and insertion of keys. With the exception of the key_index, insert, and + reorder_keys methods behavior is identical to stock dictionary objects.''' + def __init__(self, **kwargs): + '''BetterOrderedDict accepts an optional iterable of two-tuples + indicating keys and values.''' + self._d = dict() self._keys = [] @@ -25,15 +32,22 @@ del self._d[key] def key_index(self, key): + '''Accepts a parameter, :key:, and returns an integer value + representing its index in the ordered list of keys.''' return self._keys.index(key) def insert(self, key, value, index): + '''Accepts a :key:, :value:, and :index: parameter and inserts + a new key, value member at the desired index.''' if key in self._d: self._keys.pop(key) self._keys.insert(index, key) self._d[key] = value def reorder_keys(self, keys): + '''Accepts a :keys: parameter, an iterable of keys in the + desired new order. The :keys: parameter must contain all + existing keys.''' if self._keys != self._d: raise ValueError('Keys do not match.') self._keys = keys
98335de4b87638eff9613279bdd106651d4aefe1
catt/__init__.py
catt/__init__.py
# -*- coding: utf-8 -*- __author__ = "Stavros Korokithakis" __email__ = "hi@stavros.io" __version__ = "0.9.3"
# -*- coding: utf-8 -*- import sys if sys.version_info.major < 3: print("This program requires Python 3 and above to run.") sys.exit(1) __author__ = "Stavros Korokithakis" __email__ = "hi@stavros.io" __version__ = "0.9.3"
Make catt refuse to install under 2 more
fix: Make catt refuse to install under 2 more
Python
bsd-2-clause
skorokithakis/catt,skorokithakis/catt
--- +++ @@ -1,4 +1,10 @@ # -*- coding: utf-8 -*- + +import sys + +if sys.version_info.major < 3: + print("This program requires Python 3 and above to run.") + sys.exit(1) __author__ = "Stavros Korokithakis" __email__ = "hi@stavros.io"
f6ce2439f1f1ba299d0579c2dd4e57a58398aca5
printer/PrinterApplication.py
printer/PrinterApplication.py
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
from Cura.Wx.WxApplication import WxApplication from Cura.Wx.MainWindow import MainWindow class PrinterApplication(WxApplication): def __init__(self): super(PrinterApplication, self).__init__() def run(self): self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
Load all storage plugins in the printer application
Load all storage plugins in the printer application
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
--- +++ @@ -6,6 +6,8 @@ super(PrinterApplication, self).__init__() def run(self): + self._plugin_registry.loadPlugins({ "type": "StorageDevice" }) + window = MainWindow("Cura Printer") window.Show() super(PrinterApplication, self).run()
7b72dbb331c120eb5657ce9a81e725c550779485
dataportal/broker/__init__.py
dataportal/broker/__init__.py
from .simple_broker import _DataBrokerClass, EventQueue, Header from .handler_registration import register_builtin_handlers DataBroker = _DataBrokerClass() # singleton register_builtin_handlers()
from .simple_broker import (_DataBrokerClass, EventQueue, Header, LocationError, IntegrityError) from .handler_registration import register_builtin_handlers DataBroker = _DataBrokerClass() # singleton register_builtin_handlers()
Add Errors to the public API.
DOC: Add Errors to the public API.
Python
bsd-3-clause
danielballan/dataportal,ericdill/datamuxer,tacaswell/dataportal,ericdill/datamuxer,tacaswell/dataportal,NSLS-II/dataportal,danielballan/datamuxer,danielballan/datamuxer,ericdill/databroker,NSLS-II/datamuxer,danielballan/dataportal,NSLS-II/dataportal,ericdill/databroker
--- +++ @@ -1,4 +1,5 @@ -from .simple_broker import _DataBrokerClass, EventQueue, Header +from .simple_broker import (_DataBrokerClass, EventQueue, Header, + LocationError, IntegrityError) from .handler_registration import register_builtin_handlers DataBroker = _DataBrokerClass() # singleton
b40cb43eb2a3afcc08a207b66e1dededd1ff1eaa
count-inversions/count_inversions.py
count-inversions/count_inversions.py
from random import randint import sys def count(arr): n = len(arr) if n == 1: return 0 else: first_half = count(arr[:n/2]) second_half = count(arr[n/2:]) split = count_split(arr) return first_half + second_half + split def count_split(arr): return 0 def main(arr_len): test_arr = [randint(0,arr_len) for n in range(arr_len)] return count(test_arr) if __name__ == '__main__': try: arr_len = int(sys.argv[1]) except (IndexError, ValueError): print 'Format: python merge-sort.py <array-length>' print main(arr_len)
from random import randint import sys def sort_and_count(arr): n = len(arr) if n == 1: return 0 else: first_half = sort_and_count(arr[:n/2]) second_half = sort_and_count(arr[n/2:]) split = merge_and_count_split(arr) return first_half + second_half + split def merge_and_count_split(arr): return 0 def main(arr_len): test_arr = [randint(0,arr_len) for n in range(arr_len)] return sort_and_count(test_arr) if __name__ == '__main__': try: arr_len = int(sys.argv[1]) except (IndexError, ValueError): print 'Format: python merge-sort.py <array-length>' print main(arr_len)
Rename functions to include sorting and merging
Rename functions to include sorting and merging The algorithm will require sorting in order to run in O(nlogn) time. The implementation will closely follow that of merge-sort, so the functions were renamed to reflect this.
Python
mit
timpel/stanford-algs,timpel/stanford-algs
--- +++ @@ -1,25 +1,25 @@ from random import randint import sys -def count(arr): +def sort_and_count(arr): n = len(arr) if n == 1: return 0 else: - first_half = count(arr[:n/2]) - second_half = count(arr[n/2:]) - split = count_split(arr) + first_half = sort_and_count(arr[:n/2]) + second_half = sort_and_count(arr[n/2:]) + split = merge_and_count_split(arr) return first_half + second_half + split -def count_split(arr): +def merge_and_count_split(arr): return 0 def main(arr_len): test_arr = [randint(0,arr_len) for n in range(arr_len)] - return count(test_arr) + return sort_and_count(test_arr) if __name__ == '__main__': try:
7ad0aa082114811a1638916060c6b18f93d09824
books/services.py
books/services.py
from datetime import date from datetime import timedelta from django.utils import timezone from books.models import Transaction def get_months_transactions(): today = timezone.now() first_day_of_a_month = date(today.year, today.month, 1) qs = Transaction.objects.filter(created__gte=first_day_of_a_month) return qs def get_last_months_transactions(): first_day_of_a_month = timezone.now().replace(day=1) last_month = first_day_of_a_month - timedelta(days=1) first_day_of_last_month = date(last_month.year, last_month.month, 1) qs = Transaction.objects.filter(created__gte=first_day_of_last_month) return qs def get_this_years_transactions(): today = timezone.now() first_day_of_this_year = date(today.year, 1, 1) qs = Transaction.objects.filter(created__gte=first_day_of_this_year) return qs
from datetime import datetime from datetime import timedelta from django.utils import timezone from books.models import Transaction def get_months_transactions(): today = timezone.now() first_day_of_a_month = datetime(today.year, today.month, 1, tzinfo=today.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_a_month) return qs def get_last_months_transactions(): first_day_of_a_month = timezone.now().replace(day=1) last_month = first_day_of_a_month - timedelta(days=1) first_day_of_last_month = datetime(last_month.year, last_month.month, 1, tzinfo=last_month.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_last_month) return qs def get_this_years_transactions(): today = timezone.now() first_day_of_this_year = datetime(today.year, 1, 1, tzinfo=today.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_this_year) return qs
Add service functions to get transactions by time
Add service functions to get transactions by time
Python
mit
trimailov/finance,trimailov/finance,trimailov/finance
--- +++ @@ -1,4 +1,4 @@ -from datetime import date +from datetime import datetime from datetime import timedelta from django.utils import timezone @@ -8,7 +8,8 @@ def get_months_transactions(): today = timezone.now() - first_day_of_a_month = date(today.year, today.month, 1) + first_day_of_a_month = datetime(today.year, today.month, 1, + tzinfo=today.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_a_month) return qs @@ -16,13 +17,14 @@ def get_last_months_transactions(): first_day_of_a_month = timezone.now().replace(day=1) last_month = first_day_of_a_month - timedelta(days=1) - first_day_of_last_month = date(last_month.year, last_month.month, 1) + first_day_of_last_month = datetime(last_month.year, last_month.month, 1, + tzinfo=last_month.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_last_month) return qs def get_this_years_transactions(): today = timezone.now() - first_day_of_this_year = date(today.year, 1, 1) + first_day_of_this_year = datetime(today.year, 1, 1, tzinfo=today.tzinfo) qs = Transaction.objects.filter(created__gte=first_day_of_this_year) return qs
6d15281487dd7769fa60585e7c6497c3993e0e94
services/topology-engine/app/app/__init__.py
services/topology-engine/app/app/__init__.py
from flask import Flask, flash, redirect, render_template, request, session, abort from flask_sqlalchemy import SQLAlchemy import os application = Flask(__name__) application.secret_key = '123456789' application.config['PROPAGATE_EXCEPTIONS'] = True application.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////var/data/database.db" application.debug = True db = SQLAlchemy(application) from app import login from app import topology from app import models if __name__ == "__main__": try: application.run(host='0.0.0.0') except Exception as e: print e
from flask import Flask, flash, redirect, render_template, request, session, abort from flask_sqlalchemy import SQLAlchemy import os application = Flask(__name__) application.secret_key = '123456789' application.config['PROPAGATE_EXCEPTIONS'] = True application.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////var/data/database.db" application.debug = True db = SQLAlchemy(application) # # NB: If you run the topology engine like this: # ```docker-compose run --service-ports -e OK_TESTS="DISABLE_LOGIN" topology-engine``` # Then you'll be able to access the APIs without login. Useful for testing. # if "DISABLE_LOGIN" in os.environ["OK_TESTS"]: print "\nWARNING\nWARNING: Disabling Login .. all APIs exposed!\nWARNING\n" application.config['LOGIN_DISABLED'] = True from app import login from app import topology from app import models if __name__ == "__main__": try: application.run(host='0.0.0.0') except Exception as e: print e
Add OK_TESTS and DISABLE_LOGIN to TE
Add OK_TESTS and DISABLE_LOGIN to TE The OK_TESTS environment variable can be used to disable logins by setting OK_TESTS=DISABLE_LOGIN. The test isn't equality, but 'in'. So, you can add more things to that flag.
Python
apache-2.0
jonvestal/open-kilda,nikitamarchenko/open-kilda,telstra/open-kilda,carmine/open-kilda,jonvestal/open-kilda,nikitamarchenko/open-kilda,telstra/open-kilda,telstra/open-kilda,jonvestal/open-kilda,telstra/open-kilda,nikitamarchenko/open-kilda,jonvestal/open-kilda,carmine/open-kilda,nikitamarchenko/open-kilda,jonvestal/open-kilda,nikitamarchenko/open-kilda,carmine/open-kilda,carmine/open-kilda,telstra/open-kilda,telstra/open-kilda,nikitamarchenko/open-kilda,carmine/open-kilda,carmine/open-kilda,telstra/open-kilda
--- +++ @@ -9,6 +9,15 @@ application.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////var/data/database.db" application.debug = True db = SQLAlchemy(application) + +# +# NB: If you run the topology engine like this: +# ```docker-compose run --service-ports -e OK_TESTS="DISABLE_LOGIN" topology-engine``` +# Then you'll be able to access the APIs without login. Useful for testing. +# +if "DISABLE_LOGIN" in os.environ["OK_TESTS"]: + print "\nWARNING\nWARNING: Disabling Login .. all APIs exposed!\nWARNING\n" + application.config['LOGIN_DISABLED'] = True from app import login from app import topology
aa14a6036d262fab1d213d021640204419d3c9e1
daemon/__init__.py
daemon/__init__.py
# -*- coding: utf-8 -*- # Copyright © 2009 Ben Finney <ben+python@benfinney.id.au> # Copyright © 2006 Robert Niederreiter # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # later as published by the Python Software Foundation. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details. """ Library to implement a well-behaved Unix daemon process This library implements PEP [no number yet], Standard daemon process library. A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. An instance of the `DaemonContext` holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state. Simple example of usage:: import daemon from spam import do_main_program with daemon.DaemonContext() as daemon_context: do_main_program() """ from daemon import DaemonContext version = "1.4.3"
# -*- coding: utf-8 -*- # Copyright © 2009 Ben Finney <ben+python@benfinney.id.au> # Copyright © 2006 Robert Niederreiter # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # later as published by the Python Software Foundation. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details. """ Library to implement a well-behaved Unix daemon process This library implements PEP [no number yet], Standard daemon process library. A well-behaved Unix daemon process is tricky to get right, but the required steps are much the same for every daemon program. An instance of the `DaemonContext` holds the behaviour and configured process environment for the program; use the instance as a context manager to enter a daemon state. Simple example of usage:: import daemon from spam import do_main_program with daemon.DaemonContext() as daemon_context: do_main_program() """ from daemon import DaemonContext version = "1.4.4"
Prepare development of new version.
Prepare development of new version.
Python
apache-2.0
wting/python-daemon,eaufavor/python-daemon
--- +++ @@ -34,4 +34,4 @@ -version = "1.4.3" +version = "1.4.4"
d538e4fd59d714b7a7826937c50b66ec3f697b05
mygpo/api/backend.py
mygpo/api/backend.py
import uuid from django.db import transaction, IntegrityError from mygpo.users.settings import STORE_UA from mygpo.users.models import Client import logging logger = logging.getLogger(__name__) def get_device(user, uid, user_agent, undelete=True): """ Loads or creates the device indicated by user, uid. If the device has been deleted and undelete=True, it is undeleted. """ store_ua = user.profile.settings.get_wksetting(STORE_UA) # list of fields to update -- empty list = no update update_fields = [] try: with transaction.atomic(): client = Client(id=uuid.uuid1(), user=user, uid=uid) client.full_clean() client.save() except IntegrityError: client = Client.objects.get(user=user, uid=uid) if client.deleted and undelete: client.deleted = False update_fields.append('deleted') if store_ua and user_agent and client.user_agent != user_agent: client.user_agent = user_agent update_fields.append('user_agent') if update_fields: client.save(update_fields=update_fields) return client
import uuid from django.db import transaction, IntegrityError from mygpo.users.settings import STORE_UA from mygpo.users.models import Client import logging logger = logging.getLogger(__name__) def get_device(user, uid, user_agent, undelete=True): """ Loads or creates the device indicated by user, uid. If the device has been deleted and undelete=True, it is undeleted. """ store_ua = user.profile.settings.get_wksetting(STORE_UA) # list of fields to update -- empty list = no update update_fields = [] try: with transaction.atomic(): client = Client(id=uuid.uuid1(), user=user, uid=uid) client.clean_fields() client.clean() client.save() except IntegrityError: client = Client.objects.get(user=user, uid=uid) if client.deleted and undelete: client.deleted = False update_fields.append('deleted') if store_ua and user_agent and client.user_agent != user_agent: client.user_agent = user_agent update_fields.append('user_agent') if update_fields: client.save(update_fields=update_fields) return client
Fix validation of Client objects
Fix validation of Client objects
Python
agpl-3.0
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
--- +++ @@ -24,7 +24,8 @@ try: with transaction.atomic(): client = Client(id=uuid.uuid1(), user=user, uid=uid) - client.full_clean() + client.clean_fields() + client.clean() client.save() except IntegrityError:
08ea2c257780f23cec5dfb923e80966fdf9c5ac8
IPython/zmq/zmqshell.py
IPython/zmq/zmqshell.py
import sys from subprocess import Popen, PIPE from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC class ZMQInteractiveShell(InteractiveShell): """A subclass of InteractiveShell for ZMQ.""" def system(self, cmd): cmd = self.var_expand(cmd, depth=2) p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) for line in p.stdout.read().split('\n'): if len(line) > 0: print line for line in p.stderr.read().split('\n'): if len(line) > 0: print line return p.wait() InteractiveShellABC.register(ZMQInteractiveShell)
import sys from subprocess import Popen, PIPE from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC class ZMQInteractiveShell(InteractiveShell): """A subclass of InteractiveShell for ZMQ.""" def system(self, cmd): cmd = self.var_expand(cmd, depth=2) sys.stdout.flush() sys.stderr.flush() p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) for line in p.stdout.read().split('\n'): if len(line) > 0: print line for line in p.stderr.read().split('\n'): if len(line) > 0: print line return p.wait() InteractiveShellABC.register(ZMQInteractiveShell)
Add flushing to stdout/stderr in system calls.
Add flushing to stdout/stderr in system calls.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
--- +++ @@ -8,6 +8,8 @@ def system(self, cmd): cmd = self.var_expand(cmd, depth=2) + sys.stdout.flush() + sys.stderr.flush() p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) for line in p.stdout.read().split('\n'): if len(line) > 0:
5a9bf08b78176097d918d0ec7174e68094ee63a2
Lib/test/test_binhex.py
Lib/test/test_binhex.py
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Roger E. Masse """ import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open(fname1, 'w') except: raise TestSkipped, "Cannot test binhex without a temp file" start = 'Jack is my hero' f.write(start) f.close() binhex.binhex(fname1, fname2) if verbose: print 'binhex' binhex.hexbin(fname2, fname1) if verbose: print 'hexbin' f = open(fname1, 'r') finish = f.readline() if start != finish: print 'Error: binhex != hexbin' elif verbose: print 'binhex == hexbin' try: import os os.unlink(fname1) os.unlink(fname2) except: pass test()
#! /usr/bin/env python """Test script for the binhex C module Uses the mechanism of the python binhex module Roger E. Masse """ import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open(fname1, 'w') except: raise TestSkipped, "Cannot test binhex without a temp file" start = 'Jack is my hero' f.write(start) f.close() binhex.binhex(fname1, fname2) if verbose: print 'binhex' binhex.hexbin(fname2, fname1) if verbose: print 'hexbin' f = open(fname1, 'r') finish = f.readline() f.close() # on Windows an open file cannot be unlinked if start != finish: print 'Error: binhex != hexbin' elif verbose: print 'binhex == hexbin' try: import os os.unlink(fname1) os.unlink(fname2) except: pass test()
Stop creating an unbounded number of "Jack is my hero" files under Windows. Not that Jack doesn't deserve them, but saying it so often cheapens the sentiment.
Stop creating an unbounded number of "Jack is my hero" files under Windows. Not that Jack doesn't deserve them, but saying it so often cheapens the sentiment.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -31,6 +31,7 @@ f = open(fname1, 'r') finish = f.readline() + f.close() # on Windows an open file cannot be unlinked if start != finish: print 'Error: binhex != hexbin'
3bd1135bba97cf616fc7c990c12cb8b3f93a25da
nextcloudappstore/urls.py
nextcloudappstore/urls.py
from django.conf.urls import url, include from django.contrib import admin from nextcloudappstore.core.views import CategoryAppListView, AppDetailView, \ app_description urlpatterns = [ url(r'^$', CategoryAppListView.as_view(), {'id': None}, name='home'), url(r'^', include('allauth.urls')), url(r'^categories/(?P<id>[\w]*)$', CategoryAppListView.as_view(), name='category-app-list'), url(r'^app/(?P<id>[\w_]+)$', AppDetailView.as_view(), name='app-detail'), url(r'^app/(?P<id>[\w_]+)/description/?$', app_description, name='app-description'), url(r'^api/', include('nextcloudappstore.core.api.urls', namespace='api')), url(r'^admin/', admin.site.urls), ]
from django.conf.urls import url, include from django.contrib import admin from nextcloudappstore.core.views import CategoryAppListView, AppDetailView, \ app_description urlpatterns = [ url(r'^$', CategoryAppListView.as_view(), {'id': None}, name='home'), url(r'^', include('allauth.urls')), url(r'^categories/(?P<id>[\w]*)/?$', CategoryAppListView.as_view(), name='category-app-list'), url(r'^app/(?P<id>[\w_]+)/?$', AppDetailView.as_view(), name='app-detail'), url(r'^app/(?P<id>[\w_]+)/description/?$', app_description, name='app-description'), url(r'^api/', include('nextcloudappstore.core.api.urls', namespace='api')), url(r'^admin/', admin.site.urls), ]
Allow trailing slash at the end of URLs
Allow trailing slash at the end of URLs Specifically app detail page and category app list.
Python
agpl-3.0
clone1612/appstore,nextcloud/appstore,clone1612/appstore,clone1612/appstore,nextcloud/appstore,nextcloud/appstore,clone1612/appstore,clone1612/appstore,nextcloud/appstore,nextcloud/appstore,nextcloud/appstore
--- +++ @@ -7,9 +7,9 @@ urlpatterns = [ url(r'^$', CategoryAppListView.as_view(), {'id': None}, name='home'), url(r'^', include('allauth.urls')), - url(r'^categories/(?P<id>[\w]*)$', CategoryAppListView.as_view(), + url(r'^categories/(?P<id>[\w]*)/?$', CategoryAppListView.as_view(), name='category-app-list'), - url(r'^app/(?P<id>[\w_]+)$', AppDetailView.as_view(), name='app-detail'), + url(r'^app/(?P<id>[\w_]+)/?$', AppDetailView.as_view(), name='app-detail'), url(r'^app/(?P<id>[\w_]+)/description/?$', app_description, name='app-description'), url(r'^api/', include('nextcloudappstore.core.api.urls',
3b6ddce7c0db0f0b1fbd9febd9bf68ceeda51f44
della/user_manager/forms.py
della/user_manager/forms.py
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import RegexValidator alphanumericu = RegexValidator( regex=r'^[0-9a-zA-Z_]*$', message='Only alphanumeric characters and underscore are allowed.') class SignupForm(UserCreationForm): username = forms.CharField(max_length=20, validators=[alphanumericu]) email = forms.EmailField(max_length=254, required=True) class Meta: model = User fields = ['email', 'username', ] def clean_email(self): error_message = 'An user with that email already exists' email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): raise forms.ValidationError( self.error_messages[error_message], code='existing_email', ) return email
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.core.validators import RegexValidator alphanumericu = RegexValidator( regex=r'^[0-9a-zA-Z_]*$', message='Only alphanumeric characters and underscore are allowed.') class SignupForm(UserCreationForm): username = forms.CharField(max_length=20, validators=[alphanumericu]) email = forms.EmailField(max_length=254, required=True) class Meta: model = User fields = ['email', 'username', ] def clean_email(self): error_message = 'An user with that email already exists' email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): raise forms.ValidationError(error_message) return email
Raise ValidationError properly in SignupForm
Raise ValidationError properly in SignupForm
Python
mit
avinassh/della,avinassh/della,avinassh/della
--- +++ @@ -20,8 +20,5 @@ error_message = 'An user with that email already exists' email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exists(): - raise forms.ValidationError( - self.error_messages[error_message], - code='existing_email', - ) + raise forms.ValidationError(error_message) return email
6f24dc967a082251d0bc62ab66c9263235174f9f
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/test_views.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/test_views.py
from django.core.urlresolvers import reverse from django.test import Client, TestCase from users.models import User class UserRedirectViewTestCase(TestCase): def setUp(self): self.client = Client() User.objects.create_user( username="testuser", email="test@example.com", password="testpass" ) def test_redirect_url(self): self.client.login(username="testuser", password="testpass") response = self.client.get(reverse('users:redirect'), follow=True) self.assertEqual( response.redirect_chain, [('http://testserver/users/testuser/', 302)] ) class UserUpdateViewTestCase(TestCase): def setUp(self): self.client = Client() User.objects.create_user( username="testuser", email="test@example.com", password="testpass" ) def test_get_object(self): self.client.login(username="testuser", password="testpass") response = self.client.get(reverse('users:update'), follow=True) self.assertEqual( response.context_data['user'], User.objects.get(username='testuser') ) def test_success_url(self): self.client.login(username="testuser", password="testpass") response = self.client.post( reverse('users:update'), {'first_name': 'testing'}, follow=True ) self.assertRedirects( response, '/users/testuser/' )
from django.core.urlresolvers import reverse from django.test import TestCase from users.models import User class UserRedirectViewTestCase(TestCase): def setUp(self): User.objects.create_user( username="testuser", email="test@example.com", password="testpass" ) def test_redirect_url(self): self.client.login(username="testuser", password="testpass") response = self.client.get(reverse('users:redirect'), follow=True) self.assertEqual( response.redirect_chain, [('http://testserver/users/testuser/', 302)] ) class UserUpdateViewTestCase(TestCase): def setUp(self): User.objects.create_user( username="testuser", email="test@example.com", password="testpass" ) def test_get_object(self): self.client.login(username="testuser", password="testpass") response = self.client.get(reverse('users:update'), follow=True) self.assertEqual( response.context_data['user'], User.objects.get(username='testuser') ) def test_success_url(self): self.client.login(username="testuser", password="testpass") response = self.client.post( reverse('users:update'), {'first_name': 'testing'}, follow=True ) self.assertRedirects( response, '/users/testuser/' )
Remove unnecessary assignment to self.client in test cases.
Remove unnecessary assignment to self.client in test cases.
Python
bsd-3-clause
wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials,wldcordeiro/cookiecutter-django-essentials
--- +++ @@ -1,5 +1,5 @@ from django.core.urlresolvers import reverse -from django.test import Client, TestCase +from django.test import TestCase from users.models import User @@ -7,7 +7,6 @@ class UserRedirectViewTestCase(TestCase): def setUp(self): - self.client = Client() User.objects.create_user( username="testuser", email="test@example.com", @@ -27,7 +26,6 @@ class UserUpdateViewTestCase(TestCase): def setUp(self): - self.client = Client() User.objects.create_user( username="testuser", email="test@example.com",
a696e9740920018d726c0c54987f6dc6ba2128d6
eppread.py
eppread.py
#!/usr/bin/env python # # Copyright (c) 2017 Ralf Horstmann <ralf@ackstorm.de> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ parse daum ergo bike epp/eup files """ import sys import eppformat as epp if __name__ == "__main__": if (len(sys.argv) > 1): p = epp.epp_file.parse_stream(open(sys.argv[1], "rb")) print("signature =", p.signature) print("version =", p.version) print(p.header) if (len(sys.argv) > 2): limit=int(sys.argv[2]) else: limit=None for v in p.data[:limit]: print(v) else: print("usage: eppread <file> [limit]") sys.exit(1);
#!/usr/bin/env python # # Copyright (c) 2017 Ralf Horstmann <ralf@ackstorm.de> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ parse daum ergo bike epp/eup files """ from __future__ import print_function import sys import eppformat as epp if __name__ == "__main__": if (len(sys.argv) > 1): p = epp.epp_file.parse_stream(open(sys.argv[1], "rb")) print("signature =", p.signature) print("version =", p.version) print(p.header) if (len(sys.argv) > 2): limit=int(sys.argv[2]) else: limit=None for v in p.data[:limit]: print(v) else: print("usage: eppread <file> [limit]") sys.exit(1);
Improve printing of signature and version
Improve printing of signature and version
Python
isc
ra1fh/eppconvert
--- +++ @@ -18,6 +18,8 @@ parse daum ergo bike epp/eup files """ +from __future__ import print_function + import sys import eppformat as epp
fb665cf8d6c0eb6c794a41eaf312c35473d1bdf0
tests/settings_complex.py
tests/settings_complex.py
from settings import * INSTALLED_APPS.append('complex') INSTALLED_APPS.append('django.contrib.comments') ROOT_URLCONF = 'complex.urls'
from settings import * INSTALLED_APPS += [ 'complex', 'django.contrib.comments', 'django.contrib.sites', ] ROOT_URLCONF = 'complex.urls'
Add sites app, change how installed_apps are edited.
Add sites app, change how installed_apps are edited.
Python
bsd-3-clause
esatterwhite/django-tastypie,beni55/django-tastypie,Eksmo/django-tastypie,SeanHayes/django-tastypie,cbxcube/bezrealitky.py,ywarezk/nerdeez-tastypie,mohabusama/django-tastypie,ocadotechnology/django-tastypie,ocadotechnology/django-tastypie,waveaccounting/django-tastypie,SeanHayes/django-tastypie,Eksmo/django-tastypie,beedesk/django-tastypie,yfli/django-tastypie,shownomercy/django-tastypie,coxmediagroup/django-tastypie,Eksmo/django-tastypie,guilhermegm/django-tastypie,backslash112/django-tastypie,grischa/django-tastypie,mthornhill/django-tastypie,glencoates/django-tastypie,loftywaif002/django-tastypie,marcosleonefilho/hoop-tastypie,backslash112/django-tastypie,beni55/django-tastypie,SiggyF/django-tastypie,VishvajitP/django-tastypie,VishvajitP/django-tastypie,ipsosante/django-tastypie,waveaccounting/django-tastypie,doselect/django-tastypie,ipsosante/django-tastypie,beedesk/django-tastypie,yfli/django-tastypie,mjschultz/django-tastefulpy,SiggyF/django-tastypie,doselect/django-tastypie,beni55/django-tastypie,frifri/django-tastypie,mitar/django-tastypie,nomadjourney/django-tastypie,ipsosante/django-tastypie,wlanslovenija/django-tastypie,igavrilov/django-tastypie,strets123/django-tastypie,mohabusama/django-tastypie,Perkville/django-tastypie,annacorobco/django-tastypie,ywarezk/nerdeez-tastypie,Perkville/django-tastypie,strets123/django-tastypie-tweaks,igavrilov/django-tastypie,cbxcube/bezrealitky.py,ocadotechnology/django-tastypie,nomadjourney/django-tastypie,annacorobco/django-tastypie,frifri/django-tastypie,strets123/django-tastypie,guilhermegm/django-tastypie,mthornhill/django-tastypie,tyaslab/django-tastypie,strets123/django-tastypie,loftywaif002/django-tastypie,pveglia/django-tastypie,rbraley/django-tastypie,beedesk/django-tastypie,doselect/django-tastypie,backslash112/django-tastypie,esatterwhite/django-tastypie,shownomercy/django-tastypie,pveglia/django-tastypie,strets123/django-tastypie-tweaks,guilhermegm/django-tastypie,wlanslovenija/django-tastypie,mthornhill/django-tastypie,nomadjourney/django-tastypie,marcosleonefilho/hoop-tastypie,esatterwhite/django-tastypie,akvo/django-tastypie,igavrilov/django-tastypie,wlanslovenija/django-tastypie,mjschultz/django-tastefulpy,cbxcube/bezrealitky.py,loftywaif002/django-tastypie,SiggyF/django-tastypie,sideffect0/django-tastypie,akvo/django-tastypie,coxmediagroup/django-tastypie,Perkville/django-tastypie,pveglia/django-tastypie,VishvajitP/django-tastypie,strets123/django-tastypie-tweaks,mohabusama/django-tastypie,coxmediagroup/django-tastypie,glencoates/django-tastypie,grischa/django-tastypie,sideffect0/django-tastypie,mjschultz/django-tastefulpy,mitar/django-tastypie,sideffect0/django-tastypie,rbraley/django-tastypie,waveaccounting/django-tastypie,SeanHayes/django-tastypie,tyaslab/django-tastypie,shownomercy/django-tastypie,yfli/django-tastypie,annacorobco/django-tastypie
--- +++ @@ -1,5 +1,9 @@ from settings import * -INSTALLED_APPS.append('complex') -INSTALLED_APPS.append('django.contrib.comments') + +INSTALLED_APPS += [ + 'complex', + 'django.contrib.comments', + 'django.contrib.sites', +] ROOT_URLCONF = 'complex.urls'
855ed8bcef8fc17655ccc28f70ce34a6b3b58d65
official/utils/misc/tpu_lib.py
official/utils/misc/tpu_lib.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Initializes TPU system for TF 2.0.""" import tensorflow as tf def tpu_initialize(tpu_address): """Initializes TPU for TF 2.0 training. Args: tpu_address: string, bns address of master TPU worker. Returns: A TPUClusterResolver. """ cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address) if tpu_address not in ('', 'local'): tf.config.experimental_connect_to_cluster(cluster_resolver) tf.tpu.experimental.initialize_tpu_system(cluster_resolver) return cluster_resolver
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Initializes TPU system for TF 2.0.""" import tensorflow as tf def tpu_initialize(tpu_address): """Initializes TPU for TF 2.0 training. Args: tpu_address: string, bns address of master TPU worker. Returns: A TPUClusterResolver. """ cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address) if tpu_address not in ('', 'local'): tf.config.experimental_connect_to_cluster(cluster_resolver) return cluster_resolver
Remove explicit initialize_tpu_system call from model garden.
Remove explicit initialize_tpu_system call from model garden. PiperOrigin-RevId: 290354680
Python
apache-2.0
tombstone/models,alexgorban/models,alexgorban/models,alexgorban/models,tombstone/models,tombstone/models,tombstone/models,tombstone/models,alexgorban/models,alexgorban/models,tombstone/models
--- +++ @@ -30,5 +30,4 @@ tpu=tpu_address) if tpu_address not in ('', 'local'): tf.config.experimental_connect_to_cluster(cluster_resolver) - tf.tpu.experimental.initialize_tpu_system(cluster_resolver) return cluster_resolver
345056a7a6a801013cdc340f0f9cd8b4f5d48173
convert-bookmarks.py
convert-bookmarks.py
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup from datetime import datetime, timezone from bson import json_util import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='+') parser.add_argument('-t', '--tag', metavar='tag', dest='tags', action='append', help='add tag to bookmarks, repeat \ for multiple tags') parser.add_argument('-m', '--mongodb', action='store_true', dest='mongo', help='output in mongodb import format') args = parser.parse_args() for filename in args.filenames: soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib") for link in soup.find_all('a'): bookmark = {} # url and title bookmark['url'] = link.get('href') bookmark['title'] = link.string.strip() if link.string\ else bookmark['url'] # add date secs = link.get('add_date') date = datetime.fromtimestamp(int(secs), tz=timezone.utc) bookmark['add_date'] = date # tags tags = link.get('tags') bookmark['tags'] = tags.split(',') if tags else [] if args.tags: bookmark['tags'] += args.tags # comment sibling = link.parent.next_sibling bookmark['comment'] = \ sibling.string.strip() if sibling and sibling.name == 'dd' \ else '' # make json if args.mongo: print(json_util.dumps(bookmark, sort_keys=False, indent=4)) else: print(json.dumps(bookmark, sort_keys=False, indent=4))
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='+') parser.add_argument('-t', '--tag', metavar='tag', dest='tags', action='append', help='add tag to bookmarks, repeat \ for multiple tags') args = parser.parse_args() for filename in args.filenames: soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib") for link in soup.find_all('a'): bookmark = {} # url and title bookmark['url'] = link.get('href') bookmark['title'] = link.string.strip() if link.string\ else bookmark['url'] # tags tags = link.get('tags') bookmark['tags'] = tags.split(',') if tags else [] if args.tags: bookmark['tags'] += args.tags # comment sibling = link.parent.next_sibling bookmark['comment'] = \ sibling.string.strip() if sibling and sibling.name == 'dd' \ else '' print(json.dumps(bookmark, sort_keys=False, indent=4))
Remove bson, datetime, and mongo
Remove bson, datetime, and mongo Current BSON fails to work datetime can't be serialized by json_util mongodb is not needed; just use JSON
Python
mit
jhh/netscape-bookmark-converter
--- +++ @@ -4,18 +4,13 @@ # from argparse import ArgumentParser from bs4 import BeautifulSoup -from datetime import datetime, timezone -from bson import json_util import json - parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='+') parser.add_argument('-t', '--tag', metavar='tag', dest='tags', action='append', help='add tag to bookmarks, repeat \ for multiple tags') -parser.add_argument('-m', '--mongodb', action='store_true', dest='mongo', - help='output in mongodb import format') args = parser.parse_args() for filename in args.filenames: @@ -26,10 +21,6 @@ bookmark['url'] = link.get('href') bookmark['title'] = link.string.strip() if link.string\ else bookmark['url'] - # add date - secs = link.get('add_date') - date = datetime.fromtimestamp(int(secs), tz=timezone.utc) - bookmark['add_date'] = date # tags tags = link.get('tags') bookmark['tags'] = tags.split(',') if tags else [] @@ -39,9 +30,5 @@ sibling = link.parent.next_sibling bookmark['comment'] = \ sibling.string.strip() if sibling and sibling.name == 'dd' \ - else '' - # make json - if args.mongo: - print(json_util.dumps(bookmark, sort_keys=False, indent=4)) - else: - print(json.dumps(bookmark, sort_keys=False, indent=4)) + else '' + print(json.dumps(bookmark, sort_keys=False, indent=4))
05de6db4aab5f6705bb2867422fab5f7aca3a13a
thinglang/execution/builtins.py
thinglang/execution/builtins.py
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item) def __contains__(self, item): return hasattr(self, item) class ThingObjectOutput(ThingObjectBase): def __init__(self): self.data = [] def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): def __init__(self, heap): self.data = [] self.heap = heap def get_line(self, line=None): if line is not None: self.heap['Output'].write(line) line = input() self.data.append(line) return line
class ThingObjectBase(object): def __getitem__(self, item): return getattr(self, item.value) def __contains__(self, item): return hasattr(self, item.value) class ThingObjectOutput(ThingObjectBase): INTERNAL_NAME = "Output" def __init__(self, heap): self.data = [] self.heap = heap def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): INTERNAL_NAME = "Input" def __init__(self, heap): self.data = [] self.heap = heap def get_line(self, line=None): if line is not None: self.heap['Output'].write(line) line = input() self.data.append(line) return line BUILTINS = ThingObjectOutput, ThingObjectInput
Unify access in Pythonic built ins
Unify access in Pythonic built ins
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
--- +++ @@ -1,22 +1,25 @@ class ThingObjectBase(object): def __getitem__(self, item): - return getattr(self, item) + return getattr(self, item.value) def __contains__(self, item): - return hasattr(self, item) + return hasattr(self, item.value) class ThingObjectOutput(ThingObjectBase): + INTERNAL_NAME = "Output" - def __init__(self): + def __init__(self, heap): self.data = [] + self.heap = heap def write(self, *args): self.data.append(' '.join(str(x) for x in args)) class ThingObjectInput(ThingObjectBase): + INTERNAL_NAME = "Input" def __init__(self, heap): self.data = [] @@ -29,3 +32,6 @@ line = input() self.data.append(line) return line + + +BUILTINS = ThingObjectOutput, ThingObjectInput
7afedf19ff9dfcbf8872a7a9a6090c4ed235a206
phantasy/apps/__init__.py
phantasy/apps/__init__.py
# encoding: UTF-8 # # Copyright (c) 2015-2016 Facility for Rare Isotope Beams # """ Physics Applications """ from .latticemodel import lmapp from phantasy_apps import *
# encoding: UTF-8 # # Copyright (c) 2015-2016 Facility for Rare Isotope Beams # """ Physics Applications """ from .latticemodel import lmapp try: from phantasy_apps import * except ImportError: print("Package 'python-phantasy-apps' is required.")
Add warning if 'phantasy_apps' cannot be found.
Add warning if 'phantasy_apps' cannot be found.
Python
bsd-3-clause
archman/phantasy,archman/phantasy
--- +++ @@ -9,4 +9,7 @@ from .latticemodel import lmapp -from phantasy_apps import * +try: + from phantasy_apps import * +except ImportError: + print("Package 'python-phantasy-apps' is required.")