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
857ae593c14ea2401f0bb21d53d8e464fc7d3cb2
server/constants.py
server/constants.py
"""App constants""" STUDENT_ROLE = 'student' GRADER_ROLE = 'grader' STAFF_ROLE = 'staff' INSTRUCTOR_ROLE = 'instructor' LAB_ASSISTANT_ROLE = 'lab assistant' VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE] STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE] GRADE_TAGS = ['composition', 'total', 'partner a', 'partner b', 'regrade', 'revision'] API_PREFIX = '/api' GRADES_BUCKET = 'ok_grades_bucket' TIMEZONE = 'America/Los_Angeles' AUTOGRADER_URL = 'https://autograder.cs61a.org' FORBIDDEN_ROUTE_NAMES = [ 'about', 'admin', 'api', 'comments', 'login', 'logout', 'testing-login', ] FORBIDDEN_ASSIGNMENT_NAMES = []
"""App constants""" STUDENT_ROLE = 'student' GRADER_ROLE = 'grader' STAFF_ROLE = 'staff' INSTRUCTOR_ROLE = 'instructor' LAB_ASSISTANT_ROLE = 'lab_assistant' VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE] STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE] GRADE_TAGS = ['composition', 'total', 'partner a', 'partner b', 'regrade', 'revision'] API_PREFIX = '/api' GRADES_BUCKET = 'ok_grades_bucket' TIMEZONE = 'America/Los_Angeles' AUTOGRADER_URL = 'https://autograder.cs61a.org' FORBIDDEN_ROUTE_NAMES = [ 'about', 'admin', 'api', 'comments', 'login', 'logout', 'testing-login', ] FORBIDDEN_ASSIGNMENT_NAMES = []
Change lab assistant constant to one word
Change lab assistant constant to one word
Python
apache-2.0
Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok
--- +++ @@ -4,7 +4,7 @@ GRADER_ROLE = 'grader' STAFF_ROLE = 'staff' INSTRUCTOR_ROLE = 'instructor' -LAB_ASSISTANT_ROLE = 'lab assistant' +LAB_ASSISTANT_ROLE = 'lab_assistant' VALID_ROLES = [STUDENT_ROLE, GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE, LAB_ASSISTANT_ROLE] STAFF_ROLES = [GRADER_ROLE, STAFF_ROLE, INSTRUCTOR_ROLE] GRADE_TAGS = ['composition', 'total', 'partner a', 'partner b', 'regrade',
697d56dcd4aae19e6cb2351eb39a5c195f8ed029
instana/instrumentation/urllib3.py
instana/instrumentation/urllib3.py
import opentracing.ext.tags as ext import opentracing import wrapt @wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen') def urlopen_with_instana(wrapped, instance, args, kwargs): try: span = opentracing.global_tracer.start_span("urllib3") span.set_tag(ext.HTTP_URL, args[1]) span.set_tag(ext.HTTP_METHOD, args[0]) opentracing.global_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"]) rv = wrapped(*args, **kwargs) span.set_tag(ext.HTTP_STATUS_CODE, rv.status) if 500 <= rv.status <= 511: span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) except Exception as e: print("found error:", e) span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) raise else: span.finish() return rv
from __future__ import absolute_import import opentracing.ext.tags as ext import instana import opentracing import wrapt @wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen') def urlopen_with_instana(wrapped, instance, args, kwargs): try: span = instana.internal_tracer.start_span("urllib3") span.set_tag(ext.HTTP_URL, args[1]) span.set_tag(ext.HTTP_METHOD, args[0]) instana.internal_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"]) rv = wrapped(*args, **kwargs) span.set_tag(ext.HTTP_STATUS_CODE, rv.status) if 500 <= rv.status <= 599: span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) except Exception as e: span.log_kv({'message': e}) span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) raise else: span.finish() return rv
Expand 5xx coverage; log exceptions
Expand 5xx coverage; log exceptions
Python
mit
instana/python-sensor,instana/python-sensor
--- +++ @@ -1,4 +1,6 @@ +from __future__ import absolute_import import opentracing.ext.tags as ext +import instana import opentracing import wrapt @@ -6,21 +8,21 @@ @wrapt.patch_function_wrapper('urllib3', 'PoolManager.urlopen') def urlopen_with_instana(wrapped, instance, args, kwargs): try: - span = opentracing.global_tracer.start_span("urllib3") + span = instana.internal_tracer.start_span("urllib3") span.set_tag(ext.HTTP_URL, args[1]) span.set_tag(ext.HTTP_METHOD, args[0]) - opentracing.global_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"]) + instana.internal_tracer.inject(span.context, opentracing.Format.HTTP_HEADERS, kwargs["headers"]) + rv = wrapped(*args, **kwargs) - rv = wrapped(*args, **kwargs) span.set_tag(ext.HTTP_STATUS_CODE, rv.status) - if 500 <= rv.status <= 511: + if 500 <= rv.status <= 599: span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1) except Exception as e: - print("found error:", e) + span.log_kv({'message': e}) span.set_tag("error", True) ec = span.tags.get('ec', 0) span.set_tag("ec", ec+1)
f48c15a6b0c09db26a0f1b0e8846acf1c5e8cc62
plyer/platforms/ios/gyroscope.py
plyer/platforms/ios/gyroscope.py
''' iOS Gyroscope --------------------- ''' from plyer.facades import Gyroscope from pyobjus import autoclass from pyobjus.dylib_manager import load_framework load_framework('/System/Library/Frameworks/UIKit.framework') UIDevice = autoclass('UIDevice') device = UIDevice.currentDevice() class IosGyroscope(Gyroscope): def __init__(self): super(IosGyroscope, self).__init__() self.bridge = autoclass('bridge').alloc().init() if int(device.systemVersion.UTF8String().split('.')[0]) <= 4: self.bridge.motionManager.setGyroscopeUpdateInterval_(0.1) else: self.bridge.motionManager.setGyroUpdateInterval_(0.1) def _enable(self): self.bridge.startGyroscope() def _disable(self): self.bridge.stopGyroscope() def _get_orientation(self): return ( self.bridge.gy_x, self.bridge.gy_y, self.bridge.gy_z) def instance(): return IosGyroscope()
''' iOS Gyroscope --------------------- ''' from plyer.facades import Gyroscope from pyobjus import autoclass from pyobjus.dylib_manager import load_framework load_framework('/System/Library/Frameworks/UIKit.framework') UIDevice = autoclass('UIDevice') device = UIDevice.currentDevice() class IosGyroscope(Gyroscope): def __init__(self): super(IosGyroscope, self).__init__() self.bridge = autoclass('bridge').alloc().init() if int(device.systemVersion.UTF8String().split('.')[0]) <= 4: self.bridge.motionManager.setGyroscopeUpdateInterval_(0.1) else: self.bridge.motionManager.setGyroUpdateInterval_(0.1) self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1) def _enable(self): self.bridge.startGyroscope() self.bridge.startDeviceMotion() def _disable(self): self.bridge.stopGyroscope() self.bridge.stopDeviceMotion() def _get_orientation(self): return ( self.bridge.rotation_rate_x, self.bridge.rotation_rate_y, self.bridge.rotation_rate_z) def _get_rotation_uncalib(self): return ( self.bridge.gy_x, self.bridge.gy_y, self.bridge.gy_z, self.bridge.gy_x - self.bridge.rotation_rate_x, self.bridge.gy_y - self.bridge.rotation_rate_y, self.bridge.gy_z - self.bridge.rotation_rate_z) def instance(): return IosGyroscope()
Add method for uncalibrated values of iOS Gyroscope
Add method for uncalibrated values of iOS Gyroscope
Python
mit
KeyWeeUsr/plyer,KeyWeeUsr/plyer,kivy/plyer,KeyWeeUsr/plyer,kivy/plyer,kivy/plyer
--- +++ @@ -25,17 +25,30 @@ else: self.bridge.motionManager.setGyroUpdateInterval_(0.1) + self.bridge.motionManager.setDeviceMotionUpdateInterval_(0.1) + def _enable(self): self.bridge.startGyroscope() + self.bridge.startDeviceMotion() def _disable(self): self.bridge.stopGyroscope() + self.bridge.stopDeviceMotion() def _get_orientation(self): return ( + self.bridge.rotation_rate_x, + self.bridge.rotation_rate_y, + self.bridge.rotation_rate_z) + + def _get_rotation_uncalib(self): + return ( self.bridge.gy_x, self.bridge.gy_y, - self.bridge.gy_z) + self.bridge.gy_z, + self.bridge.gy_x - self.bridge.rotation_rate_x, + self.bridge.gy_y - self.bridge.rotation_rate_y, + self.bridge.gy_z - self.bridge.rotation_rate_z) def instance():
03bc712bca2001042fd856add659854d27b0a5b9
src/ansible/urls.py
src/ansible/urls.py
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileCreateView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/files/new/$', PlaybookFileCreateView.as_view(), name='playbook-file-create' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
from django.conf.urls import url from ansible.forms import AnsibleForm1, AnsibleForm2 from ansible.views import ( PlaybookWizard, PlaybookListView, PlaybookDetailView, PlaybookFileCreateView, PlaybookFileEditView, PlaybookFileView ) from . import views urlpatterns = [ url(r'^create/$', PlaybookWizard.as_view([AnsibleForm1, AnsibleForm2])), url(r'^$', PlaybookListView.as_view(), name='playbook-list'), url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), url(r'^(?P<pk>[-\w]+)/new/$', PlaybookFileCreateView.as_view(), name='playbook-file-create' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$', PlaybookFileEditView.as_view(), name='playbook-file-edit' ), ]
Rewrite URLs for playbook app
Rewrite URLs for playbook app
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
--- +++ @@ -13,10 +13,10 @@ url(r'^(?P<pk>[-\w]+)/$', PlaybookDetailView.as_view(), name='playbook-detail' ), - url(r'^(?P<pk>[-\w]+)/files/new/$', + url(r'^(?P<pk>[-\w]+)/new/$', PlaybookFileCreateView.as_view(), name='playbook-file-create' ), - url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/$', + url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)$', PlaybookFileView.as_view(), name='playbook-file-detail' ), url(r'^(?P<pk>[-\w]+)/files/(?P<slug>[\w-]+)/edit$',
9bcacb5488d32e9e4483c0b54abfa548885148d2
tamarackcollector/worker.py
tamarackcollector/worker.py
import json import requests import time from collections import Counter from multiprocessing import Process, Queue from queue import Empty shared_queue = None def datetime_by_minute(dt): return dt.replace(second=0, microsecond=0).isoformat() + 'Z' def process_jobs(url, app_id, queue): while True: time.sleep(60) by_minute = {} while True: try: i = queue.get_nowait() except Empty: break minute = datetime_by_minute(i['timestamp']) endpoint = i['endpoint'] if (minute, endpoint) not in by_minute: by_minute[(minute, endpoint)] = { 'sensor_data': Counter(), 'timestamp': minute, 'endpoint': endpoint, } sensor_data = by_minute[(minute, endpoint)]['sensor_data'] sensor_data['request_count'] += i['request_count'] sensor_data['error_count'] += i['error_count'] sensor_data['total_time'] += i['total_time'] if not by_minute: continue data = { 'app_name': app_id, 'by_minute': list(by_minute.values()), } requests.post(url, data=json.dumps(data)) def start_worker(url, app_id): q = Queue() p = Process(target=process_jobs, args=(url, app_id, q, )) p.start() global shared_queue shared_queue = q
import json import requests import time from collections import Counter from multiprocessing import Process, Queue from queue import Empty shared_queue = None def datetime_by_minute(dt): return dt.replace(second=0, microsecond=0).isoformat() + 'Z' def process_jobs(url, app_id, queue): while True: time.sleep(60) by_minute = {} while True: try: i = queue.get_nowait() except Empty: break minute = datetime_by_minute(i['timestamp']) endpoint = i['endpoint'] if (minute, endpoint) not in by_minute: by_minute[(minute, endpoint)] = { 'sensor_data': Counter(), 'timestamp': minute, 'endpoint': endpoint, 'request_count': 0, 'error_count': 0, } minute_data = by_minute[(minute, endpoint)] minute_data['request_count'] += i['request_count'] minute_data['error_count'] += i['error_count'] minute_data['sensor_data']['total_time'] += i['total_time'] if not by_minute: continue data = { 'app_name': app_id, 'by_minute': list(by_minute.values()), } requests.post(url, data=json.dumps(data)) def start_worker(url, app_id): q = Queue() p = Process(target=process_jobs, args=(url, app_id, q, )) p.start() global shared_queue shared_queue = q
Send request_count and error_count outside sensor_data
Send request_count and error_count outside sensor_data
Python
bsd-3-clause
tamarackapp/tamarack-collector-py
--- +++ @@ -32,12 +32,14 @@ 'sensor_data': Counter(), 'timestamp': minute, 'endpoint': endpoint, + 'request_count': 0, + 'error_count': 0, } - sensor_data = by_minute[(minute, endpoint)]['sensor_data'] - sensor_data['request_count'] += i['request_count'] - sensor_data['error_count'] += i['error_count'] - sensor_data['total_time'] += i['total_time'] + minute_data = by_minute[(minute, endpoint)] + minute_data['request_count'] += i['request_count'] + minute_data['error_count'] += i['error_count'] + minute_data['sensor_data']['total_time'] += i['total_time'] if not by_minute: continue
46dda5e761d3752fce26b379cc8542e3f5244376
examples/fabfile.py
examples/fabfile.py
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @task(default=True, alias="success") @notify def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) @task(alias="failure") @notify def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) @task(alias="has_roles") @notify @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test')
"""Example of integration between Fabric and Datadog. """ from fabric.api import * from fabric.colors import * from dogapi.fab import setup, notify setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task @notify @task(default=True, alias="success") def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) @notify @task(alias="failure") def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) raise Exception("failure!!!") env.roledefs.update({ 'webserver': ['localhost'] }) @notify @task(alias="has_roles") @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2): run('touch /tmp/fab_test')
Make sure @ notify is the first decorator
Make sure @ notify is the first decorator fixes #91
Python
bsd-3-clause
DataDog/dogapi,DataDog/dogapi
--- +++ @@ -8,14 +8,14 @@ setup(api_key = "YOUR API KEY HERE") # Make sure @notify is just below @task +@notify @task(default=True, alias="success") -@notify def sweet_task(some_arg, other_arg): """Always succeeds""" print(green("My sweet task always runs properly.")) +@notify @task(alias="failure") -@notify def boring_task(some_arg): """Always fails""" print(red("My boring task is designed to fail.")) @@ -25,8 +25,8 @@ 'webserver': ['localhost'] }) +@notify @task(alias="has_roles") -@notify @roles('webserver') @hosts('localhost') def roles_task(arg_1, arg_2):
3680c9e874df4daf2981d524a311d292293ca6d6
scrapi/settings/travis-dist.py
scrapi/settings/travis-dist.py
DEBUG = False BROKER_URL = 'amqp://guest@localhost' RECORD_HTTP_TRANSACTIONS = False CELERY_EAGER_PROPAGATES_EXCEPTIONS = True RAW_PROCESSING = ['cassandra', 'postgres'] NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres'] RESPONSE_PROCESSING = 'postgres' SENTRY_DSN = None USE_FLUENTD = False CASSANDRA_URI = ['127.0.0.1'] CASSANDRA_KEYSPACE = 'scrapi' ELASTIC_URI = 'localhost:9200' ELASTIC_TIMEOUT = 10 ELASTIC_INDEX = 'share' PLOS_API_KEY = 'fakekey' HARVARD_DATAVERSE_API_KEY = 'anotherfakekey' disabled = ['stepic', 'shareok'] FRONTEND_KEYS = [ u'description', u'contributors', u'tags', u'raw', u'title', u'id', u'source', u'dateUpdated' ]
DEBUG = False BROKER_URL = 'amqp://guest@localhost' RECORD_HTTP_TRANSACTIONS = False CELERY_EAGER_PROPAGATES_EXCEPTIONS = True RAW_PROCESSING = ['cassandra', 'postgres'] NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres'] RESPONSE_PROCESSING = 'cassandra' SENTRY_DSN = None USE_FLUENTD = False CASSANDRA_URI = ['127.0.0.1'] CASSANDRA_KEYSPACE = 'scrapi' ELASTIC_URI = 'localhost:9200' ELASTIC_TIMEOUT = 10 ELASTIC_INDEX = 'share' PLOS_API_KEY = 'fakekey' HARVARD_DATAVERSE_API_KEY = 'anotherfakekey' disabled = ['stepic', 'shareok'] FRONTEND_KEYS = [ u'description', u'contributors', u'tags', u'raw', u'title', u'id', u'source', u'dateUpdated' ]
Change resp processing to cassandra -- need to fix tests for postgres
Change resp processing to cassandra -- need to fix tests for postgres
Python
apache-2.0
mehanig/scrapi,felliott/scrapi,fabianvf/scrapi,mehanig/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,erinspace/scrapi
--- +++ @@ -8,7 +8,7 @@ RAW_PROCESSING = ['cassandra', 'postgres'] NORMALIZED_PROCESSING = ['elasticsearch', 'cassandra', 'postgres'] -RESPONSE_PROCESSING = 'postgres' +RESPONSE_PROCESSING = 'cassandra' SENTRY_DSN = None
235bf56a4f80475f618a62db15844d7a004dd967
scripts/TestFontCompilation.py
scripts/TestFontCompilation.py
from string import split from os import remove from mojo.roboFont import version from jkRFoTools.FontChooser import ProcessFonts def test_compilation(font): temp_font = font.copy(showUI=False) for g in temp_font: g.clear() if font.path is None: return "ERROR: The font needs to be saved first." myPath = font.path + "_compiletest.otf" result = temp_font.generate(myPath, "otf") temp_font.close() lines = split(result, "\n") if version[:3] == "1.5": checkLine = -3 elif version[:3] == "1.6": checkLine = -1 else: checkLine = -10 if lines[checkLine][:15] == "makeotf [Error]": test_result = "" for r in lines: if r[:18] in ["makeotfexe [ERROR]", "makeotfexe [FATAL]"]: test_result += r[11:] + "\n" else: test_result = "OK" remove(myPath) return test_result ProcessFonts("Test Compilation", test_compilation)
from os import remove from os.path import exists from mojo.roboFont import version from jkRFoTools.FontChooser import ProcessFonts from fontCompiler.compiler import FontCompilerOptions from fontCompiler.emptyCompiler import EmptyOTFCompiler def test_compilation(font): if font.path is None: return "ERROR: The font needs to be saved first." font = font.naked() compiler = EmptyOTFCompiler() options = FontCompilerOptions() options.outputPath = font.path + "_compiletest.otf" reports = compiler.compile(font, options) if not "makeotf" in reports: return "OK" result = reports["makeotf"] lines = result.splitlines() if lines[-2][:15] == "makeotf [Error]": test_result = "" for r in lines: if r[:18] in ["makeotfexe [ERROR]", "makeotfexe [FATAL]"]: test_result += r[11:] + "\n" else: test_result = "OK" if exists(options.outputPath): remove(options.outputPath) return test_result ProcessFonts("Test Compilation", test_compilation)
Use EmptyOTFCompiler for test compilation
Use EmptyOTFCompiler for test compilation
Python
mit
jenskutilek/RoboFont,jenskutilek/RoboFont
--- +++ @@ -1,39 +1,36 @@ -from string import split from os import remove +from os.path import exists from mojo.roboFont import version from jkRFoTools.FontChooser import ProcessFonts +from fontCompiler.compiler import FontCompilerOptions +from fontCompiler.emptyCompiler import EmptyOTFCompiler + def test_compilation(font): - temp_font = font.copy(showUI=False) - - for g in temp_font: - g.clear() - if font.path is None: return "ERROR: The font needs to be saved first." - - myPath = font.path + "_compiletest.otf" - result = temp_font.generate(myPath, "otf") - temp_font.close() - - lines = split(result, "\n") - - if version[:3] == "1.5": - checkLine = -3 - elif version[:3] == "1.6": - checkLine = -1 - else: - checkLine = -10 - - if lines[checkLine][:15] == "makeotf [Error]": + font = font.naked() + compiler = EmptyOTFCompiler() + options = FontCompilerOptions() + options.outputPath = font.path + "_compiletest.otf" + reports = compiler.compile(font, options) + + if not "makeotf" in reports: + return "OK" + + result = reports["makeotf"] + lines = result.splitlines() + + if lines[-2][:15] == "makeotf [Error]": test_result = "" for r in lines: if r[:18] in ["makeotfexe [ERROR]", "makeotfexe [FATAL]"]: test_result += r[11:] + "\n" else: test_result = "OK" - remove(myPath) + if exists(options.outputPath): + remove(options.outputPath) return test_result ProcessFonts("Test Compilation", test_compilation)
61e6fbbba42256f0a4b9d8b6ad25575ec6c21fee
scripts/datachain/datachain.py
scripts/datachain/datachain.py
import os import sys import MySQLdb sys.path.append('D:\\Projects\\PySQLKits\\lib\\simplequery') from table_data import * from simplequery import * def get_mysql_connection(): args = {'host':'localhost', 'user':'root', 'passwd':'root', 'db':"test"} conn = MySQLdb.connect(**args) with conn.cursor() as c: c.execute('show databases;') print(list(map(lambda x: x[0], c.fetchall()))) return conn """ """ if __name__ == '__main__': e = SimpleQueryExecutor() conn = get_mysql_connection() #print(conn) #exit() e.set_connection(conn) filename = sys.argv[1] params = None if len(sys.argv) > 2: params = sys.argv[2:] if os.path.exists(filename): e.run_file(filename, params)
import os from os.path import dirname import sys import MySQLdb root_path = dirname(dirname(os.getcwd())) require_path = os.path.join(root_path, 'lib\\simplequery') sys.path.append(require_path) from table_data import * from simplequery import * def get_mysql_connection(): args = {'host':'localhost', 'user':'root', 'passwd':'root', 'db':"test"} conn = MySQLdb.connect(**args) with conn.cursor() as c: c.execute('show databases;') print(list(map(lambda x: x[0], c.fetchall()))) return conn def usage(): print('Help:') """ Run file with argv[] """ if __name__ == '__main__': if len(sys.argv) < 2: usage() exit() e = SimpleQueryExecutor() conn = get_mysql_connection() #print(conn) #exit() e.set_connection(conn) filename = sys.argv[1] params = None if len(sys.argv) > 2: params = sys.argv[2:] if os.path.exists(filename): e.run_file(filename, params)
Refactor import path and usage
Refactor import path and usage
Python
mit
healerkx/PySQLKits,healerkx/PySQLKits
--- +++ @@ -1,8 +1,13 @@ import os +from os.path import dirname import sys import MySQLdb -sys.path.append('D:\\Projects\\PySQLKits\\lib\\simplequery') + +root_path = dirname(dirname(os.getcwd())) +require_path = os.path.join(root_path, 'lib\\simplequery') +sys.path.append(require_path) + from table_data import * from simplequery import * @@ -17,10 +22,16 @@ print(list(map(lambda x: x[0], c.fetchall()))) return conn +def usage(): + print('Help:') """ +Run file with argv[] """ if __name__ == '__main__': + if len(sys.argv) < 2: + usage() + exit() e = SimpleQueryExecutor() conn = get_mysql_connection()
fd2d61e6b9ce22a404ab404dcf4b4a53fe91f81a
aybu/controlpanel/handlers/base.py
aybu/controlpanel/handlers/base.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2010 Asidev s.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging from aybu.core.models import User class BaseHandler(object): __autoexpose__ = None def __init__(self, request): self.request = request self.session = self.request.db_session self.request.template_helper.rendering_type = 'static' self.request.template_helper.section = 'admin' self.log = logging.getLogger("%s.%s" % ( self.__class__.__module__, self.__class__.__name__)) # TODO set language of request from session @property def user(self): import warning warning.warn("User is not yet taken from session") return self.session.query(User).first()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2010 Asidev s.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import logging from pyramid.httpexceptions import HTTPBadRequest from aybu.core.models import Language class BaseHandler(object): __autoexpose__ = None def __init__(self, request): self.request = request self.session = self.request.db_session self.request.template_helper.rendering_type = 'static' self.request.template_helper.section = 'admin' self.log = logging.getLogger("%s.%s" % ( self.__class__.__module__, self.__class__.__name__)) lang = request.params.get('lang') country = request.params.get('country') if bool(lang) ^ bool(country): # either the request contains no lang options or both. # if the request contains only one of the two, it's a bad request raise HTTPBadRequest() elif lang: self.log.debug('Setting language to %s', lang) request.language = Language.get_by_lang(request.db_session, lang)
Set request language in admin panel if user request a different language
Set request language in admin panel if user request a different language
Python
apache-2.0
asidev/aybu-controlpanel
--- +++ @@ -17,7 +17,8 @@ """ import logging -from aybu.core.models import User +from pyramid.httpexceptions import HTTPBadRequest +from aybu.core.models import Language class BaseHandler(object): @@ -30,10 +31,13 @@ self.request.template_helper.section = 'admin' self.log = logging.getLogger("%s.%s" % ( self.__class__.__module__, self.__class__.__name__)) - # TODO set language of request from session - @property - def user(self): - import warning - warning.warn("User is not yet taken from session") - return self.session.query(User).first() + lang = request.params.get('lang') + country = request.params.get('country') + if bool(lang) ^ bool(country): + # either the request contains no lang options or both. + # if the request contains only one of the two, it's a bad request + raise HTTPBadRequest() + elif lang: + self.log.debug('Setting language to %s', lang) + request.language = Language.get_by_lang(request.db_session, lang)
0e04613306defe11f1c358a594352008120c7b41
datasets/admin.py
datasets/admin.py
from django.contrib import admin from datasets.models import Dataset, Sound, Vote, Taxonomy, DatasetRelease, TaxonomyNode class TaxonomyNodeAdmin(admin.ModelAdmin): fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples', 'list_freesound_examples_verification') admin.site.register(Dataset) admin.site.register(Sound) admin.site.register(Vote) admin.site.register(Taxonomy) admin.site.register(DatasetRelease) admin.site.register(TaxonomyNode, TaxonomyNodeAdmin)
from django.contrib import admin from datasets.models import Dataset, Sound, Vote, Taxonomy, DatasetRelease, TaxonomyNode class TaxonomyNodeAdmin(admin.ModelAdmin): fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples', 'list_freesound_examples_verification', 'beginner_task') admin.site.register(Dataset) admin.site.register(Sound) admin.site.register(Vote) admin.site.register(Taxonomy) admin.site.register(DatasetRelease) admin.site.register(TaxonomyNode, TaxonomyNodeAdmin)
Add Admin beginner task field TaxonomyNode
Add Admin beginner task field TaxonomyNode
Python
agpl-3.0
MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets
--- +++ @@ -4,7 +4,7 @@ class TaxonomyNodeAdmin(admin.ModelAdmin): fields = ('node_id', 'name', 'description', 'citation_uri', 'faq', 'omitted', 'list_freesound_examples', - 'list_freesound_examples_verification') + 'list_freesound_examples_verification', 'beginner_task') admin.site.register(Dataset)
39228ca69262511b1d0efbfc437dda19c097d530
logger.py
logger.py
from time import strftime """logger.py: A simple logging module""" __author__ = "Prajesh Ananthan" def printDebug(text): print(strftime('%d/%b/%Y %H:%M:%S DEBUG | {}'.format(text))) def printInfo(text): print(strftime('%d/%b/%Y %H:%M:%S INFO | {}'.format(text))) def printWarning(text): print(strftime('%d/%b/%Y %H:%M:%S WARNING | {}'.format(text)))
from time import strftime """logger.py: A simple logging module""" __author__ = "Prajesh Ananthan" def DEBUG(text): print(strftime('%d/%b/%Y %H:%M:%S DEBUG | {}'.format(text))) def INFO(text): print(strftime('%d/%b/%Y %H:%M:%S INFO | {}'.format(text))) def WARNING(text): print(strftime('%d/%b/%Y %H:%M:%S WARNING | {}'.format(text))) def ERROR(text): print(strftime('%d/%b/%Y %H:%M:%S ERROR | {}'.format(text)))
Update on the method names
Update on the method names
Python
mit
prajesh-ananthan/Tools
--- +++ @@ -5,13 +5,17 @@ __author__ = "Prajesh Ananthan" -def printDebug(text): +def DEBUG(text): print(strftime('%d/%b/%Y %H:%M:%S DEBUG | {}'.format(text))) -def printInfo(text): +def INFO(text): print(strftime('%d/%b/%Y %H:%M:%S INFO | {}'.format(text))) -def printWarning(text): +def WARNING(text): print(strftime('%d/%b/%Y %H:%M:%S WARNING | {}'.format(text))) + + +def ERROR(text): + print(strftime('%d/%b/%Y %H:%M:%S ERROR | {}'.format(text)))
fb5fc6e62a3c1b018d8f68cc37e4d541226a564b
integration-tests/features/steps/gremlin.py
integration-tests/features/steps/gremlin.py
"""Tests for Gremlin database.""" import os import requests from behave import given, then, when from urllib.parse import urljoin @when('I access Gremlin API') def gremlin_url_access(context): """Access the Gremlin service API using the HTTP POST method.""" post_query(context, "") def post_query(context, query): """Post the already constructed query to the Gremlin.""" data = {"gremlin": query} context.response = requests.post(context.gremlin_url, json=data)
"""Tests for Gremlin database.""" import os import requests from behave import given, then, when from urllib.parse import urljoin from src.json_utils import * @when('I access Gremlin API') def gremlin_url_access(context): """Access the Gremlin service API using the HTTP POST method.""" post_query(context, "") def post_query(context, query): """Post the already constructed query to the Gremlin.""" data = {"gremlin": query} context.response = requests.post(context.gremlin_url, json=data) @then('I should get valid Gremlin response') def valid_gremlin_response(context): """Check that the Gremlin response is valid.""" check_request_id_value_in_json_response(context, "requestId") data = context.response.json() assert data, "Gremlin does not send a proper response" check_gremlin_status_node(data) check_gremlin_result_node(data) def check_gremlin_status_node(data): """Check the basic structure of the 'status' node in Gremlin response.""" status = check_and_get_attribute(data, "status") message = check_and_get_attribute(status, "message") code = check_and_get_attribute(status, "code") attributes = check_and_get_attribute(status, "attributes") assert message == "" assert code == 200 def check_gremlin_result_node(data): """Check the basic structure of the 'result' node in Gremlin response.""" result = check_and_get_attribute(data, "result") data = check_and_get_attribute(result, "data") meta = check_and_get_attribute(result, "meta") assert type(data) is list assert type(meta) is dict
Test step for check the Gremlin response structure
Test step for check the Gremlin response structure
Python
apache-2.0
tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common,jpopelka/fabric8-analytics-common,tisnik/fabric8-analytics-common,tisnik/fabric8-analytics-common,jpopelka/fabric8-analytics-common
--- +++ @@ -4,6 +4,7 @@ from behave import given, then, when from urllib.parse import urljoin +from src.json_utils import * @when('I access Gremlin API') @@ -16,3 +17,36 @@ """Post the already constructed query to the Gremlin.""" data = {"gremlin": query} context.response = requests.post(context.gremlin_url, json=data) + + +@then('I should get valid Gremlin response') +def valid_gremlin_response(context): + """Check that the Gremlin response is valid.""" + check_request_id_value_in_json_response(context, "requestId") + + data = context.response.json() + assert data, "Gremlin does not send a proper response" + + check_gremlin_status_node(data) + check_gremlin_result_node(data) + + +def check_gremlin_status_node(data): + """Check the basic structure of the 'status' node in Gremlin response.""" + status = check_and_get_attribute(data, "status") + message = check_and_get_attribute(status, "message") + code = check_and_get_attribute(status, "code") + attributes = check_and_get_attribute(status, "attributes") + + assert message == "" + assert code == 200 + + +def check_gremlin_result_node(data): + """Check the basic structure of the 'result' node in Gremlin response.""" + result = check_and_get_attribute(data, "result") + data = check_and_get_attribute(result, "data") + meta = check_and_get_attribute(result, "meta") + + assert type(data) is list + assert type(meta) is dict
0bd469751034c9a9bc9c3b6f396885670722a692
manage.py
manage.py
#!/usr/bin/env python import os from flask_script import Manager, Server from flask_script.commands import ShowUrls, Clean from mothership import create_app from mothership.models import db # default to dev config because no one should use this in # production anyway env = os.environ.get('MOTHERSHIP_ENV', 'dev') app = create_app('mothership.settings.%sConfig' % env.capitalize()) manager = Manager(app) manager.add_command("server", Server()) manager.add_command("show-urls", ShowUrls()) manager.add_command("clean", Clean()) @manager.shell def make_shell_context(): """ Creates a python REPL with several default imports in the context of the app """ return dict(app=app, db=db) # return dict(app=app, db=db, User=User) @manager.command def createdb(): """ Creates a database with all of the tables defined in your SQLAlchemy models """ db.create_all() if __name__ == "__main__": manager.run() # ./venv/bin/uwsgi --http 0.0.0.0:8000 --home venv --wsgi-file manage.py --callable app --master --catch-exceptions
#!/usr/bin/env python import os from flask_script import Manager, Server from flask_script.commands import ShowUrls, Clean from mothership import create_app from mothership.models import db # default to dev config because no one should use this in # production anyway env = os.environ.get('MOTHERSHIP_ENV', 'dev') app = create_app('mothership.settings.%sConfig' % env.capitalize()) manager = Manager(app) manager.add_command("server", Server()) manager.add_command("show-urls", ShowUrls()) manager.add_command("clean", Clean()) @manager.shell def make_shell_context(): """ Creates a python REPL with several default imports in the context of the app """ return dict(app=app, db=db) # return dict(app=app, db=db, User=User) @manager.command def createdb(): """ Creates a database with all of the tables defined in your SQLAlchemy models """ db.create_all() if __name__ == "__main__": manager.run()
Remove comment for running under uwsgi
Remove comment for running under uwsgi
Python
mit
afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership
--- +++ @@ -38,6 +38,3 @@ if __name__ == "__main__": manager.run() - - -# ./venv/bin/uwsgi --http 0.0.0.0:8000 --home venv --wsgi-file manage.py --callable app --master --catch-exceptions
243f973ee1757b7b8426e9e4b62de2a272d82407
protocols/urls.py
protocols/urls.py
from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), )
from django.conf.urls import patterns, url urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), url(r'^page/(?P<page>.*)/$', 'listing', name='pagination') )
Add url for listing protocols
Add url for listing protocols
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
--- +++ @@ -4,4 +4,5 @@ urlpatterns = patterns('protocols.views', url(r'^archive/$', 'list_all_protocols', name='list_all_protocols'), url(r'^add/$', 'add', name='add_protocol'), + url(r'^page/(?P<page>.*)/$', 'listing', name='pagination') )
ef98d8bf242bfd182b4e5c8675db599182a371a5
metpy/io/__init__.py
metpy/io/__init__.py
# Copyright (c) 2015,2016,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """MetPy's IO module contains classes for reading files. These classes are written to take both file names (for local files) or file-like objects; this allows reading files that are already in memory (using :class:`python:io.StringIO`) or remote files (using :func:`~python:urllib.request.urlopen`). """ from .gini import * # noqa: F403 from .nexrad import * # noqa: F403 __all__ = gini.__all__[:] # pylint: disable=undefined-variable __all__.extend(nexrad.__all__) # pylint: disable=undefined-variable
# Copyright (c) 2015,2016,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Classes for reading various file formats. These classes are written to take both file names (for local files) or file-like objects; this allows reading files that are already in memory (using :class:`python:io.StringIO`) or remote files (using :func:`~python:urllib.request.urlopen`). """ from .gini import * # noqa: F403 from .nexrad import * # noqa: F403 __all__ = gini.__all__[:] # pylint: disable=undefined-variable __all__.extend(nexrad.__all__) # pylint: disable=undefined-variable
Make io module docstring conform to standards
MNT: Make io module docstring conform to standards Picked up by pydocstyle 3.0.
Python
bsd-3-clause
Unidata/MetPy,ShawnMurd/MetPy,ahaberlie/MetPy,jrleeman/MetPy,dopplershift/MetPy,jrleeman/MetPy,Unidata/MetPy,ahaberlie/MetPy,dopplershift/MetPy
--- +++ @@ -1,10 +1,11 @@ # Copyright (c) 2015,2016,2018 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause -"""MetPy's IO module contains classes for reading files. These classes are written -to take both file names (for local files) or file-like objects; this allows reading files -that are already in memory (using :class:`python:io.StringIO`) or remote files -(using :func:`~python:urllib.request.urlopen`). +"""Classes for reading various file formats. + +These classes are written to take both file names (for local files) or file-like objects; +this allows reading files that are already in memory (using :class:`python:io.StringIO`) +or remote files (using :func:`~python:urllib.request.urlopen`). """ from .gini import * # noqa: F403
d483d47ec6670a0be82c323397d995e8f2fb506c
sphinxcontrib/openstreetmap.py
sphinxcontrib/openstreetmap.py
# -*- coding: utf-8 -*- """ sphinxcontrib.openstreetmap =========================== Embed OpenStreetMap on your documentation. :copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com> :license: BSD, see LICENSE for details. """ from docutils import nodes from docutils.parsers.rst import directives from sphinx.util.compat import Directive class openstreetmap(nodes.General, nodes.Element): pass class OpenStreetMapDirective(Directive): """Directive for embedding OpenStreetMap""" has_content = False option_spec = { 'name': directives.unchanged, 'label': directives.unchanged } def run(self): node = openstreetmap() return [node] def visit_openstreetmap_node(self, node): self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>") def depart_openstreetmap_node(self, node): pass def setup(app): app.add_node(openstreetmap, html=(visit_openstreetmap_node, depart_openstreetmap_node)) app.add_directive('openstreetmap', OpenStreetMapDirective)
# -*- coding: utf-8 -*- """ sphinxcontrib.openstreetmap =========================== Embed OpenStreetMap on your documentation. :copyright: Copyright 2015 HAYASHI Kentaro <kenhys@gmail.com> :license: BSD, see LICENSE for details. """ from docutils import nodes from docutils.parsers.rst import directives from sphinx.util.compat import Directive class openstreetmap(nodes.General, nodes.Element): pass class OpenStreetMapDirective(Directive): """Directive for embedding OpenStreetMap""" has_content = False option_spec = { 'id': directives.unchanged, 'label': directives.unchanged } def run(self): node = openstreetmap() return [node] def visit_openstreetmap_node(self, node): self.body.append("<div id='openstreetmap' style='color:red'>OpenStreetMap directive</div>") def depart_openstreetmap_node(self, node): pass def setup(app): app.add_node(openstreetmap, html=(visit_openstreetmap_node, depart_openstreetmap_node)) app.add_directive('openstreetmap', OpenStreetMapDirective)
Use id as required parameter
Use id as required parameter
Python
bsd-2-clause
kenhys/sphinxcontrib-openstreetmap,kenhys/sphinxcontrib-openstreetmap
--- +++ @@ -19,7 +19,7 @@ """Directive for embedding OpenStreetMap""" has_content = False option_spec = { - 'name': directives.unchanged, + 'id': directives.unchanged, 'label': directives.unchanged }
2f222b5ea9816f55c5a07c42650a7803b92241a4
cogs/routes/login.py
cogs/routes/login.py
""" Copyright (c) 2017 Genome Research Ltd. Authors: * Simon Beal <sb48@sanger.ac.uk> * Christopher Harrison <ch12@sanger.ac.uk> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. """ from aiohttp.web import Request, Response async def login(request:Request) -> Response: """ Log a user into the system and set their permissions FIXME I believe this is just a testing/debugging handler; it can probably be removed... :param request: :return: """ post_req = await request.post() user_type = post_req["type"] # FIXME The user is already fetched in the authentication middleware # or fails upon an authentication error (e.g., no such user) db = request.app["db"] user = db.get_user_by_id(1) user.user_type = user_type db.commit() return Response(text=user_type)
""" Copyright (c) 2017 Genome Research Ltd. Authors: * Simon Beal <sb48@sanger.ac.uk> * Christopher Harrison <ch12@sanger.ac.uk> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. """ from aiohttp.web import Request, Response async def login(request:Request) -> Response: """ Log a user into the system and set their permissions FIXME I believe this is just a testing/debugging handler; it can probably be removed... :param request: :return: """ post_req = await request.post() user_type = post_req["type"] user = request["user"] user.user_type = user_type request.app["db"].commit() # FIXME? Is this necessary? return Response(text=user_type)
Use the user that has been threaded through the request by the authentication middleware
Use the user that has been threaded through the request by the authentication middleware NOTE If the DummyAuthenticator is being used, then this will be the root user in every request, per the semantics of the original
Python
agpl-3.0
wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp,wtsi-hgi/CoGS-Webapp
--- +++ @@ -35,11 +35,8 @@ post_req = await request.post() user_type = post_req["type"] - # FIXME The user is already fetched in the authentication middleware - # or fails upon an authentication error (e.g., no such user) - db = request.app["db"] - user = db.get_user_by_id(1) + user = request["user"] user.user_type = user_type - db.commit() + request.app["db"].commit() # FIXME? Is this necessary? return Response(text=user_type)
8e3cc5821f3b597b256eb9f586380f3b3cfd35a8
qnd/experiment.py
qnd/experiment.py
import tensorflow as tf from .flag import FLAGS, FlagAdder from .estimator import def_estimator from .inputs import def_def_train_input_fn from .inputs import def_def_eval_input_fn def def_def_experiment_fn(): adder = FlagAdder() works_with = lambda name: "Works only with {}".format(name) train_help = works_with("qnd.train_and_evaluate()") adder.add_flag("train_steps", type=int, help=train_help) adder.add_flag("eval_steps", type=int, help=works_with("qnd.evaluate()")) adder.add_flag("min_eval_frequency", type=int, default=1, help=train_help) estimator = def_estimator() def_train_input_fn = def_def_train_input_fn() def_eval_input_fn = def_def_eval_input_fn() def def_experiment_fn(model_fn, input_fn): def experiment_fn(output_dir): return tf.contrib.learn.Experiment( estimator(model_fn, output_dir), def_train_input_fn(input_fn), def_eval_input_fn(input_fn), **{arg: getattr(FLAGS, arg) for arg in adder.flags}) return experiment_fn return def_experiment_fn
import tensorflow as tf from .flag import FLAGS, FlagAdder from .estimator import def_estimator from .inputs import DataUse, def_def_train_input_fn, def_def_eval_input_fn def def_def_experiment_fn(): adder = FlagAdder() for use in DataUse: use = use.value adder.add_flag("{}_steps".format(use), type=int, help="Maximum number of {} steps".format(use)) adder.add_flag("min_eval_frequency", type=int, default=1, help="Minimum evaluation frequency in number of model " "savings") estimator = def_estimator() def_train_input_fn = def_def_train_input_fn() def_eval_input_fn = def_def_eval_input_fn() def def_experiment_fn(model_fn, input_fn): def experiment_fn(output_dir): return tf.contrib.learn.Experiment( estimator(model_fn, output_dir), def_train_input_fn(input_fn), def_eval_input_fn(input_fn), **{arg: getattr(FLAGS, arg) for arg in adder.flags}) return experiment_fn return def_experiment_fn
Fix outdated command line help
Fix outdated command line help
Python
unlicense
raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd
--- +++ @@ -2,19 +2,20 @@ from .flag import FLAGS, FlagAdder from .estimator import def_estimator -from .inputs import def_def_train_input_fn -from .inputs import def_def_eval_input_fn +from .inputs import DataUse, def_def_train_input_fn, def_def_eval_input_fn def def_def_experiment_fn(): adder = FlagAdder() - works_with = lambda name: "Works only with {}".format(name) - train_help = works_with("qnd.train_and_evaluate()") + for use in DataUse: + use = use.value + adder.add_flag("{}_steps".format(use), type=int, + help="Maximum number of {} steps".format(use)) - adder.add_flag("train_steps", type=int, help=train_help) - adder.add_flag("eval_steps", type=int, help=works_with("qnd.evaluate()")) - adder.add_flag("min_eval_frequency", type=int, default=1, help=train_help) + adder.add_flag("min_eval_frequency", type=int, default=1, + help="Minimum evaluation frequency in number of model " + "savings") estimator = def_estimator() def_train_input_fn = def_def_train_input_fn()
b65a55189b7294547e14bea7593047f8f00518d6
partner_communication/models/res_partner.py
partner_communication/models/res_partner.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp import api, models, fields import logging logger = logging.getLogger(__name__) class ResPartner(models.Model): """ Add a field for communication preference. """ _inherit = 'res.partner' ########################################################################## # FIELDS # ########################################################################## global_communication_delivery_preference = fields.Selection( selection='_get_delivery_preference', default='auto_digital', required=True, help='Delivery preference for Global Communication') @api.model def _get_delivery_preference(self): return self.env[ 'partner.communication.config'].get_delivery_preferences()
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2016 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __openerp__.py # ############################################################################## from openerp import api, models, fields import logging logger = logging.getLogger(__name__) class ResPartner(models.Model): """ Add a field for communication preference. """ _inherit = 'res.partner' ########################################################################## # FIELDS # ########################################################################## global_communication_delivery_preference = fields.Selection( selection='_get_delivery_preference', default='digital', required=True, help='Delivery preference for Global Communication') @api.model def _get_delivery_preference(self): return self.env[ 'partner.communication.config'].get_delivery_preferences()
Change delivery of communication to manual digital by default
Change delivery of communication to manual digital by default
Python
agpl-3.0
CompassionCH/compassion-modules,ecino/compassion-modules,maxime-beck/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,maxime-beck/compassion-modules,ecino/compassion-modules,eicher31/compassion-modules,maxime-beck/compassion-modules,maxime-beck/compassion-modules,eicher31/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,ecino/compassion-modules
--- +++ @@ -24,7 +24,7 @@ ########################################################################## global_communication_delivery_preference = fields.Selection( selection='_get_delivery_preference', - default='auto_digital', + default='digital', required=True, help='Delivery preference for Global Communication')
2609042ba2a11089561d3c9d9f0542f263619951
src/models/event.py
src/models/event.py
from flock import db class Event(db.Model): id = db.Column(db.Integer, primary_key=True) def __init__(self): pass
from flock import db class Event(db.Model): id = db.Column(db.Integer, primary_key=True) owner_id = db.Column(db.Integer, foreign_key('user.id'), primary_key=True) def __init__(self): pass
Add owner as a primary, foreign key
Add owner as a primary, foreign key
Python
agpl-3.0
DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit
--- +++ @@ -3,6 +3,7 @@ class Event(db.Model): id = db.Column(db.Integer, primary_key=True) + owner_id = db.Column(db.Integer, foreign_key('user.id'), primary_key=True) def __init__(self): pass
ffee30cb1a5b9e477a7456bcd753a45c2a02fb4f
glance_registry_local_check.py
glance_registry_local_check.py
#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_token = keystone.auth_token registry_endpoint = 'http://127.0.0.1:9191' api_status = 1 milliseconds = 0 s = Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # /images returns a list of public, non-deleted images r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10) except (exc.ConnectionError, exc.HTTPError, exc.Timeout) as e: api_status = 0 milliseconds = -1 except Exception as e: status_err(str(e)) else: if r.ok: milliseconds = r.elapsed.total_seconds() * 1000 else: api_status = 0 milliseconds = -1 status_ok() metric('glance_registry_local_status', 'uint32', api_status) metric('glance_registry_local_response_time', 'uint32', milliseconds) def main(): auth_ref = get_auth_ref() check(auth_ref) if __name__ == "__main__": main()
#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_token = keystone.auth_token registry_endpoint = 'http://127.0.0.1:9191' api_status = 1 milliseconds = 0 s = Session() s.headers.update( {'Content-type': 'application/json', 'x-auth-token': auth_token}) try: # /images returns a list of public, non-deleted images r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10) except (exc.ConnectionError, exc.HTTPError, exc.Timeout): api_status = 0 milliseconds = -1 except Exception as e: status_err(str(e)) else: milliseconds = r.elapsed.total_seconds() * 1000 if not r.ok: api_status = 0 status_ok() metric('glance_registry_local_status', 'uint32', api_status) metric('glance_registry_local_response_time', 'uint32', milliseconds) def main(): auth_ref = get_auth_ref() check(auth_ref) if __name__ == "__main__": main()
Send proper response time even if non-200
Send proper response time even if non-200
Python
apache-2.0
claco/rpc-openstack,robb-romans/rpc-openstack,cloudnull/rpc-maas,mattt416/rpc-openstack,stevelle/rpc-openstack,nrb/rpc-openstack,npawelek/rpc-maas,xeregin/rpc-openstack,xeregin/rpc-openstack,shannonmitchell/rpc-openstack,cfarquhar/rpc-openstack,git-harry/rpc-openstack,sigmavirus24/rpc-openstack,prometheanfire/rpc-openstack,shannonmitchell/rpc-openstack,briancurtin/rpc-maas,cfarquhar/rpc-maas,byronmccollum/rpc-openstack,andymcc/rpc-openstack,mancdaz/rpc-openstack,jpmontez/rpc-openstack,darrenchan/rpc-openstack,xeregin/rpc-openstack,sigmavirus24/rpc-openstack,darrenchan/rpc-openstack,hughsaunders/rpc-openstack,cloudnull/rpc-openstack,busterswt/rpc-openstack,nrb/rpc-openstack,briancurtin/rpc-maas,mancdaz/rpc-openstack,prometheanfire/rpc-openstack,npawelek/rpc-maas,andymcc/rpc-openstack,stevelle/rpc-openstack,rcbops/rpc-openstack,briancurtin/rpc-maas,claco/rpc-openstack,mattt416/rpc-openstack,busterswt/rpc-openstack,galstrom21/rpc-openstack,cfarquhar/rpc-maas,miguelgrinberg/rpc-openstack,rcbops/rpc-openstack,claco/rpc-openstack,byronmccollum/rpc-openstack,cloudnull/rpc-maas,cloudnull/rpc-openstack,miguelgrinberg/rpc-openstack,BjoernT/rpc-openstack,major/rpc-openstack,npawelek/rpc-maas,robb-romans/rpc-openstack,xeregin/rpc-openstack,cloudnull/rpc-maas,andymcc/rpc-openstack,jacobwagner/rpc-openstack,sigmavirus24/rpc-openstack,miguelgrinberg/rpc-openstack,jacobwagner/rpc-openstack,sigmavirus24/rpc-openstack,nrb/rpc-openstack,galstrom21/rpc-openstack,darrenchan/rpc-openstack,major/rpc-openstack,mattt416/rpc-openstack,hughsaunders/rpc-openstack,busterswt/rpc-openstack,darrenchan/rpc-openstack,cfarquhar/rpc-openstack,stevelle/rpc-openstack,jpmontez/rpc-openstack,BjoernT/rpc-openstack,byronmccollum/rpc-openstack,git-harry/rpc-openstack,jpmontez/rpc-openstack,cfarquhar/rpc-maas
--- +++ @@ -26,17 +26,16 @@ r = s.get('%s/images' % registry_endpoint, verify=False, timeout=10) except (exc.ConnectionError, exc.HTTPError, - exc.Timeout) as e: + exc.Timeout): api_status = 0 milliseconds = -1 except Exception as e: status_err(str(e)) else: - if r.ok: - milliseconds = r.elapsed.total_seconds() * 1000 - else: + milliseconds = r.elapsed.total_seconds() * 1000 + + if not r.ok: api_status = 0 - milliseconds = -1 status_ok() metric('glance_registry_local_status', 'uint32', api_status)
6a462d6cbf1d82e9e600b997185a265bcd35b6e4
jsonrpc/__init__.py
jsonrpc/__init__.py
__version = (1, 0, 4) __version__ = version = '.'.join(map(str, __version)) __project__ = PROJECT = __name__ #from .jsonrpc import JSONRPCProtocol, JSONRPCRequest, JSONRPCResponse #from .exceptions import * # lint_ignore=W0611,W0401
__version = (1, 0, 5) __version__ = version = '.'.join(map(str, __version)) __project__ = PROJECT = __name__ #from .jsonrpc import JSONRPCProtocol, JSONRPCRequest, JSONRPCResponse #from .exceptions import * # lint_ignore=W0611,W0401
Update version: add python 3.3 to classifiers.
Update version: add python 3.3 to classifiers.
Python
mit
pavlov99/json-rpc
--- +++ @@ -1,4 +1,4 @@ -__version = (1, 0, 4) +__version = (1, 0, 5) __version__ = version = '.'.join(map(str, __version)) __project__ = PROJECT = __name__
0cebce08025844ae1e0154b7332779be0567e9ab
ipywidgets/widgets/__init__.py
ipywidgets/widgets/__init__.py
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout
from .widget import Widget, CallbackDispatcher, register, widget_serialization from .domwidget import DOMWidget from .trait_types import Color, EventfulDict, EventfulList from .widget_bool import Checkbox, ToggleButton, Valid from .widget_button import Button from .widget_box import Box, FlexBox, Proxy, PlaceProxy, HBox, VBox from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider from .widget_image import Image from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output from .widget_selection import RadioButtons, ToggleButtons, Dropdown, ScrollableDropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller from .interaction import interact, interactive, fixed, interact_manual from .widget_link import jslink, jsdlink from .widget_layout import Layout
Add ScrollableDropdown import to ipywidgets
Add ScrollableDropdown import to ipywidgets
Python
bsd-3-clause
ipython/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets
--- +++ @@ -11,7 +11,7 @@ from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider from .widget_color import ColorPicker from .widget_output import Output -from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select, SelectMultiple +from .widget_selection import RadioButtons, ToggleButtons, Dropdown, ScrollableDropdown, Select, SelectMultiple from .widget_selectioncontainer import Tab, Accordion from .widget_string import HTML, Latex, Text, Textarea from .widget_controller import Controller
f0c7e1b8a2de6f7e9445e2158cf679f399df6545
jupyternotify/jupyternotify.py
jupyternotify/jupyternotify.py
# see https://ipython.org/ipython-doc/3/config/custommagics.html # for more details on the implementation here import uuid from IPython.core.getipython import get_ipython from IPython.core.magic import Magics, magics_class, cell_magic from IPython.display import display, Javascript from pkg_resources import resource_filename @magics_class class JupyterNotifyMagics(Magics): def __init__(self, shell): super().__init__(shell) with open(resource_filename("jupyternotify", "js/init.js")) as jsFile: jsString = jsFile.read() display(Javascript(jsString)) @cell_magic def notify(self, line, cell): # generate a uuid so that we only deliver this notification once, not again # when the browser reloads (we append a div to check that) notification_uuid = uuid.uuid4() output = get_ipython().run_cell(cell) # display our browser notification using javascript with open(resource_filename("jupyternotify", "js/notify.js")) as jsFile: jsString = jsFile.read() display(Javascript(jsString % {"notification_uuid": notification_uuid})) # finally, if we generated an exception, print the traceback if output.error_in_exec is not None: output.raise_error()
# see https://ipython.org/ipython-doc/3/config/custommagics.html # for more details on the implementation here import uuid from IPython.core.getipython import get_ipython from IPython.core.magic import Magics, magics_class, cell_magic from IPython.display import display, Javascript from pkg_resources import resource_filename @magics_class class JupyterNotifyMagics(Magics): def __init__(self, shell): super(JupyterNotifyMagics, self).__init__(shell) with open(resource_filename("jupyternotify", "js/init.js")) as jsFile: jsString = jsFile.read() display(Javascript(jsString)) @cell_magic def notify(self, line, cell): # generate a uuid so that we only deliver this notification once, not again # when the browser reloads (we append a div to check that) notification_uuid = uuid.uuid4() output = get_ipython().run_cell(cell) # display our browser notification using javascript with open(resource_filename("jupyternotify", "js/notify.js")) as jsFile: jsString = jsFile.read() display(Javascript(jsString % {"notification_uuid": notification_uuid})) # finally, if we generated an exception, print the traceback if output.error_in_exec is not None: output.raise_error()
Make this work with python2 too.
Make this work with python2 too.
Python
bsd-3-clause
ShopRunner/jupyter-notify,ShopRunner/jupyter-notify
--- +++ @@ -11,7 +11,7 @@ @magics_class class JupyterNotifyMagics(Magics): def __init__(self, shell): - super().__init__(shell) + super(JupyterNotifyMagics, self).__init__(shell) with open(resource_filename("jupyternotify", "js/init.js")) as jsFile: jsString = jsFile.read() display(Javascript(jsString))
582fb412560ce068e2ac516a64ab1979beaccdb2
keystonemiddleware_echo/app.py
keystonemiddleware_echo/app.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import json import webob.dec @webob.dec.wsgify def echo_app(request): """A WSGI application that echoes the CGI environment to the user.""" return webob.Response(content_type='application/json', body=json.dumps(request.environ, indent=4)) def echo_app_factory(global_conf, **local_conf): import ipdb; ipdb.set_trace() return echo_app
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import pprint import webob.dec @webob.dec.wsgify def echo_app(request): """A WSGI application that echoes the CGI environment to the user.""" return webob.Response(content_type='application/json', body=pprint.pformat(request.environ, indent=4)) def echo_app_factory(global_conf, **local_conf): return echo_app
Use pprint instead of json for formatting
Use pprint instead of json for formatting json.dumps fails to print anything for an object. I would prefer to show a representation of the object rather than filter it out so rely on pprint instead.
Python
apache-2.0
jamielennox/keystonemiddleware-echo
--- +++ @@ -10,7 +10,7 @@ # License for the specific language governing permissions and limitations # under the License. -import json +import pprint import webob.dec @@ -18,9 +18,8 @@ def echo_app(request): """A WSGI application that echoes the CGI environment to the user.""" return webob.Response(content_type='application/json', - body=json.dumps(request.environ, indent=4)) + body=pprint.pformat(request.environ, indent=4)) def echo_app_factory(global_conf, **local_conf): - import ipdb; ipdb.set_trace() return echo_app
ac173dd3eace738b705ad5924aa830d3c3dffcf6
Instanssi/admin_screenshow/forms.py
Instanssi/admin_screenshow/forms.py
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import ValidationError from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.screenshow.models import Sponsor,Message,IRCMessage import os class MessageForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MessageForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Viesti', 'show_start', 'show_end', 'text', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = Message fields = ('show_start','show_end','text') class SponsorForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SponsorForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Sponsori', 'name', 'logo', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = Sponsor fields = ('name','logo')
# -*- coding: utf-8 -*- from django import forms from django.core.exceptions import ValidationError from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.screenshow.models import Sponsor,Message,IRCMessage import os class IRCMessageForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(IRCMessageForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'IRC-Viesti', 'nick', 'date', 'message', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = IRCMessage fields = ('nick','message','date') class MessageForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MessageForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Viesti', 'show_start', 'show_end', 'text', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = Message fields = ('show_start','show_end','text') class SponsorForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(SponsorForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( u'Sponsori', 'name', 'logo', ButtonHolder ( Submit('submit', u'Tallenna') ) ) ) class Meta: model = Sponsor fields = ('name','logo')
Add form for irc messages.
admin_screenshow: Add form for irc messages.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
--- +++ @@ -6,6 +6,26 @@ from crispy_forms.layout import Submit, Layout, Fieldset, ButtonHolder from Instanssi.screenshow.models import Sponsor,Message,IRCMessage import os + +class IRCMessageForm(forms.ModelForm): + def __init__(self, *args, **kwargs): + super(IRCMessageForm, self).__init__(*args, **kwargs) + self.helper = FormHelper() + self.helper.layout = Layout( + Fieldset( + u'IRC-Viesti', + 'nick', + 'date', + 'message', + ButtonHolder ( + Submit('submit', u'Tallenna') + ) + ) + ) + + class Meta: + model = IRCMessage + fields = ('nick','message','date') class MessageForm(forms.ModelForm): def __init__(self, *args, **kwargs):
4cf402558c084be208bbf0f4e682b2a06894738e
scikits/learn/datasets/__init__.py
scikits/learn/datasets/__init__.py
from base import load_diabetes from base import load_digits from base import load_files from base import load_iris from mlcomp import load_mlcomp
from .base import load_diabetes from .base import load_digits from .base import load_files from .base import load_iris from .mlcomp import load_mlcomp
Use relative imports in datasets.
Use relative imports in datasets.
Python
bsd-3-clause
shikhardb/scikit-learn,imaculate/scikit-learn,IndraVikas/scikit-learn,bhargav/scikit-learn,yonglehou/scikit-learn,q1ang/scikit-learn,yanlend/scikit-learn,pypot/scikit-learn,theoryno3/scikit-learn,lbishal/scikit-learn,466152112/scikit-learn,icdishb/scikit-learn,IshankGulati/scikit-learn,wazeerzulfikar/scikit-learn,spallavolu/scikit-learn,UNR-AERIAL/scikit-learn,jorge2703/scikit-learn,poryfly/scikit-learn,cainiaocome/scikit-learn,JsNoNo/scikit-learn,jm-begon/scikit-learn,rsivapr/scikit-learn,jm-begon/scikit-learn,mblondel/scikit-learn,rsivapr/scikit-learn,krez13/scikit-learn,fengzhyuan/scikit-learn,wlamond/scikit-learn,loli/sklearn-ensembletrees,manhhomienbienthuy/scikit-learn,ZENGXH/scikit-learn,ChanderG/scikit-learn,kmike/scikit-learn,Windy-Ground/scikit-learn,maheshakya/scikit-learn,JosmanPS/scikit-learn,arjoly/scikit-learn,ilyes14/scikit-learn,yunfeilu/scikit-learn,MohammedWasim/scikit-learn,joshloyal/scikit-learn,cybernet14/scikit-learn,bnaul/scikit-learn,treycausey/scikit-learn,mblondel/scikit-learn,shyamalschandra/scikit-learn,sgenoud/scikit-learn,wlamond/scikit-learn,Lawrence-Liu/scikit-learn,tosolveit/scikit-learn,jm-begon/scikit-learn,shikhardb/scikit-learn,CVML/scikit-learn,Srisai85/scikit-learn,arjoly/scikit-learn,JsNoNo/scikit-learn,kylerbrown/scikit-learn,466152112/scikit-learn,pratapvardhan/scikit-learn,idlead/scikit-learn,nomadcube/scikit-learn,Adai0808/scikit-learn,ilyes14/scikit-learn,shyamalschandra/scikit-learn,hlin117/scikit-learn,lbishal/scikit-learn,ngoix/OCRF,krez13/scikit-learn,MartinSavc/scikit-learn,Achuth17/scikit-learn,Vimos/scikit-learn,carrillo/scikit-learn,liangz0707/scikit-learn,cdegroc/scikit-learn,fredhusser/scikit-learn,lbishal/scikit-learn,bnaul/scikit-learn,equialgo/scikit-learn,bnaul/scikit-learn,glemaitre/scikit-learn,mrshu/scikit-learn,AlexRobson/scikit-learn,appapantula/scikit-learn,glouppe/scikit-learn,siutanwong/scikit-learn,shusenl/scikit-learn,ilo10/scikit-learn,xyguo/scikit-learn,mlyundin/scikit-learn,themrmax/scikit-learn,Jimmy-Morzaria/scikit-learn,Jimmy-Morzaria/scikit-learn,jakirkham/scikit-learn,fbagirov/scikit-learn,jmetzen/scikit-learn,AlexandreAbraham/scikit-learn,stylianos-kampakis/scikit-learn,evgchz/scikit-learn,TomDLT/scikit-learn,untom/scikit-learn,liberatorqjw/scikit-learn,anurag313/scikit-learn,jereze/scikit-learn,tdhopper/scikit-learn,hsiaoyi0504/scikit-learn,cainiaocome/scikit-learn,meduz/scikit-learn,kagayakidan/scikit-learn,Fireblend/scikit-learn,IssamLaradji/scikit-learn,appapantula/scikit-learn,mrshu/scikit-learn,trankmichael/scikit-learn,fredhusser/scikit-learn,schets/scikit-learn,russel1237/scikit-learn,khkaminska/scikit-learn,russel1237/scikit-learn,mhue/scikit-learn,deepesch/scikit-learn,vivekmishra1991/scikit-learn,jblackburne/scikit-learn,xzh86/scikit-learn,deepesch/scikit-learn,B3AU/waveTree,shyamalschandra/scikit-learn,ky822/scikit-learn,rsivapr/scikit-learn,mjudsp/Tsallis,vybstat/scikit-learn,mattilyra/scikit-learn,zuku1985/scikit-learn,fabioticconi/scikit-learn,lucidfrontier45/scikit-learn,jzt5132/scikit-learn,wazeerzulfikar/scikit-learn,ltiao/scikit-learn,kylerbrown/scikit-learn,Achuth17/scikit-learn,liyu1990/sklearn,fbagirov/scikit-learn,procoder317/scikit-learn,Sentient07/scikit-learn,shenzebang/scikit-learn,hlin117/scikit-learn,NelisVerhoef/scikit-learn,0x0all/scikit-learn,petosegan/scikit-learn,loli/sklearn-ensembletrees,evgchz/scikit-learn,xwolf12/scikit-learn,tmhm/scikit-learn,Aasmi/scikit-learn,beepee14/scikit-learn,MechCoder/scikit-learn,alexeyum/scikit-learn,xuewei4d/scikit-learn,arabenjamin/scikit-learn,ominux/scikit-learn,CVML/scikit-learn,mattgiguere/scikit-learn,glennq/scikit-learn,zorojean/scikit-learn,robbymeals/scikit-learn,xwolf12/scikit-learn,etkirsch/scikit-learn,zorroblue/scikit-learn,glouppe/scikit-learn,treycausey/scikit-learn,lin-credible/scikit-learn,Srisai85/scikit-learn,arjoly/scikit-learn,anirudhjayaraman/scikit-learn,mhue/scikit-learn,BiaDarkia/scikit-learn,madjelan/scikit-learn,kashif/scikit-learn,cwu2011/scikit-learn,smartscheduling/scikit-learn-categorical-tree,TomDLT/scikit-learn,ssaeger/scikit-learn,victorbergelin/scikit-learn,vigilv/scikit-learn,mattgiguere/scikit-learn,devanshdalal/scikit-learn,thientu/scikit-learn,idlead/scikit-learn,qifeigit/scikit-learn,huzq/scikit-learn,mattilyra/scikit-learn,Nyker510/scikit-learn,Obus/scikit-learn,fyffyt/scikit-learn,UNR-AERIAL/scikit-learn,abimannans/scikit-learn,DonBeo/scikit-learn,schets/scikit-learn,abhishekkrthakur/scikit-learn,akionakamura/scikit-learn,sergeyf/scikit-learn,RPGOne/scikit-learn,mjgrav2001/scikit-learn,RPGOne/scikit-learn,zorroblue/scikit-learn,kaichogami/scikit-learn,Garrett-R/scikit-learn,heli522/scikit-learn,f3r/scikit-learn,nesterione/scikit-learn,billy-inn/scikit-learn,MartinDelzant/scikit-learn,moutai/scikit-learn,vortex-ape/scikit-learn,aflaxman/scikit-learn,CforED/Machine-Learning,pratapvardhan/scikit-learn,harshaneelhg/scikit-learn,tosolveit/scikit-learn,jaidevd/scikit-learn,vinayak-mehta/scikit-learn,NelisVerhoef/scikit-learn,dsquareindia/scikit-learn,ltiao/scikit-learn,arahuja/scikit-learn,vybstat/scikit-learn,jaidevd/scikit-learn,Titan-C/scikit-learn,vortex-ape/scikit-learn,trankmichael/scikit-learn,thilbern/scikit-learn,bikong2/scikit-learn,Barmaley-exe/scikit-learn,sinhrks/scikit-learn,Myasuka/scikit-learn,AlexanderFabisch/scikit-learn,zuku1985/scikit-learn,kjung/scikit-learn,manashmndl/scikit-learn,LohithBlaze/scikit-learn,ominux/scikit-learn,potash/scikit-learn,trungnt13/scikit-learn,Achuth17/scikit-learn,simon-pepin/scikit-learn,ldirer/scikit-learn,devanshdalal/scikit-learn,pnedunuri/scikit-learn,carrillo/scikit-learn,ephes/scikit-learn,LiaoPan/scikit-learn,qifeigit/scikit-learn,rvraghav93/scikit-learn,wlamond/scikit-learn,mjudsp/Tsallis,MechCoder/scikit-learn,mattgiguere/scikit-learn,equialgo/scikit-learn,glemaitre/scikit-learn,sgenoud/scikit-learn,bhargav/scikit-learn,xiaoxiamii/scikit-learn,Aasmi/scikit-learn,mfjb/scikit-learn,luo66/scikit-learn,rishikksh20/scikit-learn,mhue/scikit-learn,olologin/scikit-learn,joernhees/scikit-learn,BiaDarkia/scikit-learn,RomainBrault/scikit-learn,Vimos/scikit-learn,vivekmishra1991/scikit-learn,lucidfrontier45/scikit-learn,shyamalschandra/scikit-learn,cl4rke/scikit-learn,xavierwu/scikit-learn,ishanic/scikit-learn,zorroblue/scikit-learn,ngoix/OCRF,Nyker510/scikit-learn,ndingwall/scikit-learn,aabadie/scikit-learn,djgagne/scikit-learn,RayMick/scikit-learn,CforED/Machine-Learning,xuewei4d/scikit-learn,RPGOne/scikit-learn,giorgiop/scikit-learn,nvoron23/scikit-learn,fabioticconi/scikit-learn,meduz/scikit-learn,liangz0707/scikit-learn,Fireblend/scikit-learn,ishanic/scikit-learn,DonBeo/scikit-learn,mfjb/scikit-learn,PatrickChrist/scikit-learn,aminert/scikit-learn,jpautom/scikit-learn,bigdataelephants/scikit-learn,HolgerPeters/scikit-learn,ZENGXH/scikit-learn,schets/scikit-learn,jseabold/scikit-learn,ssaeger/scikit-learn,tdhopper/scikit-learn,dhruv13J/scikit-learn,AlexanderFabisch/scikit-learn,ClimbsRocks/scikit-learn,mojoboss/scikit-learn,ilo10/scikit-learn,ivannz/scikit-learn,nrhine1/scikit-learn,terkkila/scikit-learn,gclenaghan/scikit-learn,rishikksh20/scikit-learn,tosolveit/scikit-learn,arabenjamin/scikit-learn,terkkila/scikit-learn,espg/scikit-learn,tomlof/scikit-learn,depet/scikit-learn,hdmetor/scikit-learn,abhishekgahlot/scikit-learn,ldirer/scikit-learn,lesteve/scikit-learn,hitszxp/scikit-learn,rvraghav93/scikit-learn,aewhatley/scikit-learn,fengzhyuan/scikit-learn,vinayak-mehta/scikit-learn,Adai0808/scikit-learn,zaxtax/scikit-learn,vivekmishra1991/scikit-learn,huobaowangxi/scikit-learn,ishanic/scikit-learn,zaxtax/scikit-learn,bigdataelephants/scikit-learn,ldirer/scikit-learn,cauchycui/scikit-learn,thilbern/scikit-learn,Titan-C/scikit-learn,andrewnc/scikit-learn,kagayakidan/scikit-learn,0x0all/scikit-learn,lenovor/scikit-learn,shusenl/scikit-learn,Djabbz/scikit-learn,yunfeilu/scikit-learn,nvoron23/scikit-learn,phdowling/scikit-learn,ndingwall/scikit-learn,cainiaocome/scikit-learn,shenzebang/scikit-learn,lucidfrontier45/scikit-learn,djgagne/scikit-learn,jzt5132/scikit-learn,jorik041/scikit-learn,JPFrancoia/scikit-learn,manashmndl/scikit-learn,cybernet14/scikit-learn,Windy-Ground/scikit-learn,mjgrav2001/scikit-learn,jmetzen/scikit-learn,loli/semisupervisedforests,abimannans/scikit-learn,pkruskal/scikit-learn,victorbergelin/scikit-learn,kaichogami/scikit-learn,ClimbsRocks/scikit-learn,jseabold/scikit-learn,YinongLong/scikit-learn,ycaihua/scikit-learn,betatim/scikit-learn,harshaneelhg/scikit-learn,pythonvietnam/scikit-learn,voxlol/scikit-learn,3manuek/scikit-learn,untom/scikit-learn,billy-inn/scikit-learn,qifeigit/scikit-learn,pythonvietnam/scikit-learn,rajat1994/scikit-learn,mayblue9/scikit-learn,lesteve/scikit-learn,herilalaina/scikit-learn,dsquareindia/scikit-learn,anurag313/scikit-learn,khkaminska/scikit-learn,djgagne/scikit-learn,jlegendary/scikit-learn,petosegan/scikit-learn,henrykironde/scikit-learn,RayMick/scikit-learn,hainm/scikit-learn,mxjl620/scikit-learn,sinhrks/scikit-learn,JPFrancoia/scikit-learn,ElDeveloper/scikit-learn,IndraVikas/scikit-learn,hlin117/scikit-learn,r-mart/scikit-learn,lazywei/scikit-learn,alexeyum/scikit-learn,JeanKossaifi/scikit-learn,yask123/scikit-learn,JeanKossaifi/scikit-learn,ycaihua/scikit-learn,potash/scikit-learn,evgchz/scikit-learn,elkingtonmcb/scikit-learn,ashhher3/scikit-learn,moutai/scikit-learn,nvoron23/scikit-learn,alexeyum/scikit-learn,jjx02230808/project0223,xavierwu/scikit-learn,RachitKansal/scikit-learn,pv/scikit-learn,zhenv5/scikit-learn,potash/scikit-learn,nelson-liu/scikit-learn,djgagne/scikit-learn,aewhatley/scikit-learn,xyguo/scikit-learn,3manuek/scikit-learn,jayflo/scikit-learn,beepee14/scikit-learn,espg/scikit-learn,lazywei/scikit-learn,PrashntS/scikit-learn,nikitasingh981/scikit-learn,potash/scikit-learn,liyu1990/sklearn,pianomania/scikit-learn,ivannz/scikit-learn,ngoix/OCRF,mfjb/scikit-learn,zorroblue/scikit-learn,themrmax/scikit-learn,ominux/scikit-learn,gotomypc/scikit-learn,icdishb/scikit-learn,wanggang3333/scikit-learn,kashif/scikit-learn,hrjn/scikit-learn,zihua/scikit-learn,elkingtonmcb/scikit-learn,rajat1994/scikit-learn,eg-zhang/scikit-learn,rahul-c1/scikit-learn,aflaxman/scikit-learn,MartinSavc/scikit-learn,nomadcube/scikit-learn,cybernet14/scikit-learn,depet/scikit-learn,ChanderG/scikit-learn,elkingtonmcb/scikit-learn,giorgiop/scikit-learn,marcocaccin/scikit-learn,altairpearl/scikit-learn,chrsrds/scikit-learn,giorgiop/scikit-learn,mugizico/scikit-learn,sergeyf/scikit-learn,wanggang3333/scikit-learn,anntzer/scikit-learn,giorgiop/scikit-learn,gotomypc/scikit-learn,0asa/scikit-learn,beepee14/scikit-learn,Adai0808/scikit-learn,wzbozon/scikit-learn,michigraber/scikit-learn,betatim/scikit-learn,UNR-AERIAL/scikit-learn,liberatorqjw/scikit-learn,heli522/scikit-learn,vibhorag/scikit-learn,ephes/scikit-learn,mattilyra/scikit-learn,belltailjp/scikit-learn,vermouthmjl/scikit-learn,spallavolu/scikit-learn,rexshihaoren/scikit-learn,theoryno3/scikit-learn,PatrickOReilly/scikit-learn,ankurankan/scikit-learn,OshynSong/scikit-learn,plissonf/scikit-learn,raghavrv/scikit-learn,Clyde-fare/scikit-learn,sarahgrogan/scikit-learn,IssamLaradji/scikit-learn,xavierwu/scikit-learn,ky822/scikit-learn,florian-f/sklearn,Garrett-R/scikit-learn,trungnt13/scikit-learn,fyffyt/scikit-learn,HolgerPeters/scikit-learn,florian-f/sklearn,hrjn/scikit-learn,eg-zhang/scikit-learn,xubenben/scikit-learn,untom/scikit-learn,xzh86/scikit-learn,eg-zhang/scikit-learn,huobaowangxi/scikit-learn,hdmetor/scikit-learn,alexsavio/scikit-learn,mwv/scikit-learn,Akshay0724/scikit-learn,aetilley/scikit-learn,frank-tancf/scikit-learn,pypot/scikit-learn,xubenben/scikit-learn,xubenben/scikit-learn,ashhher3/scikit-learn,roxyboy/scikit-learn,joshloyal/scikit-learn,alexeyum/scikit-learn,henridwyer/scikit-learn,ilo10/scikit-learn,Myasuka/scikit-learn,vigilv/scikit-learn,vermouthmjl/scikit-learn,pv/scikit-learn,rsivapr/scikit-learn,procoder317/scikit-learn,arahuja/scikit-learn,jorik041/scikit-learn,ndingwall/scikit-learn,huobaowangxi/scikit-learn,joshloyal/scikit-learn,rahuldhote/scikit-learn,tdhopper/scikit-learn,IshankGulati/scikit-learn,466152112/scikit-learn,q1ang/scikit-learn,ankurankan/scikit-learn,madjelan/scikit-learn,ky822/scikit-learn,gclenaghan/scikit-learn,manashmndl/scikit-learn,adamgreenhall/scikit-learn,MartinDelzant/scikit-learn,maheshakya/scikit-learn,IndraVikas/scikit-learn,CforED/Machine-Learning,kagayakidan/scikit-learn,shenzebang/scikit-learn,thientu/scikit-learn,kylerbrown/scikit-learn,quheng/scikit-learn,luo66/scikit-learn,vybstat/scikit-learn,madjelan/scikit-learn,kmike/scikit-learn,massmutual/scikit-learn,IssamLaradji/scikit-learn,devanshdalal/scikit-learn,shangwuhencc/scikit-learn,zorojean/scikit-learn,waterponey/scikit-learn,nomadcube/scikit-learn,shenzebang/scikit-learn,ankurankan/scikit-learn,h2educ/scikit-learn,justincassidy/scikit-learn,wazeerzulfikar/scikit-learn,anntzer/scikit-learn,scikit-learn/scikit-learn,elkingtonmcb/scikit-learn,Windy-Ground/scikit-learn,LiaoPan/scikit-learn,massmutual/scikit-learn,lesteve/scikit-learn,ChanChiChoi/scikit-learn,hainm/scikit-learn,fabianp/scikit-learn,kjung/scikit-learn,schets/scikit-learn,dingocuster/scikit-learn,andaag/scikit-learn,anurag313/scikit-learn,anirudhjayaraman/scikit-learn,zaxtax/scikit-learn,B3AU/waveTree,scikit-learn/scikit-learn,costypetrisor/scikit-learn,hugobowne/scikit-learn,q1ang/scikit-learn,shikhardb/scikit-learn,MohammedWasim/scikit-learn,jblackburne/scikit-learn,eickenberg/scikit-learn,chrisburr/scikit-learn,B3AU/waveTree,abhishekgahlot/scikit-learn,arjoly/scikit-learn,luo66/scikit-learn,rrohan/scikit-learn,xyguo/scikit-learn,mehdidc/scikit-learn,ycaihua/scikit-learn,theoryno3/scikit-learn,ningchi/scikit-learn,nhejazi/scikit-learn,iismd17/scikit-learn,smartscheduling/scikit-learn-categorical-tree,manhhomienbienthuy/scikit-learn,jakobworldpeace/scikit-learn,rvraghav93/scikit-learn,walterreade/scikit-learn,ogrisel/scikit-learn,florian-f/sklearn,IshankGulati/scikit-learn,mojoboss/scikit-learn,murali-munna/scikit-learn,chrisburr/scikit-learn,kjung/scikit-learn,rahul-c1/scikit-learn,chrisburr/scikit-learn,Lawrence-Liu/scikit-learn,tawsifkhan/scikit-learn,dsullivan7/scikit-learn,toastedcornflakes/scikit-learn,maheshakya/scikit-learn,walterreade/scikit-learn,abhishekkrthakur/scikit-learn,chrsrds/scikit-learn,xuewei4d/scikit-learn,rrohan/scikit-learn,andrewnc/scikit-learn,liyu1990/sklearn,JsNoNo/scikit-learn,Aasmi/scikit-learn,sergeyf/scikit-learn,untom/scikit-learn,yunfeilu/scikit-learn,nikitasingh981/scikit-learn,fabianp/scikit-learn,jjx02230808/project0223,mattilyra/scikit-learn,vibhorag/scikit-learn,RomainBrault/scikit-learn,abhishekkrthakur/scikit-learn,LohithBlaze/scikit-learn,jblackburne/scikit-learn,depet/scikit-learn,xuewei4d/scikit-learn,huzq/scikit-learn,yonglehou/scikit-learn,alvarofierroclavero/scikit-learn,RayMick/scikit-learn,lbishal/scikit-learn,chrisburr/scikit-learn,treycausey/scikit-learn,victorbergelin/scikit-learn,bhargav/scikit-learn,appapantula/scikit-learn,ningchi/scikit-learn,evgchz/scikit-learn,Clyde-fare/scikit-learn,wzbozon/scikit-learn,ephes/scikit-learn,JPFrancoia/scikit-learn,ldirer/scikit-learn,nmayorov/scikit-learn,aabadie/scikit-learn,ephes/scikit-learn,mojoboss/scikit-learn,shangwuhencc/scikit-learn,sonnyhu/scikit-learn,raghavrv/scikit-learn,robbymeals/scikit-learn,hitszxp/scikit-learn,hugobowne/scikit-learn,TomDLT/scikit-learn,sonnyhu/scikit-learn,jkarnows/scikit-learn,heli522/scikit-learn,shahankhatch/scikit-learn,stylianos-kampakis/scikit-learn,AnasGhrab/scikit-learn,samuel1208/scikit-learn,Vimos/scikit-learn,h2educ/scikit-learn,akionakamura/scikit-learn,samuel1208/scikit-learn,glouppe/scikit-learn,fbagirov/scikit-learn,0asa/scikit-learn,NunoEdgarGub1/scikit-learn,espg/scikit-learn,wazeerzulfikar/scikit-learn,cainiaocome/scikit-learn,nikitasingh981/scikit-learn,RomainBrault/scikit-learn,pratapvardhan/scikit-learn,CforED/Machine-Learning,kylerbrown/scikit-learn,billy-inn/scikit-learn,justincassidy/scikit-learn,sanketloke/scikit-learn,btabibian/scikit-learn,ltiao/scikit-learn,jkarnows/scikit-learn,ycaihua/scikit-learn,ankurankan/scikit-learn,mehdidc/scikit-learn,bigdataelephants/scikit-learn,rahul-c1/scikit-learn,phdowling/scikit-learn,mxjl620/scikit-learn,PrashntS/scikit-learn,henrykironde/scikit-learn,ogrisel/scikit-learn,simon-pepin/scikit-learn,hsuantien/scikit-learn,quheng/scikit-learn,ogrisel/scikit-learn,loli/sklearn-ensembletrees,akionakamura/scikit-learn,jlegendary/scikit-learn,vshtanko/scikit-learn,fzalkow/scikit-learn,ilo10/scikit-learn,ycaihua/scikit-learn,sinhrks/scikit-learn,smartscheduling/scikit-learn-categorical-tree,ChanChiChoi/scikit-learn,wlamond/scikit-learn,zhenv5/scikit-learn,RachitKansal/scikit-learn,adamgreenhall/scikit-learn,eickenberg/scikit-learn,AIML/scikit-learn,Titan-C/scikit-learn,davidgbe/scikit-learn,procoder317/scikit-learn,ClimbsRocks/scikit-learn,harshaneelhg/scikit-learn,samzhang111/scikit-learn,rohanp/scikit-learn,DonBeo/scikit-learn,jakirkham/scikit-learn,PrashntS/scikit-learn,idlead/scikit-learn,cdegroc/scikit-learn,jpautom/scikit-learn,AIML/scikit-learn,huzq/scikit-learn,thilbern/scikit-learn,fengzhyuan/scikit-learn,gotomypc/scikit-learn,alvarofierroclavero/scikit-learn,andaag/scikit-learn,hsiaoyi0504/scikit-learn,Srisai85/scikit-learn,massmutual/scikit-learn,zuku1985/scikit-learn,harshaneelhg/scikit-learn,mjudsp/Tsallis,zorojean/scikit-learn,AlexanderFabisch/scikit-learn,mjgrav2001/scikit-learn,kevin-intel/scikit-learn,poryfly/scikit-learn,eickenberg/scikit-learn,sergeyf/scikit-learn,nelson-liu/scikit-learn,spallavolu/scikit-learn,rohanp/scikit-learn,ky822/scikit-learn,btabibian/scikit-learn,ChanChiChoi/scikit-learn,UNR-AERIAL/scikit-learn,h2educ/scikit-learn,PatrickOReilly/scikit-learn,lazywei/scikit-learn,ngoix/OCRF,mehdidc/scikit-learn,Garrett-R/scikit-learn,xzh86/scikit-learn,jorik041/scikit-learn,Achuth17/scikit-learn,arabenjamin/scikit-learn,aewhatley/scikit-learn,jorik041/scikit-learn,jayflo/scikit-learn,0x0all/scikit-learn,olologin/scikit-learn,glouppe/scikit-learn,r-mart/scikit-learn,MatthieuBizien/scikit-learn,pv/scikit-learn,ssaeger/scikit-learn,RachitKansal/scikit-learn,loli/sklearn-ensembletrees,tomlof/scikit-learn,mattilyra/scikit-learn,Myasuka/scikit-learn,zhenv5/scikit-learn,ZENGXH/scikit-learn,MechCoder/scikit-learn,BiaDarkia/scikit-learn,treycausey/scikit-learn,ahoyosid/scikit-learn,jseabold/scikit-learn,aetilley/scikit-learn,DonBeo/scikit-learn,massmutual/scikit-learn,abhishekgahlot/scikit-learn,mojoboss/scikit-learn,kmike/scikit-learn,zhenv5/scikit-learn,saiwing-yeung/scikit-learn,wanggang3333/scikit-learn,pythonvietnam/scikit-learn,vermouthmjl/scikit-learn,dhruv13J/scikit-learn,466152112/scikit-learn,mwv/scikit-learn,deepesch/scikit-learn,ZenDevelopmentSystems/scikit-learn,shahankhatch/scikit-learn,altairpearl/scikit-learn,arahuja/scikit-learn,herilalaina/scikit-learn,michigraber/scikit-learn,gotomypc/scikit-learn,PatrickChrist/scikit-learn,jmschrei/scikit-learn,belltailjp/scikit-learn,cdegroc/scikit-learn,MatthieuBizien/scikit-learn,amueller/scikit-learn,Myasuka/scikit-learn,depet/scikit-learn,vinayak-mehta/scikit-learn,iismd17/scikit-learn,pianomania/scikit-learn,billy-inn/scikit-learn,mhdella/scikit-learn,depet/scikit-learn,jorge2703/scikit-learn,davidgbe/scikit-learn,samzhang111/scikit-learn,costypetrisor/scikit-learn,iismd17/scikit-learn,Jimmy-Morzaria/scikit-learn,marcocaccin/scikit-learn,PatrickOReilly/scikit-learn,fredhusser/scikit-learn,Akshay0724/scikit-learn,pompiduskus/scikit-learn,AlexRobson/scikit-learn,yyjiang/scikit-learn,trungnt13/scikit-learn,nrhine1/scikit-learn,kagayakidan/scikit-learn,lin-credible/scikit-learn,costypetrisor/scikit-learn,AlexanderFabisch/scikit-learn,jzt5132/scikit-learn,Sentient07/scikit-learn,HolgerPeters/scikit-learn,nikitasingh981/scikit-learn,f3r/scikit-learn,mugizico/scikit-learn,cl4rke/scikit-learn,shusenl/scikit-learn,amueller/scikit-learn,pkruskal/scikit-learn,marcocaccin/scikit-learn,moutai/scikit-learn,jm-begon/scikit-learn,sumspr/scikit-learn,abimannans/scikit-learn,dsullivan7/scikit-learn,larsmans/scikit-learn,samuel1208/scikit-learn,jereze/scikit-learn,chrsrds/scikit-learn,liangz0707/scikit-learn,fzalkow/scikit-learn,sonnyhu/scikit-learn,jakirkham/scikit-learn,alvarofierroclavero/scikit-learn,ahoyosid/scikit-learn,MohammedWasim/scikit-learn,dhruv13J/scikit-learn,icdishb/scikit-learn,iismd17/scikit-learn,tosolveit/scikit-learn,0asa/scikit-learn,macks22/scikit-learn,ZenDevelopmentSystems/scikit-learn,Obus/scikit-learn,jakobworldpeace/scikit-learn,fengzhyuan/scikit-learn,kashif/scikit-learn,NelisVerhoef/scikit-learn,ishanic/scikit-learn,amueller/scikit-learn,etkirsch/scikit-learn,shangwuhencc/scikit-learn,nhejazi/scikit-learn,ClimbsRocks/scikit-learn,YinongLong/scikit-learn,marcocaccin/scikit-learn,mikebenfield/scikit-learn,JeanKossaifi/scikit-learn,vibhorag/scikit-learn,jkarnows/scikit-learn,ElDeveloper/scikit-learn,waterponey/scikit-learn,fzalkow/scikit-learn,betatim/scikit-learn,cl4rke/scikit-learn,andrewnc/scikit-learn,vybstat/scikit-learn,robbymeals/scikit-learn,nrhine1/scikit-learn,nrhine1/scikit-learn,samzhang111/scikit-learn,jzt5132/scikit-learn,nhejazi/scikit-learn,alexsavio/scikit-learn,chrsrds/scikit-learn,rahul-c1/scikit-learn,altairpearl/scikit-learn,hsiaoyi0504/scikit-learn,tomlof/scikit-learn,alexsavio/scikit-learn,tawsifkhan/scikit-learn,mjgrav2001/scikit-learn,glennq/scikit-learn,carrillo/scikit-learn,sgenoud/scikit-learn,procoder317/scikit-learn,MechCoder/scikit-learn,kevin-intel/scikit-learn,ZenDevelopmentSystems/scikit-learn,wzbozon/scikit-learn,nmayorov/scikit-learn,DSLituiev/scikit-learn,vortex-ape/scikit-learn,sonnyhu/scikit-learn,imaculate/scikit-learn,belltailjp/scikit-learn,ChanChiChoi/scikit-learn,jpautom/scikit-learn,davidgbe/scikit-learn,mwv/scikit-learn,maheshakya/scikit-learn,shikhardb/scikit-learn,hrjn/scikit-learn,xiaoxiamii/scikit-learn,amueller/scikit-learn,russel1237/scikit-learn,petosegan/scikit-learn,NunoEdgarGub1/scikit-learn,PatrickChrist/scikit-learn,rsivapr/scikit-learn,victorbergelin/scikit-learn,stylianos-kampakis/scikit-learn,waterponey/scikit-learn,sarahgrogan/scikit-learn,moutai/scikit-learn,liangz0707/scikit-learn,espg/scikit-learn,cwu2011/scikit-learn,khkaminska/scikit-learn,Garrett-R/scikit-learn,frank-tancf/scikit-learn,AIML/scikit-learn,clemkoa/scikit-learn,appapantula/scikit-learn,ssaeger/scikit-learn,hainm/scikit-learn,fzalkow/scikit-learn,kashif/scikit-learn,plissonf/scikit-learn,Fireblend/scikit-learn,macks22/scikit-learn,Nyker510/scikit-learn,Barmaley-exe/scikit-learn,mayblue9/scikit-learn,yanlend/scikit-learn,hdmetor/scikit-learn,pnedunuri/scikit-learn,jpautom/scikit-learn,treycausey/scikit-learn,robin-lai/scikit-learn,PatrickOReilly/scikit-learn,jseabold/scikit-learn,ningchi/scikit-learn,cauchycui/scikit-learn,kmike/scikit-learn,costypetrisor/scikit-learn,CVML/scikit-learn,simon-pepin/scikit-learn,saiwing-yeung/scikit-learn,ahoyosid/scikit-learn,altairpearl/scikit-learn,krez13/scikit-learn,dsullivan7/scikit-learn,waterponey/scikit-learn,TomDLT/scikit-learn,tomlof/scikit-learn,pnedunuri/scikit-learn,lin-credible/scikit-learn,mhue/scikit-learn,tmhm/scikit-learn,hsiaoyi0504/scikit-learn,nomadcube/scikit-learn,smartscheduling/scikit-learn-categorical-tree,voxlol/scikit-learn,kevin-intel/scikit-learn,sanketloke/scikit-learn,MartinSavc/scikit-learn,mxjl620/scikit-learn,ilyes14/scikit-learn,lucidfrontier45/scikit-learn,MohammedWasim/scikit-learn,huobaowangxi/scikit-learn,HolgerPeters/scikit-learn,vortex-ape/scikit-learn,pianomania/scikit-learn,anirudhjayaraman/scikit-learn,jereze/scikit-learn,Akshay0724/scikit-learn,luo66/scikit-learn,ngoix/OCRF,liyu1990/sklearn,rishikksh20/scikit-learn,alvarofierroclavero/scikit-learn,yyjiang/scikit-learn,manashmndl/scikit-learn,larsmans/scikit-learn,MatthieuBizien/scikit-learn,robin-lai/scikit-learn,henrykironde/scikit-learn,olologin/scikit-learn,mxjl620/scikit-learn,ivannz/scikit-learn,tmhm/scikit-learn,rohanp/scikit-learn,mikebenfield/scikit-learn,huzq/scikit-learn,saiwing-yeung/scikit-learn,rvraghav93/scikit-learn,manhhomienbienthuy/scikit-learn,Djabbz/scikit-learn,pypot/scikit-learn,Obus/scikit-learn,pkruskal/scikit-learn,hrjn/scikit-learn,kevin-intel/scikit-learn,murali-munna/scikit-learn,rahuldhote/scikit-learn,jaidevd/scikit-learn,nmayorov/scikit-learn,bthirion/scikit-learn,f3r/scikit-learn,jorge2703/scikit-learn,MartinSavc/scikit-learn,cl4rke/scikit-learn,imaculate/scikit-learn,imaculate/scikit-learn,frank-tancf/scikit-learn,vshtanko/scikit-learn,siutanwong/scikit-learn,larsmans/scikit-learn,bthirion/scikit-learn,fabioticconi/scikit-learn,jlegendary/scikit-learn,qifeigit/scikit-learn,YinongLong/scikit-learn,mattgiguere/scikit-learn,vigilv/scikit-learn,rexshihaoren/scikit-learn,ominux/scikit-learn,Aasmi/scikit-learn,hitszxp/scikit-learn,DSLituiev/scikit-learn,glemaitre/scikit-learn,jayflo/scikit-learn,murali-munna/scikit-learn,Lawrence-Liu/scikit-learn,IssamLaradji/scikit-learn,OshynSong/scikit-learn,rahuldhote/scikit-learn,hsuantien/scikit-learn,herilalaina/scikit-learn,michigraber/scikit-learn,mlyundin/scikit-learn,shangwuhencc/scikit-learn,maheshakya/scikit-learn,nvoron23/scikit-learn,zorojean/scikit-learn,ashhher3/scikit-learn,roxyboy/scikit-learn,mehdidc/scikit-learn,toastedcornflakes/scikit-learn,xyguo/scikit-learn,dsullivan7/scikit-learn,yunfeilu/scikit-learn,jakobworldpeace/scikit-learn,RomainBrault/scikit-learn,abhishekkrthakur/scikit-learn,RachitKansal/scikit-learn,aflaxman/scikit-learn,arahuja/scikit-learn,jmetzen/scikit-learn,sarahgrogan/scikit-learn,pypot/scikit-learn,florian-f/sklearn,3manuek/scikit-learn,mrshu/scikit-learn,pv/scikit-learn,Jimmy-Morzaria/scikit-learn,murali-munna/scikit-learn,lazywei/scikit-learn,ashhher3/scikit-learn,andrewnc/scikit-learn,mlyundin/scikit-learn,AIML/scikit-learn,dsquareindia/scikit-learn,loli/semisupervisedforests,ogrisel/scikit-learn,jjx02230808/project0223,gclenaghan/scikit-learn,adamgreenhall/scikit-learn,spallavolu/scikit-learn,r-mart/scikit-learn,vivekmishra1991/scikit-learn,YinongLong/scikit-learn,sanketloke/scikit-learn,yyjiang/scikit-learn,glennq/scikit-learn,vshtanko/scikit-learn,rexshihaoren/scikit-learn,tdhopper/scikit-learn,andaag/scikit-learn,thilbern/scikit-learn,pompiduskus/scikit-learn,sumspr/scikit-learn,q1ang/scikit-learn,Adai0808/scikit-learn,cwu2011/scikit-learn,raghavrv/scikit-learn,mugizico/scikit-learn,liberatorqjw/scikit-learn,hugobowne/scikit-learn,idlead/scikit-learn,fabioticconi/scikit-learn,voxlol/scikit-learn,jblackburne/scikit-learn,DSLituiev/scikit-learn,joshloyal/scikit-learn,etkirsch/scikit-learn,ZenDevelopmentSystems/scikit-learn,robbymeals/scikit-learn,aminert/scikit-learn,bikong2/scikit-learn,cdegroc/scikit-learn,mhdella/scikit-learn,MatthieuBizien/scikit-learn,shusenl/scikit-learn,mayblue9/scikit-learn,rexshihaoren/scikit-learn,raghavrv/scikit-learn,abhishekgahlot/scikit-learn,henridwyer/scikit-learn,larsmans/scikit-learn,xavierwu/scikit-learn,IshankGulati/scikit-learn,ZENGXH/scikit-learn,LohithBlaze/scikit-learn,ningchi/scikit-learn,justincassidy/scikit-learn,AlexandreAbraham/scikit-learn,xwolf12/scikit-learn,plissonf/scikit-learn,NunoEdgarGub1/scikit-learn,fyffyt/scikit-learn,rishikksh20/scikit-learn,JsNoNo/scikit-learn,Djabbz/scikit-learn,nhejazi/scikit-learn,pompiduskus/scikit-learn,jaidevd/scikit-learn,sgenoud/scikit-learn,akionakamura/scikit-learn,IndraVikas/scikit-learn,meduz/scikit-learn,0asa/scikit-learn,gclenaghan/scikit-learn,terkkila/scikit-learn,michigraber/scikit-learn,russel1237/scikit-learn,davidgbe/scikit-learn,pratapvardhan/scikit-learn,jayflo/scikit-learn,jmschrei/scikit-learn,bhargav/scikit-learn,ivannz/scikit-learn,Barmaley-exe/scikit-learn,wzbozon/scikit-learn,frank-tancf/scikit-learn,nesterione/scikit-learn,bthirion/scikit-learn,phdowling/scikit-learn,hitszxp/scikit-learn,fabianp/scikit-learn,lin-credible/scikit-learn,sumspr/scikit-learn,vibhorag/scikit-learn,Nyker510/scikit-learn,siutanwong/scikit-learn,deepesch/scikit-learn,AnasGhrab/scikit-learn,vigilv/scikit-learn,terkkila/scikit-learn,pianomania/scikit-learn,dsquareindia/scikit-learn,bthirion/scikit-learn,pkruskal/scikit-learn,aetilley/scikit-learn,jmetzen/scikit-learn,tawsifkhan/scikit-learn,anirudhjayaraman/scikit-learn,yanlend/scikit-learn,wanggang3333/scikit-learn,trungnt13/scikit-learn,jereze/scikit-learn,JPFrancoia/scikit-learn,rrohan/scikit-learn,tawsifkhan/scikit-learn,Djabbz/scikit-learn,mfjb/scikit-learn,andaag/scikit-learn,Lawrence-Liu/scikit-learn,fredhusser/scikit-learn,saiwing-yeung/scikit-learn,henrykironde/scikit-learn,kjung/scikit-learn,theoryno3/scikit-learn,yask123/scikit-learn,petosegan/scikit-learn,dhruv13J/scikit-learn,hainm/scikit-learn,jjx02230808/project0223,AlexRobson/scikit-learn,ngoix/OCRF,belltailjp/scikit-learn,ahoyosid/scikit-learn,ilyes14/scikit-learn,trankmichael/scikit-learn,kmike/scikit-learn,mikebenfield/scikit-learn,xiaoxiamii/scikit-learn,macks22/scikit-learn,JeanKossaifi/scikit-learn,roxyboy/scikit-learn,bnaul/scikit-learn,Clyde-fare/scikit-learn,equialgo/scikit-learn,vshtanko/scikit-learn,mhdella/scikit-learn,sarahgrogan/scikit-learn,NelisVerhoef/scikit-learn,ElDeveloper/scikit-learn,walterreade/scikit-learn,bikong2/scikit-learn,jkarnows/scikit-learn,nelson-liu/scikit-learn,aabadie/scikit-learn,heli522/scikit-learn,mrshu/scikit-learn,xwolf12/scikit-learn,Fireblend/scikit-learn,dingocuster/scikit-learn,scikit-learn/scikit-learn,krez13/scikit-learn,loli/semisupervisedforests,abhishekgahlot/scikit-learn,ltiao/scikit-learn,CVML/scikit-learn,sinhrks/scikit-learn,lenovor/scikit-learn,florian-f/sklearn,nelson-liu/scikit-learn,poryfly/scikit-learn,LiaoPan/scikit-learn,btabibian/scikit-learn,carrillo/scikit-learn,dingocuster/scikit-learn,3manuek/scikit-learn,rahuldhote/scikit-learn,DSLituiev/scikit-learn,lenovor/scikit-learn,devanshdalal/scikit-learn,Sentient07/scikit-learn,rajat1994/scikit-learn,hitszxp/scikit-learn,khkaminska/scikit-learn,NunoEdgarGub1/scikit-learn,bigdataelephants/scikit-learn,samuel1208/scikit-learn,mayblue9/scikit-learn,nesterione/scikit-learn,lesteve/scikit-learn,zihua/scikit-learn,phdowling/scikit-learn,r-mart/scikit-learn,RPGOne/scikit-learn,xiaoxiamii/scikit-learn,jmschrei/scikit-learn,mjudsp/Tsallis,OshynSong/scikit-learn,samzhang111/scikit-learn,MartinDelzant/scikit-learn,voxlol/scikit-learn,zaxtax/scikit-learn,sumspr/scikit-learn,yask123/scikit-learn,PrashntS/scikit-learn,kaichogami/scikit-learn,AnasGhrab/scikit-learn,zihua/scikit-learn,meduz/scikit-learn,vinayak-mehta/scikit-learn,ankurankan/scikit-learn,cauchycui/scikit-learn,B3AU/waveTree,anntzer/scikit-learn,zihua/scikit-learn,MartinDelzant/scikit-learn,abimannans/scikit-learn,jorge2703/scikit-learn,vermouthmjl/scikit-learn,stylianos-kampakis/scikit-learn,B3AU/waveTree,scikit-learn/scikit-learn,herilalaina/scikit-learn,Vimos/scikit-learn,etkirsch/scikit-learn,toastedcornflakes/scikit-learn,AlexandreAbraham/scikit-learn,zuku1985/scikit-learn,themrmax/scikit-learn,joernhees/scikit-learn,siutanwong/scikit-learn,loli/semisupervisedforests,hdmetor/scikit-learn,fbagirov/scikit-learn,robin-lai/scikit-learn,clemkoa/scikit-learn,pnedunuri/scikit-learn,ndingwall/scikit-learn,0asa/scikit-learn,anntzer/scikit-learn,hugobowne/scikit-learn,cauchycui/scikit-learn,yonglehou/scikit-learn,alexsavio/scikit-learn,eickenberg/scikit-learn,justincassidy/scikit-learn,mlyundin/scikit-learn,mblondel/scikit-learn,pompiduskus/scikit-learn,hsuantien/scikit-learn,jmschrei/scikit-learn,LohithBlaze/scikit-learn,nesterione/scikit-learn,cybernet14/scikit-learn,lucidfrontier45/scikit-learn,OshynSong/scikit-learn,ElDeveloper/scikit-learn,yask123/scikit-learn,BiaDarkia/scikit-learn,fabianp/scikit-learn,mhdella/scikit-learn,tmhm/scikit-learn,henridwyer/scikit-learn,olologin/scikit-learn,fyffyt/scikit-learn,sgenoud/scikit-learn,aewhatley/scikit-learn,LiaoPan/scikit-learn,Titan-C/scikit-learn,bikong2/scikit-learn,JosmanPS/scikit-learn,aetilley/scikit-learn,btabibian/scikit-learn,shahankhatch/scikit-learn,f3r/scikit-learn,pythonvietnam/scikit-learn,quheng/scikit-learn,JosmanPS/scikit-learn,clemkoa/scikit-learn,rrohan/scikit-learn,0x0all/scikit-learn,mikebenfield/scikit-learn,Srisai85/scikit-learn,eg-zhang/scikit-learn,macks22/scikit-learn,Obus/scikit-learn,sanketloke/scikit-learn,themrmax/scikit-learn,yanlend/scikit-learn,ChanderG/scikit-learn,nmayorov/scikit-learn,joernhees/scikit-learn,RayMick/scikit-learn,manhhomienbienthuy/scikit-learn,JosmanPS/scikit-learn,larsmans/scikit-learn,equialgo/scikit-learn,Akshay0724/scikit-learn,rajat1994/scikit-learn,Clyde-fare/scikit-learn,mjudsp/Tsallis,jlegendary/scikit-learn,glemaitre/scikit-learn,icdishb/scikit-learn,AlexRobson/scikit-learn,clemkoa/scikit-learn,Windy-Ground/scikit-learn,beepee14/scikit-learn,AnasGhrab/scikit-learn,walterreade/scikit-learn,yonglehou/scikit-learn,mugizico/scikit-learn,liberatorqjw/scikit-learn,roxyboy/scikit-learn,eickenberg/scikit-learn,PatrickChrist/scikit-learn,thientu/scikit-learn,rohanp/scikit-learn,evgchz/scikit-learn,aabadie/scikit-learn,glennq/scikit-learn,arabenjamin/scikit-learn,aminert/scikit-learn,Sentient07/scikit-learn,aflaxman/scikit-learn,thientu/scikit-learn,Barmaley-exe/scikit-learn,loli/sklearn-ensembletrees,mrshu/scikit-learn,madjelan/scikit-learn,plissonf/scikit-learn,0x0all/scikit-learn,hsuantien/scikit-learn,joernhees/scikit-learn,adamgreenhall/scikit-learn,cwu2011/scikit-learn,xzh86/scikit-learn,henridwyer/scikit-learn,xubenben/scikit-learn,shahankhatch/scikit-learn,betatim/scikit-learn,simon-pepin/scikit-learn,trankmichael/scikit-learn,hlin117/scikit-learn,kaichogami/scikit-learn,yyjiang/scikit-learn,poryfly/scikit-learn,dingocuster/scikit-learn,jakobworldpeace/scikit-learn,quheng/scikit-learn,mwv/scikit-learn,aminert/scikit-learn,lenovor/scikit-learn,jakirkham/scikit-learn,Garrett-R/scikit-learn,robin-lai/scikit-learn,anurag313/scikit-learn,AlexandreAbraham/scikit-learn,h2educ/scikit-learn,toastedcornflakes/scikit-learn,mblondel/scikit-learn,ChanderG/scikit-learn
--- +++ @@ -1,5 +1,5 @@ -from base import load_diabetes -from base import load_digits -from base import load_files -from base import load_iris -from mlcomp import load_mlcomp +from .base import load_diabetes +from .base import load_digits +from .base import load_files +from .base import load_iris +from .mlcomp import load_mlcomp
634d645f949f7dbff8c4e9300eebe01158649a83
datafilters/views.py
datafilters/views.py
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and get_context_data(self, **kwargs) method. """ filter_form_cls = None use_filter_chaining = False context_filterform_name = 'filterform' def get_filter(self): return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): qs = super(FilterFormMixin, self).get_queryset() filter_form = self.get_filter() if filter_form.is_valid(): qs = filter_form.filter(qs).distinct() return qs def get_context_data(self, **kwargs): context = super(FilterFormMixin, self).get_context_data(**kwargs) context[self.context_filterform_name] = self.get_filter() return context def get_runtime_context(self): return {'user': self.request.user}
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. """ filter_form_cls = None use_filter_chaining = False context_filterform_name = 'filterform' def get_filter(self): """ Get FilterForm instance. """ return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): """ Return queryset with filtering applied (if filter form passes validation). """ qs = super(FilterFormMixin, self).get_queryset() filter_form = self.get_filter() if filter_form.is_valid(): qs = filter_form.filter(qs).distinct() return qs def get_context_data(self, **kwargs): """ Add filter form to the context. TODO: Currently we construct the filter form object twice - in get_queryset and here, in get_context_data. Will need to figure out a good way to eliminate extra initialization. """ context = super(FilterFormMixin, self).get_context_data(**kwargs) context[self.context_filterform_name] = self.get_filter() return context def get_runtime_context(self): """ Get context for filter form to allow passing runtime information, such as user, cookies, etc. Method might be overriden by implementation and context returned by this method will be accessible in to_lookup() method implementation of FilterSpec. """ return {'user': self.request.user}
Add docstrings to the view mixin
Add docstrings to the view mixin
Python
mit
zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters
--- +++ @@ -6,19 +6,24 @@ class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. - Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and - get_context_data(self, **kwargs) method. """ filter_form_cls = None use_filter_chaining = False context_filterform_name = 'filterform' def get_filter(self): + """ + Get FilterForm instance. + """ return self.filter_form_cls(self.request.GET, runtime_context=self.get_runtime_context(), use_filter_chaining=self.use_filter_chaining) def get_queryset(self): + """ + Return queryset with filtering applied (if filter form passes + validation). + """ qs = super(FilterFormMixin, self).get_queryset() filter_form = self.get_filter() if filter_form.is_valid(): @@ -26,9 +31,24 @@ return qs def get_context_data(self, **kwargs): + """ + Add filter form to the context. + + TODO: Currently we construct the filter form object twice - in + get_queryset and here, in get_context_data. Will need to figure out a + good way to eliminate extra initialization. + """ context = super(FilterFormMixin, self).get_context_data(**kwargs) context[self.context_filterform_name] = self.get_filter() return context def get_runtime_context(self): + """ + Get context for filter form to allow passing runtime information, + such as user, cookies, etc. + + Method might be overriden by implementation and context returned by + this method will be accessible in to_lookup() method implementation + of FilterSpec. + """ return {'user': self.request.user}
4b127103d8bea8e9dc9793e92abee9f7a111a018
doc/Manual/config.py
doc/Manual/config.py
from Synopsis.Config import Base class Config (Base): class Formatter (Base.Formatter): class HTML (Base.Formatter.HTML): toc_output = 'links.toc' pages = [ 'ScopePages', 'ModuleListingJS', 'ModuleIndexer', 'FileTreeJS', 'InheritanceTree', 'InheritanceGraph', 'NameIndex', 'FilePages', 'FramesIndex' ] class FilePages: "Override defaults" file_path = '../../../%s' links_path = 'syn/%s-links' toc_files = ['links.toc'] class FileTree: link_to_pages = 1 class ScopePages (Base.Formatter.HTML.ScopePages): summary_formatters = [ ('Synopsis.Formatter.HTML.ASTFormatter','SummaryASTFormatter'), ('Synopsis.Formatter.HTML.ASTFormatter','SummaryASTCommenter'), ('Synopsis.Formatter.HTML.ASTFormatter','FilePageLinker'), ] modules = {'HTML':HTML}
from Synopsis.Config import Base class Config (Base): class Formatter (Base.Formatter): class HTML (Base.Formatter.HTML): toc_output = 'links.toc' pages = [ 'ScopePages', 'ModuleListingJS', 'ModuleIndexer', 'FileTreeJS', 'InheritanceTree', 'InheritanceGraph', 'NameIndex', 'FilePages', ('modules.py', 'ConfScopeJS'), 'FramesIndex' ] synopsis_pages = pages # Add custom comment formatter comment_formatters = [ 'summary', 'javadoc', 'section', ('modules.py', 'RefCommentFormatter') ] # Also use it when either style is specified: synopsis_comment_formatters = comment_formatters doxygen_comment_formatters = comment_formatters class FilePages: "Override defaults" file_path = '../../../%s' links_path = 'syn/%s-links' toc_files = ['links.toc'] class FileTree: link_to_pages = 1 class ScopePages (Base.Formatter.HTML.ScopePages): summary_formatters = [ ('Synopsis.Formatter.HTML.ASTFormatter','SummaryASTFormatter'), ('Synopsis.Formatter.HTML.ASTFormatter','SummaryASTCommenter'), ('Synopsis.Formatter.HTML.ASTFormatter','FilePageLinker'), ] class ConfigHTML (HTML): pages = [ ('modules.py', 'ConfScopeJS'), ('modules.py', 'ConfScopePage') ] synopsis_pages = pages modules = { 'HTML':HTML, 'ConfigHTML':ConfigHTML }
Use custom modules in modules.py
Use custom modules in modules.py
Python
lgpl-2.1
stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis,stefanseefeld/synopsis
--- +++ @@ -12,8 +12,19 @@ 'InheritanceGraph', 'NameIndex', 'FilePages', + ('modules.py', 'ConfScopeJS'), 'FramesIndex' ] + synopsis_pages = pages + + # Add custom comment formatter + comment_formatters = [ + 'summary', 'javadoc', 'section', + ('modules.py', 'RefCommentFormatter') + ] + # Also use it when either style is specified: + synopsis_comment_formatters = comment_formatters + doxygen_comment_formatters = comment_formatters class FilePages: "Override defaults" @@ -28,4 +39,13 @@ ('Synopsis.Formatter.HTML.ASTFormatter','SummaryASTCommenter'), ('Synopsis.Formatter.HTML.ASTFormatter','FilePageLinker'), ] - modules = {'HTML':HTML} + class ConfigHTML (HTML): + pages = [ + ('modules.py', 'ConfScopeJS'), + ('modules.py', 'ConfScopePage') + ] + synopsis_pages = pages + modules = { + 'HTML':HTML, + 'ConfigHTML':ConfigHTML + }
26f437d7d33c0531e53ea42a5aea247c445ec5b3
flumotion/common/compat.py
flumotion/common/compat.py
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com). All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """ Compatibility for various versions of supporting libraries """ import gtk import gobject # We don't want to get the loud deprecation warnings from PyGtk for using # gobject.type_register() if we don't need it def type_register(type): (major, minor, patch) = gtk.pygtk_version if(major <= 1 and minor < 8): gobject.type_register(type) elif(not (hasattr(type, '__gtype_name__' or hasattr(type, '__gproperties__') or hasattr(type, '__gsignals__'))): gobject.type_register(type)
# -*- Mode: Python -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005 Fluendo, S.L. (www.fluendo.com). All rights reserved. # This file may be distributed and/or modified under the terms of # the GNU General Public License version 2 as published by # the Free Software Foundation. # This file is distributed without any warranty; without even the implied # warranty of merchantability or fitness for a particular purpose. # See "LICENSE.GPL" in the source distribution for more information. # Licensees having purchased or holding a valid Flumotion Advanced # Streaming Server license may use this file in accordance with the # Flumotion Advanced Streaming Server Commercial License Agreement. # See "LICENSE.Flumotion" in the source distribution for more information. # Headers in this file shall remain intact. """ Compatibility for various versions of supporting libraries """ import gtk import gobject # We don't want to get the loud deprecation warnings from PyGtk for using # gobject.type_register() if we don't need it def type_register(type): (major, minor, patch) = gtk.pygtk_version if(major <= 2 and minor < 8): gobject.type_register(type) elif(not (hasattr(type, '__gtype_name__' or hasattr(type, '__gproperties__') or hasattr(type, '__gsignals__'))): gobject.type_register(type)
Check for 2.8, not 1.8
Check for 2.8, not 1.8
Python
lgpl-2.1
timvideos/flumotion,timvideos/flumotion,timvideos/flumotion,Flumotion/flumotion,flumotion-mirror/flumotion,Flumotion/flumotion,flumotion-mirror/flumotion,Flumotion/flumotion,Flumotion/flumotion
--- +++ @@ -29,7 +29,7 @@ # gobject.type_register() if we don't need it def type_register(type): (major, minor, patch) = gtk.pygtk_version - if(major <= 1 and minor < 8): + if(major <= 2 and minor < 8): gobject.type_register(type) elif(not (hasattr(type, '__gtype_name__' or hasattr(type, '__gproperties__') or hasattr(type, '__gsignals__'))):
b26fc811872caf3393be0a6b6c0800f5335ad2df
netbox/utilities/metadata.py
netbox/utilities/metadata.py
from rest_framework.metadata import SimpleMetadata from django.utils.encoding import force_str from utilities.api import ContentTypeField class ContentTypeMetadata(SimpleMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if hasattr(field, 'queryset') and not field_info.get('read_only') and isinstance(field, ContentTypeField): field_info['choices'] = [ { 'value': choice_value, 'display_name': force_str(choice_name, strings_only=True) } for choice_value, choice_name in field.choices.items() ] return field_info
from rest_framework.metadata import SimpleMetadata from django.utils.encoding import force_str from utilities.api import ContentTypeField class ContentTypeMetadata(SimpleMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if hasattr(field, 'queryset') and not field_info.get('read_only') and isinstance(field, ContentTypeField): field_info['choices'] = [ { 'value': choice_value, 'display_name': force_str(choice_name, strings_only=True) } for choice_value, choice_name in field.choices.items() ] field_info['choices'].sort(key=lambda item: item['display_name']) return field_info
Sort the list for consistent output
Sort the list for consistent output
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
--- +++ @@ -15,4 +15,5 @@ } for choice_value, choice_name in field.choices.items() ] + field_info['choices'].sort(key=lambda item: item['display_name']) return field_info
7cdbf0c989109c089c758d28b68f5f1925ebf388
securedrop/worker.py
securedrop/worker.py
import os from redis import Redis from rq import Queue queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default' q = Queue(name=queue_name, connection=Redis()) def enqueue(*args, **kwargs): q.enqueue(*args, **kwargs)
import os from redis import Redis from rq import Queue queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default' # `srm` can take a long time on large files, so allow it run for up to an hour q = Queue(name=queue_name, connection=Redis(), default_timeout=3600) def enqueue(*args, **kwargs): q.enqueue(*args, **kwargs)
Increase job timeout for securely deleting files
Increase job timeout for securely deleting files
Python
agpl-3.0
garrettr/securedrop,kelcecil/securedrop,jaseg/securedrop,jeann2013/securedrop,jeann2013/securedrop,chadmiller/securedrop,micahflee/securedrop,micahflee/securedrop,pwplus/securedrop,harlo/securedrop,ageis/securedrop,ageis/securedrop,jeann2013/securedrop,kelcecil/securedrop,micahflee/securedrop,harlo/securedrop,jrosco/securedrop,ehartsuyker/securedrop,jaseg/securedrop,pwplus/securedrop,harlo/securedrop,micahflee/securedrop,chadmiller/securedrop,chadmiller/securedrop,chadmiller/securedrop,jrosco/securedrop,ehartsuyker/securedrop,GabeIsman/securedrop,heartsucker/securedrop,kelcecil/securedrop,jeann2013/securedrop,jrosco/securedrop,jrosco/securedrop,conorsch/securedrop,kelcecil/securedrop,heartsucker/securedrop,heartsucker/securedrop,garrettr/securedrop,pwplus/securedrop,conorsch/securedrop,ageis/securedrop,kelcecil/securedrop,pwplus/securedrop,jrosco/securedrop,harlo/securedrop,jaseg/securedrop,ehartsuyker/securedrop,jeann2013/securedrop,jaseg/securedrop,kelcecil/securedrop,conorsch/securedrop,heartsucker/securedrop,chadmiller/securedrop,pwplus/securedrop,heartsucker/securedrop,GabeIsman/securedrop,ehartsuyker/securedrop,jeann2013/securedrop,harlo/securedrop,jaseg/securedrop,jrosco/securedrop,GabeIsman/securedrop,chadmiller/securedrop,harlo/securedrop,pwplus/securedrop,jaseg/securedrop,conorsch/securedrop,garrettr/securedrop,garrettr/securedrop,GabeIsman/securedrop,ageis/securedrop,ehartsuyker/securedrop,GabeIsman/securedrop,GabeIsman/securedrop,ehartsuyker/securedrop,conorsch/securedrop
--- +++ @@ -5,7 +5,8 @@ queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default' -q = Queue(name=queue_name, connection=Redis()) +# `srm` can take a long time on large files, so allow it run for up to an hour +q = Queue(name=queue_name, connection=Redis(), default_timeout=3600) def enqueue(*args, **kwargs): q.enqueue(*args, **kwargs)
0b9e8795318922c1c7699932d8a6e984ce00b13d
mmstats/__init__.py
mmstats/__init__.py
version = __version__ = '0.6.2' from .defaults import * from .fields import * from .models import *
version = __version__ = '0.7.0-dev' from .defaults import * from .fields import * from .models import *
Bump to 0.7.0 development version
Bump to 0.7.0 development version
Python
bsd-3-clause
schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats
--- +++ @@ -1,4 +1,4 @@ -version = __version__ = '0.6.2' +version = __version__ = '0.7.0-dev' from .defaults import * from .fields import *
e2b7ebf9a559a50462f64ca15a7688166fd4de9f
modules/music/gs.py
modules/music/gs.py
import subprocess from grooveshark import Client client = Client() client.init() def get_song_url(song_name): song = client.search(song_name).next() return song.stream.url def play_song_url(song_url): subprocess.call(['cvlc', song_url]) def play_song(song_name): play_song_url(get_song_url(song_name))
import subprocess from grooveshark import Client client = Client() client.init() def get_song_url(song_name): song = client.search(song_name).next() return song.stream.url def play_song_url(song_url): subprocess.call(['cvlc', '--play-and-exit', song_url]) def play_song(song_name): play_song_url(get_song_url(song_name))
Make vlc exit at end of play
Make vlc exit at end of play
Python
mit
adelq/mirror
--- +++ @@ -9,7 +9,7 @@ return song.stream.url def play_song_url(song_url): - subprocess.call(['cvlc', song_url]) + subprocess.call(['cvlc', '--play-and-exit', song_url]) def play_song(song_name): play_song_url(get_song_url(song_name))
268753ad6e4c3345e821c541e1851ee7f7a2b649
eachday/tests/test_resource_utils.py
eachday/tests/test_resource_utils.py
from eachday.tests.base import BaseTestCase import json class TestResourceUtils(BaseTestCase): def test_invalid_json_error(self): ''' Test that an invalid JSON body has a decent error message ''' resp = self.client.post( '/register', data='{"invalid": json}', content_type='application/json' ) data = json.loads(resp.data.decode()) self.assertEqual(resp.status_code, 400) self.assertEqual(data['status'], 'error') self.assertEqual(data['error'], 'Invalid JSON body')
from eachday.resources import LoginResource from eachday.tests.base import BaseTestCase from unittest.mock import patch import json class TestResourceUtils(BaseTestCase): def test_invalid_json_error(self): ''' Test that an invalid JSON body has a decent error message ''' resp = self.client.post( '/register', data='{"invalid": json}', content_type='application/json' ) data = json.loads(resp.data.decode()) self.assertEqual(resp.status_code, 400) self.assertEqual(data['status'], 'error') self.assertEqual(data['error'], 'Invalid JSON body') class TestExceptionHandler(BaseTestCase): @patch('eachday.resources.db') @patch('eachday.resources.log') def test_exception_handling(self, LogMock, DbMock): ''' Test that internal server errors are handled gracefully ''' view_exception = Exception('Uh oh') # Inject function into /login to raise an exception def raise_error(self): raise view_exception LoginResource.post = raise_error resp = self.client.post('/login') self.assertEqual(resp.status_code, 500) data = json.loads(resp.data.decode()) self.assertEqual(data['status'], 'error') self.assertEqual(data['error'], 'Something went wrong.') # Make sure session gets rolled back self.assertTrue(DbMock.session.rollback.called) # Make sure exception is logged correctly LogMock.error.assert_called_with(view_exception) LogMock.info.assert_called_with('Rolled back current session')
Add test for exception handling in flask app
Add test for exception handling in flask app
Python
mit
bcongdon/EachDay,bcongdon/EachDay,bcongdon/EachDay,bcongdon/EachDay
--- +++ @@ -1,4 +1,6 @@ +from eachday.resources import LoginResource from eachday.tests.base import BaseTestCase +from unittest.mock import patch import json @@ -14,3 +16,30 @@ self.assertEqual(resp.status_code, 400) self.assertEqual(data['status'], 'error') self.assertEqual(data['error'], 'Invalid JSON body') + + +class TestExceptionHandler(BaseTestCase): + + @patch('eachday.resources.db') + @patch('eachday.resources.log') + def test_exception_handling(self, LogMock, DbMock): + ''' Test that internal server errors are handled gracefully ''' + view_exception = Exception('Uh oh') + + # Inject function into /login to raise an exception + def raise_error(self): + raise view_exception + LoginResource.post = raise_error + + resp = self.client.post('/login') + self.assertEqual(resp.status_code, 500) + data = json.loads(resp.data.decode()) + self.assertEqual(data['status'], 'error') + self.assertEqual(data['error'], 'Something went wrong.') + + # Make sure session gets rolled back + self.assertTrue(DbMock.session.rollback.called) + + # Make sure exception is logged correctly + LogMock.error.assert_called_with(view_exception) + LogMock.info.assert_called_with('Rolled back current session')
24089dfb12c3ecbec40423acf4d3c89c0b833f40
share/models/util.py
share/models/util.py
import zlib import base64 import binascii from django.db import models from django.core import exceptions class ZipField(models.Field): def db_type(self, connection): return 'bytea' def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) assert isinstance(value, (bytes, str)), 'Values must be of type str or bytes, got {}'.format(type(value)) if not value and not self.blank: raise exceptions.ValidationError('"{}" on {!r} can not be blank or empty'.format(self.attname, model_instance)) if isinstance(value, str): value = value.encode() return base64.b64encode(zlib.compress(value)) def from_db_value(self, value, expression, connection, context): if value is None: return value assert value return zlib.decompress(base64.b64decode(value)) def to_python(self, value): assert value if value is None or isinstance(value, ZipField): return value # TODO: Not sure if this is necessary or just solving a temporary error try: base64.decodestring(bytes(value, 'utf8')) except binascii.Error: value = base64.b64encode(zlib.compress(bytes(value, 'utf8'))) # END TODO return zlib.decompress(base64.b64decode(value))
import zlib import base64 import binascii from django.db import models from django.core import exceptions class ZipField(models.Field): def db_type(self, connection): return 'bytea' def pre_save(self, model_instance, add): value = getattr(model_instance, self.attname) assert isinstance(value, (bytes, str)), 'Values must be of type str or bytes, got {}'.format(type(value)) if not value and not self.blank: raise exceptions.ValidationError('"{}" on {!r} can not be blank or empty'.format(self.attname, model_instance)) if isinstance(value, str): value = value.encode() return base64.b64encode(zlib.compress(value)) def from_db_value(self, value, expression, connection, context): if value is None: return value assert value return zlib.decompress(base64.b64decode(value)) def to_python(self, value): assert value if value is None or isinstance(value, ZipField): return value try: base64.decodebytes(bytes(value, 'utf8')) except binascii.Error: # it's not base64, return it. return value return zlib.decompress(base64.b64decode(value))
Make it just return the string if it is not base64
Make it just return the string if it is not base64
Python
apache-2.0
CenterForOpenScience/SHARE,aaxelb/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,aaxelb/SHARE,zamattiac/SHARE,laurenbarker/SHARE,zamattiac/SHARE,aaxelb/SHARE,CenterForOpenScience/SHARE
--- +++ @@ -30,10 +30,10 @@ assert value if value is None or isinstance(value, ZipField): return value - # TODO: Not sure if this is necessary or just solving a temporary error try: - base64.decodestring(bytes(value, 'utf8')) + base64.decodebytes(bytes(value, 'utf8')) except binascii.Error: - value = base64.b64encode(zlib.compress(bytes(value, 'utf8'))) - # END TODO + # it's not base64, return it. + return value + return zlib.decompress(base64.b64decode(value))
8c8f26ffe52e2df68a8f7ba87871f260a5023406
measurement/measures/energy.py
measurement/measures/energy.py
from measurement.base import MeasureBase __all__ = [ 'Energy' ] class Energy(MeasureBase): STANDARD_UNIT = 'J' UNITS = { 'c': 4.18400, 'C': 4184.0, 'J': 1.0, 'eV': 1.602177e-9, 'tonne_tnt': 4184000000, } ALIAS = { 'joule': 'J', 'calorie': 'c', 'Calorie': 'C', } SI_UNITS = ['J', 'c', 'eV', 'tonne_tnt']
from measurement.base import MeasureBase __all__ = [ 'Energy' ] class Energy(MeasureBase): STANDARD_UNIT = 'J' UNITS = { 'c': 4.18400, 'C': 4184.0, 'J': 1.0, 'eV': 1.602177e-19, 'tonne_tnt': 4184000000, } ALIAS = { 'joule': 'J', 'calorie': 'c', 'Calorie': 'C', } SI_UNITS = ['J', 'c', 'eV', 'tonne_tnt']
Correct factor for electron volt
Correct factor for electron volt
Python
mit
yggdr/python-measurement,coddingtonbear/python-measurement
--- +++ @@ -12,7 +12,7 @@ 'c': 4.18400, 'C': 4184.0, 'J': 1.0, - 'eV': 1.602177e-9, + 'eV': 1.602177e-19, 'tonne_tnt': 4184000000, } ALIAS = {
9aa60f5da016468b345fac4499454ca4abeb8b3f
ansible/roles/cumulus/files/amis.py
ansible/roles/cumulus/files/amis.py
import boto.ec2 import sys import argparse parser = argparse.ArgumentParser() parser.add_argument('aws_access_key_id') parser.add_argument('aws_secret_access_key') parser.add_argument('region') config = parser.parse_args() conn = boto.ec2.connect_to_region(config.region, aws_access_key_id=config.aws_access_key_id, aws_secret_access_key=config.aws_secret_access_key) images = conn.get_all_images(owners=['self']) values = [] for image in images: values.append('"%s": "%s"' % (image.name, image.id)) print ','.join(values)
import boto.ec2 import sys import argparse parser = argparse.ArgumentParser() parser.add_argument('aws_access_key_id') parser.add_argument('aws_secret_access_key') parser.add_argument('region') config = parser.parse_args() conn = boto.ec2.connect_to_region(config.region, aws_access_key_id=config.aws_access_key_id, aws_secret_access_key=config.aws_secret_access_key) images = conn.get_all_images(owners=['self']) values = [] for image in images: values.append('"%s": "%s"' % (image.name, image.id)) print( ','.join(values))
Fix python 3 incompatible print statement
Fix python 3 incompatible print statement
Python
apache-2.0
Kitware/HPCCloud-deploy,Kitware/HPCCloud-deploy,Kitware/HPCCloud-deploy
--- +++ @@ -1,6 +1,7 @@ import boto.ec2 import sys import argparse + parser = argparse.ArgumentParser() parser.add_argument('aws_access_key_id') @@ -17,4 +18,4 @@ for image in images: values.append('"%s": "%s"' % (image.name, image.id)) -print ','.join(values) +print( ','.join(values))
4047f744debb73d64de03bc0e7f16d2bbd308529
ores/wsgi/routes/__init__.py
ores/wsgi/routes/__init__.py
from . import scores from . import ui def configure(config, bp, score_processor): @bp.route("/", methods=["GET"]) def index(): return render_template("home.html") bp = scores.configure(config, bp, score_processor) bp = ui.configure(config, bp) return bp
from . import scores from . import ui def configure(config, bp, score_processor): @bp.route("/", methods=["GET"]) def index(): return ui.render_template("home.html") bp = scores.configure(config, bp, score_processor) bp = ui.configure(config, bp) return bp
FIX 'render_template not defined' error
FIX 'render_template not defined' error This was appearing if you try to open 'http://host:port/'
Python
mit
he7d3r/ores,wiki-ai/ores,he7d3r/ores,he7d3r/ores,wiki-ai/ores,wiki-ai/ores
--- +++ @@ -7,7 +7,7 @@ @bp.route("/", methods=["GET"]) def index(): - return render_template("home.html") + return ui.render_template("home.html") bp = scores.configure(config, bp, score_processor) bp = ui.configure(config, bp)
eb368c344075ce78606d4656ebfb19c7e7ccdf50
src/054.py
src/054.py
from path import dirpath def ans(): lines = open(dirpath() + '054.txt').readlines() cards = [line.strip().split() for line in lines] return None if __name__ == '__main__': print(ans())
from collections import ( defaultdict, namedtuple, ) from path import dirpath def _value(rank): try: return int(rank) except ValueError: return 10 + 'TJQKA'.index(rank) def _sort_by_rank(hand): return list(reversed(sorted( hand, key=lambda card: _value(card[0]), ))) def _of_a_kind(hand, count): counts = defaultdict(list) for card in hand: counts[card[0]].append(card) filtered = { rank: cards for rank, cards in counts.items() if count <= len(cards) } if len(filtered) < 1: return None return max( filtered.values(), key=lambda cards: _value(cards[0][0]) ) def high_card(hand): return _of_a_kind(hand, 1) def two_of_a_kind(hand): return _of_a_kind(hand, 2) def three_of_a_kind(hand): return _of_a_kind(hand, 3) def four_of_a_kind(hand): return _of_a_kind(hand, 4) def full_house(hand): three = three_of_a_kind(hand) if not three: return None pair = two_of_a_kind([card for card in hand if card not in three]) if not pair: return None return three + pair def straight(hand): sorted_ = sorted([_value(card[0]) for card in hand]) if sorted_ == list(range(sorted_[0], sorted_[-1] + 1)): return _sort_by_rank(hand) return None def flush(hand): counts = defaultdict(list) for card in hand: counts[card[1]].append(card) for cards in counts.values(): if len(cards) == 5: return _sort_by_rank(cards) return None def straight_flush(hand): return flush(hand) if straight(hand) else None def ans(): lines = open(dirpath() + '054.txt').readlines() turns = [line.strip().split() for line in lines] num_wins = 0 for cards in turns: one = cards[:5] two = cards[5:] return None if __name__ == '__main__': print(ans())
Write some logic for 54
Write some logic for 54
Python
mit
mackorone/euler
--- +++ @@ -1,9 +1,95 @@ +from collections import ( + defaultdict, + namedtuple, +) from path import dirpath + + +def _value(rank): + try: + return int(rank) + except ValueError: + return 10 + 'TJQKA'.index(rank) + + +def _sort_by_rank(hand): + return list(reversed(sorted( + hand, + key=lambda card: _value(card[0]), + ))) + + +def _of_a_kind(hand, count): + counts = defaultdict(list) + for card in hand: + counts[card[0]].append(card) + filtered = { + rank: cards for + rank, cards in counts.items() if + count <= len(cards) + } + if len(filtered) < 1: + return None + return max( + filtered.values(), + key=lambda cards: _value(cards[0][0]) + ) + + +def high_card(hand): + return _of_a_kind(hand, 1) + + +def two_of_a_kind(hand): + return _of_a_kind(hand, 2) + + +def three_of_a_kind(hand): + return _of_a_kind(hand, 3) + + +def four_of_a_kind(hand): + return _of_a_kind(hand, 4) + + +def full_house(hand): + three = three_of_a_kind(hand) + if not three: + return None + pair = two_of_a_kind([card for card in hand if card not in three]) + if not pair: + return None + return three + pair + + +def straight(hand): + sorted_ = sorted([_value(card[0]) for card in hand]) + if sorted_ == list(range(sorted_[0], sorted_[-1] + 1)): + return _sort_by_rank(hand) + return None + + +def flush(hand): + counts = defaultdict(list) + for card in hand: + counts[card[1]].append(card) + for cards in counts.values(): + if len(cards) == 5: + return _sort_by_rank(cards) + return None + + +def straight_flush(hand): + return flush(hand) if straight(hand) else None def ans(): lines = open(dirpath() + '054.txt').readlines() - cards = [line.strip().split() for line in lines] + turns = [line.strip().split() for line in lines] + num_wins = 0 + for cards in turns: + one = cards[:5] + two = cards[5:] return None
88517c2f458a0e94b1a526bf99e565571353ed56
flicktor/__main__.py
flicktor/__main__.py
from flicktor import subcommands def main(): parser = subcommands._argpaser() args = parser.parse_args() try: args.func(args) # except AttributeError: # parser.print_help() except KeyboardInterrupt: print("bye.") if __name__ == '__main__': main()
from flicktor import subcommands def main(): parser = subcommands._argpaser() args = parser.parse_args() try: if hasattr(args, "func"): args.func(args) else: parser.print_help() except KeyboardInterrupt: print("bye.") if __name__ == '__main__': main()
Print help when subcommand is not supecified
Print help when subcommand is not supecified
Python
mit
minamorl/flicktor
--- +++ @@ -5,9 +5,12 @@ parser = subcommands._argpaser() args = parser.parse_args() try: - args.func(args) - # except AttributeError: - # parser.print_help() + if hasattr(args, "func"): + args.func(args) + else: + parser.print_help() + + except KeyboardInterrupt: print("bye.")
6c19837ec2d29e2ad48c09b6287e64c825830bc9
prototypes/regex/__init__.py
prototypes/regex/__init__.py
# coding: utf-8 """ regex ~~~~~ This is a prototype for an implementation of regular expressions. The goal of this prototype is to develop a completely transparent implementation, that can be better reasoned about and used in a parser. Note that as of now "regular expressions" actually means *regular*, so non-greedy repetitions (``*?``, ``+?``), positive/negative lookahead/-behind assertions are not supported with the current implementation. On the other hand this allows for a very efficient implementation. Currently regular expressions can be compiled to NFAs and DFAs (graph and table driven). :copyright: 2012 by Daniel Neuhäuser :license: BSD, see LICENSE.rst """
# coding: utf-8 """ regex ~~~~~ This is a prototype for an implementation of regular expressions. The goal of this prototype is to develop a completely transparent implementation, that can be better reasoned about and used in a parser. This is not meant to be an implementation that will see real-world usage, in fact the performance on most - if not all - python implementations will make that prohibitive. Note that as of now "regular expressions" actually means *regular*, so non-greedy repetitions (``*?``, ``+?``), positive/negative lookahead/-behind assertions are not supported with the current implementation. On the other hand this allows for a very efficient implementation. Currently regular expressions can be compiled to NFAs and DFAs (graph and table driven). :copyright: 2012 by Daniel Neuhäuser :license: BSD, see LICENSE.rst """
Add warning about real-world usage
Add warning about real-world usage
Python
bsd-3-clause
DasIch/editor
--- +++ @@ -5,7 +5,10 @@ This is a prototype for an implementation of regular expressions. The goal of this prototype is to develop a completely transparent implementation, - that can be better reasoned about and used in a parser. + that can be better reasoned about and used in a parser. This is not meant + to be an implementation that will see real-world usage, in fact the + performance on most - if not all - python implementations will make that + prohibitive. Note that as of now "regular expressions" actually means *regular*, so non-greedy repetitions (``*?``, ``+?``), positive/negative
1b5ad9a8e2b06218d511ce8f97521235c14a9507
src/app.py
src/app.py
import os import json import random import flask from hashlib import md5 records = {} # Create a hash table of all records. for record in json.loads(open('data/records-2015.json').read())['records']: records[md5(str(record['id']).encode('utf-8')).hexdigest()] = record app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('index.html') @app.route('/hello') def hello(): return 'hello' @app.route('/random') def random_record(): record_hash = random.choice(list(records.keys())) return str(records[record_hash]) if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
import os import json import random import flask import requests import hashlib DNZ_URL = 'http://api.digitalnz.org/v3/records/' DNZ_KEY = os.environ.get('DNZ_KEY') records = {} # TODO This should be switched to records associated with days. # Create a hash table of all records. for record in json.loads(open('data/records-2015.json').read())['records']: record_hash = hashlib.md5(str(record['id']).encode('utf-8')).hexdigest() records[record_hash] = record app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('index.html') @app.route('/hello') def hello(): return 'hello' @app.route('/random') def random_record(): record_hash = random.choice(list(records.keys())) return str(get_metadata(records[record_hash]['id'])) def get_metadata(id): url = DNZ_URL + '{id}.json?api_key={key}'.format(id=id, key=DNZ_KEY) return requests.get(url).json() if __name__ == '__main__': port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port, debug=True)
Add method to query DNZ Metadata API
Add method to query DNZ Metadata API
Python
mit
judsonsam/tekautoday,judsonsam/tekautoday,judsonsam/tekautoday,judsonsam/tekautoday
--- +++ @@ -2,14 +2,18 @@ import json import random import flask +import requests +import hashlib -from hashlib import md5 - +DNZ_URL = 'http://api.digitalnz.org/v3/records/' +DNZ_KEY = os.environ.get('DNZ_KEY') records = {} +# TODO This should be switched to records associated with days. # Create a hash table of all records. for record in json.loads(open('data/records-2015.json').read())['records']: - records[md5(str(record['id']).encode('utf-8')).hexdigest()] = record + record_hash = hashlib.md5(str(record['id']).encode('utf-8')).hexdigest() + records[record_hash] = record app = flask.Flask(__name__) @@ -27,7 +31,12 @@ @app.route('/random') def random_record(): record_hash = random.choice(list(records.keys())) - return str(records[record_hash]) + return str(get_metadata(records[record_hash]['id'])) + + +def get_metadata(id): + url = DNZ_URL + '{id}.json?api_key={key}'.format(id=id, key=DNZ_KEY) + return requests.get(url).json() if __name__ == '__main__': port = int(os.environ.get('PORT', 5000))
c458126baac92e1152026f51a9d3a544e8c6826f
testsV2/ut_repy2api_copycontext.py
testsV2/ut_repy2api_copycontext.py
""" Check that copy and repr of _context SafeDict don't result in inifinite loop """ #pragma repy # Create an almost shallow copy of _context # Contained self-reference is moved from _context to _context_copy _context_copy = _context.copy() repr(_context) repr(_context_copy)
""" Check that copy and repr of _context SafeDict don't result in infinite loop """ #pragma repy # Create an "almost" shallow copy of _context, i.e. the contained reference # to _context is not copied as such but is changed to reference the new # _context_copy. # In consequence repr immediately truncates the contained self-reference # ("{...}") to prevent an infinite loop. # Caveat: In a real shallow copy, repr would only truncate the context # contained in the contained context (3rd level). _context_copy = _context.copy() repr(_context) repr(_context_copy)
Update comment in copycontext unit test
Update comment in copycontext unit test Following @vladimir-v-diaz's review comment this change adds more information about how repr works with Python dicts and with repy's SafeDict to the unit test's comments. Even more information can be found on the issue tracker SeattleTestbed/repy_v2#97.
Python
mit
SeattleTestbed/repy_v2
--- +++ @@ -1,10 +1,15 @@ """ -Check that copy and repr of _context SafeDict don't result in inifinite loop +Check that copy and repr of _context SafeDict don't result in infinite loop """ #pragma repy -# Create an almost shallow copy of _context -# Contained self-reference is moved from _context to _context_copy +# Create an "almost" shallow copy of _context, i.e. the contained reference +# to _context is not copied as such but is changed to reference the new +# _context_copy. +# In consequence repr immediately truncates the contained self-reference +# ("{...}") to prevent an infinite loop. +# Caveat: In a real shallow copy, repr would only truncate the context +# contained in the contained context (3rd level). _context_copy = _context.copy() repr(_context) repr(_context_copy)
d10199e4e3cd5b0557cf2dc2f4aea1014f18a290
lib/wordfilter.py
lib/wordfilter.py
import os import json class Wordfilter: def __init__(self): # json is in same directory as this class, given by __location__. __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'badwords.json')) as f: self.blacklist = json.loads(f.read()) def blacklisted(self, string): test_string = string.lower() for badword in self.blacklist: if test_string.find(badword) != -1: return True return False def addWords(self, words): self.blacklist.extend(words.lower()) def clearList(self): self.blacklist = []
import os import json class Wordfilter: def __init__(self): # json is in same directory as this class, given by __location__. __location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) with open(os.path.join(__location__, 'badwords.json')) as f: self.blacklist = json.loads(f.read()) def blacklisted(self, string): test_string = string.lower() for badword in self.blacklist: if test_string.find(badword) != -1: return True return False def addWords(self, words): self.blacklist.extend([word.lower() for word in words]]) def clearList(self): self.blacklist = []
Fix AttributeError: 'list' object has no attribute 'lower'
Fix AttributeError: 'list' object has no attribute 'lower'
Python
mit
dariusk/wordfilter,hugovk/wordfilter,hugovk/wordfilter,mwatson/wordfilter,hugovk/wordfilter,dariusk/wordfilter,mwatson/wordfilter,dariusk/wordfilter,mwatson/wordfilter,mwatson/wordfilter,dariusk/wordfilter,hugovk/wordfilter
--- +++ @@ -16,9 +16,9 @@ return True return False - + def addWords(self, words): - self.blacklist.extend(words.lower()) + self.blacklist.extend([word.lower() for word in words]]) def clearList(self): self.blacklist = []
322d8f90f86c40a756716a79e7e5719196687ece
saic/paste/search_indexes.py
saic/paste/search_indexes.py
import datetime from haystack.indexes import * from haystack import site from models import Paste, Commit class CommitIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) commit = CharField(model_attr='commit') created = DateField(model_attr='created') user = CharField(model_attr='owner', null=True) class PasteIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) paste = CharField(model_attr='paste') filename = CharField(model_attr='filename') language = CharField(model_attr='language') commit = CharField(model_attr='revision__commit') site.register(Paste, PasteIndex) site.register(Commit, CommitIndex)
import datetime from haystack.indexes import * from haystack import site from models import Paste, Commit class CommitIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) commit = CharField(model_attr='commit') created = DateField(model_attr='created') user = CharField(model_attr='owner', null=True) def index_queryset(self): return Commit.objects.all() class PasteIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) paste = CharField(model_attr='paste') filename = CharField(model_attr='filename') language = CharField(model_attr='language') commit = CharField(model_attr='revision__commit') def index_queryset(self): return Paste.objects.all() site.register(Paste, PasteIndex) site.register(Commit, CommitIndex)
Update search index to look for all objects.
Update search index to look for all objects.
Python
bsd-3-clause
justinvh/gitpaste,GarrettHeel/quark-paste,GarrettHeel/quark-paste,justinvh/gitpaste,justinvh/gitpaste,justinvh/gitpaste,GarrettHeel/quark-paste
--- +++ @@ -9,6 +9,9 @@ created = DateField(model_attr='created') user = CharField(model_attr='owner', null=True) + def index_queryset(self): + return Commit.objects.all() + class PasteIndex(RealTimeSearchIndex): text = CharField(document=True, use_template=True) @@ -17,6 +20,9 @@ language = CharField(model_attr='language') commit = CharField(model_attr='revision__commit') + def index_queryset(self): + return Paste.objects.all() + site.register(Paste, PasteIndex) site.register(Commit, CommitIndex)
1bda3fa8b3bffaca38b26191602e74d0afeaad19
app/views.py
app/views.py
from flask import render_template, request, Blueprint import json from app.state import state index = Blueprint('index', __name__, template_folder='templates') @index.route('/', methods=['POST', 'GET']) def show(): if request.method == 'GET': return render_template('index.html', program = 'ascii_text', brightness = 0.5, rotation = 0, text = 'Hello, World!', ) elif request.method == 'POST': params = {} if 'brightness' in request.form: params['brightness'] = request.form['brightness'] if 'rotation' in request.form: params['rotation'] = request.form['rotation'] if 'text' in request.form: params['text'] = request.form['text'] if request.form['submit'] == 'Run': state.start_program(request.form['program'], params) elif request.form['submit'] == 'Stop': state.stop_program() return render_template('index.html', program = request.form['program'], brightness = request.form['brightness'], rotation = request.form['rotation'], text = request.form['text'], )
from flask import render_template, request, Blueprint import json from app.state import state index = Blueprint('index', __name__, template_folder='templates') @index.route('/', methods=['GET']) def show(): if request.method == 'GET': return render_template('index.html')
Remove old web ui backend
Remove old web ui backend
Python
mit
njbbaer/unicorn-remote,njbbaer/unicorn-remote,njbbaer/unicorn-remote
--- +++ @@ -5,37 +5,8 @@ index = Blueprint('index', __name__, template_folder='templates') -@index.route('/', methods=['POST', 'GET']) +@index.route('/', methods=['GET']) def show(): - + if request.method == 'GET': - return render_template('index.html', - program = 'ascii_text', - brightness = 0.5, - rotation = 0, - text = 'Hello, World!', - ) - - elif request.method == 'POST': - params = {} - - if 'brightness' in request.form: - params['brightness'] = request.form['brightness'] - - if 'rotation' in request.form: - params['rotation'] = request.form['rotation'] - - if 'text' in request.form: - params['text'] = request.form['text'] - - if request.form['submit'] == 'Run': - state.start_program(request.form['program'], params) - elif request.form['submit'] == 'Stop': - state.stop_program() - - return render_template('index.html', - program = request.form['program'], - brightness = request.form['brightness'], - rotation = request.form['rotation'], - text = request.form['text'], - ) + return render_template('index.html')
5fcc90741e443133695c65e04b26fc9d1313e530
djangae/models.py
djangae/models.py
from django.db import models from djangae import patches class CounterShard(models.Model): count = models.PositiveIntegerField() # Apply our django patches patches.patch()
from django.db import models from djangae import patches class CounterShard(models.Model): count = models.PositiveIntegerField() class Meta: app_label = "djangae" # Apply our django patches patches.patch()
Fix a warning in 1.8
Fix a warning in 1.8
Python
bsd-3-clause
wangjun/djangae,trik/djangae,martinogden/djangae,asendecka/djangae,grzes/djangae,leekchan/djangae,chargrizzle/djangae,grzes/djangae,martinogden/djangae,armirusco/djangae,potatolondon/djangae,SiPiggles/djangae,kirberich/djangae,potatolondon/djangae,armirusco/djangae,asendecka/djangae,leekchan/djangae,SiPiggles/djangae,chargrizzle/djangae,jscissr/djangae,asendecka/djangae,jscissr/djangae,grzes/djangae,kirberich/djangae,martinogden/djangae,chargrizzle/djangae,wangjun/djangae,trik/djangae,leekchan/djangae,wangjun/djangae,jscissr/djangae,armirusco/djangae,kirberich/djangae,trik/djangae,SiPiggles/djangae
--- +++ @@ -6,5 +6,8 @@ class CounterShard(models.Model): count = models.PositiveIntegerField() + class Meta: + app_label = "djangae" + # Apply our django patches patches.patch()
3d9b7fe808f2c8a64e0b834c0a67fa53631e5235
dbaas/api/integration_credential.py
dbaas/api/integration_credential.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from integrations.credentials.models import IntegrationCredential from .environment import EnvironmentSerializer from .integration_type import IntegrationTypeSerializer class IntegrationCredentialSerializer(serializers.HyperlinkedModelSerializer): environments = EnvironmentSerializer(many=True, read_only=True) integration_type = IntegrationTypeSerializer(many=False, read_only=True) class Meta: model = IntegrationCredential fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments') class IntegrationCredentialAPI(viewsets.ModelViewSet): """ Integration Credential Api """ serializer_class = IntegrationCredentialSerializer queryset = IntegrationCredential.objects.all()
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from integrations.credentials.models import IntegrationCredential from .environment import EnvironmentSerializer from .integration_type import IntegrationTypeSerializer class IntegrationCredentialSerializer(serializers.HyperlinkedModelSerializer): environments = EnvironmentSerializer(many=True, read_only=True) integration_type = IntegrationTypeSerializer(many=False, read_only=True) class Meta: model = IntegrationCredential fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments',"project",) class IntegrationCredentialAPI(viewsets.ModelViewSet): """ Integration Credential Api """ serializer_class = IntegrationCredentialSerializer queryset = IntegrationCredential.objects.all()
Add project to integration credential api fields
Add project to integration credential api fields
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
--- +++ @@ -13,7 +13,7 @@ class Meta: model = IntegrationCredential - fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments') + fields = ('user', 'password', 'integration_type', 'token', 'secret', 'endpoint', 'environments',"project",) class IntegrationCredentialAPI(viewsets.ModelViewSet):
eb6e89409296443369b73f5a0475ef8903700037
servers/curioecho_streams.py
servers/curioecho_streams.py
from curio import Kernel, new_task, run_server from socket import * async def echo_handler(client, addr): print('Connection from', addr) try: client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) except (OSError, NameError): pass reader, writer = client.make_streams() async with reader, writer: while True: data = await reader.read() if not data: break await writer.write(data) await client.close() print('Connection closed') if __name__ == '__main__': kernel = Kernel() kernel.run(run_server('', 25000, echo_handler))
from curio import Kernel, new_task, run_server from socket import * async def echo_handler(client, addr): print('Connection from', addr) try: client.setsockopt(IPPROTO_TCP, TCP_NODELAY, 1) except (OSError, NameError): pass reader, writer = client.make_streams() async with reader, writer: while True: data = await reader.read(102400) if not data: break await writer.write(data) await client.close() print('Connection closed') if __name__ == '__main__': kernel = Kernel() kernel.run(run_server('', 25000, echo_handler))
Use explicit read buffer size in curio/streams bench
Use explicit read buffer size in curio/streams bench
Python
mit
MagicStack/vmbench,MagicStack/vmbench,MagicStack/vmbench,MagicStack/vmbench,MagicStack/vmbench
--- +++ @@ -10,7 +10,7 @@ reader, writer = client.make_streams() async with reader, writer: while True: - data = await reader.read() + data = await reader.read(102400) if not data: break await writer.write(data)
db78e585c9b2edfdf9ccb5025d429b2e25f641fd
jupyterhub_config.py
jupyterhub_config.py
import os import re c = get_config() c.JupyterHub.hub_ip = '0.0.0.0' c.DockerSpawner.use_docker_client_env = True c.DockerSpawner.tls_assert_hostname = True c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator' c.JupyterHub.login_url = '/hub/oauth_login' def userlist(varname): """ Interept an environment variable as a whitespace-separated list of GitHub usernames. """ parts = re.split("\s*,\s*", os.environ[varname]) return set([part for part in parts if len(part) > 0]) c.Authenticator.whitelist = userlist("JUPYTERHUB_USERS") c.Authenticator.admin_users = userlist("JUPYTERHUB_ADMINS") c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL'] c.GitHubOAuthenticator.client_id = os.environ['GITHUB_CLIENT_ID'] c.GitHubOAuthenticator.client_secret = os.environ['GITHUB_CLIENT_SECRET']
import os import re c = get_config() c.JupyterHub.hub_ip = '0.0.0.0' c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' c.DockerSpawner.tls_verify = True c.DockerSpawner.tls_ca = "/etc/docker/ca.pem" c.DockerSpawner.tls_cert = "/etc/docker/server-cert.pem" c.DockerSpawner.tls_key = "/etc/docker/server-key.pem" c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator' c.JupyterHub.login_url = '/hub/oauth_login' def userlist(varname): """ Interept an environment variable as a whitespace-separated list of GitHub usernames. """ parts = re.split("\s*,\s*", os.environ[varname]) return set([part for part in parts if len(part) > 0]) c.Authenticator.whitelist = userlist("JUPYTERHUB_USERS") c.Authenticator.admin_users = userlist("JUPYTERHUB_ADMINS") c.GitHubOAuthenticator.oauth_callback_url = os.environ['OAUTH_CALLBACK_URL'] c.GitHubOAuthenticator.client_id = os.environ['GITHUB_CLIENT_ID'] c.GitHubOAuthenticator.client_secret = os.environ['GITHUB_CLIENT_SECRET']
Configure TLS for the DockerSpawner.
Configure TLS for the DockerSpawner.
Python
apache-2.0
smashwilson/jupyterhub-carina,smashwilson/jupyterhub-carina
--- +++ @@ -4,10 +4,12 @@ c = get_config() c.JupyterHub.hub_ip = '0.0.0.0' -c.DockerSpawner.use_docker_client_env = True -c.DockerSpawner.tls_assert_hostname = True c.JupyterHub.spawner_class = 'dockerspawner.DockerSpawner' +c.DockerSpawner.tls_verify = True +c.DockerSpawner.tls_ca = "/etc/docker/ca.pem" +c.DockerSpawner.tls_cert = "/etc/docker/server-cert.pem" +c.DockerSpawner.tls_key = "/etc/docker/server-key.pem" c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator'
0de3ca1439acec9191932a51e222aabc8b957047
mosql/__init__.py
mosql/__init__.py
# -*- coding: utf-8 -*- VERSION = (0, 11,) __author__ = 'Mosky <http://mosky.tw>' __version__ = '.'.join(str(v) for v in VERSION)
# -*- coding: utf-8 -*- VERSION = (0, 12,) __author__ = 'Mosky <http://mosky.tw>' __version__ = '.'.join(str(v) for v in VERSION)
Change the version to v0.12
Change the version to v0.12
Python
mit
moskytw/mosql
--- +++ @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -VERSION = (0, 11,) +VERSION = (0, 12,) __author__ = 'Mosky <http://mosky.tw>' __version__ = '.'.join(str(v) for v in VERSION)
1dfec537de941e32a13905a2aab7352439961bd3
entrypoint.py
entrypoint.py
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') app = Flask(__name__) @app.route('/') def ContainerService(): return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) output = stream.read() output
#!/usr/bin/python3 # # Define containerized environment for running Diosix on Qemu # # On Google Cloud Run: Creates HTTP server on port 8080 # or whatever was specified using the PORT system variable. # Outputs via the HTTP port. This requires K_SERVICE to be set. # # On all other environments: Log to stdout # # syntax: entrypoint.py <command> # # Author: Chris Williams <diodesign@tuta.io> # import os import sys global command_result from flask import Flask if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') # app = Flask(__name__) # @app.route('/') # def ContainerService(): # return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' # app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') # stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) # output = stream.read() # output
Debug Google Cloud Run support
Debug Google Cloud Run support
Python
mit
diodesign/diosix
--- +++ @@ -23,13 +23,13 @@ if __name__ == "__main__": if (os.environ.get('K_SERVICE')) != '': print('Running HTTP service for Google Cloud') - app = Flask(__name__) - @app.route('/') - def ContainerService(): - return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' - app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) + # app = Flask(__name__) + # @app.route('/') + # def ContainerService(): + # return 'Container built. Use docker images and docker run in the Google Cloud shell to run this container.\n' + # app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080))) else: print('Running locally') - stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) - output = stream.read() - output + # stream = os.popen('. $HOME/.cargo/env && cd /build/diosix && {}'.format(' '.join(sys.argv[1:]))) + # output = stream.read() + # output
3bf9853e83bf8d95844b58acac0d027b0ef5b863
fbanalysis.py
fbanalysis.py
import random import operator def get_sentiment(current_user, users, threads): friend_msg_count = {} for user in users.keys(): friend_msg_count[user] = 0 for thread in threads: for comment in thread: try: sender = comment['from']['id'] if sender not in friend_msg_count: friend_msg_count[sender] = 0 except: continue friend_msg_count[sender] += 1 friend_msg_count[current_user['id']] = None max_comments = float(max(friend_msg_count.values())) def outlook(user): if user['id'] not in friend_msg_count: print '%s not found in message count' % users[user['id']]['name'] else: return friend_msg_count[user['id']]/max_comments * 20.0 - 10.0 """ current_gender = current_user['gender'] current_rel_status = current_user['relationship_status'] current_sig_other = current_user['significant_other']['id'] def romance(user): if user['id'] == current_sig_other: return 10 elif current_rel_status == "Single" and user['relationship_status'] == 'Single': return 7 elif current_gender != user['gender']: return 3 else: return -2 """ def romance(user): return random.randint(-10,10) return dict([(ui, { 'outlook': outlook(u), 'romance': romance(u) }) for ui, u in users.items()])
import random import operator def get_sentiment(current_user, users, threads): friend_msg_count = {} for user in users.keys(): friend_msg_count[user] = 0 for thread in threads: for comment in thread: try: sender = comment['from']['id'] if sender not in friend_msg_count: friend_msg_count[sender] = 0 except: continue friend_msg_count[sender] += 1 friend_msg_count[current_user['id']] = None max_comments = float(max(friend_msg_count.values())) def volume(user): if user['id'] not in friend_msg_count: print '%s not found in message count' % users[user['id']]['name'] else: return friend_msg_count[user['id']]/max_comments * 20.0 - 10.0 def outlook(user): return random.randint(-10,10) return dict([(ui, { 'volume': volume(u), 'outlook': outlook(u) }) for ui, u in users.items()])
Change romance to outlook, outlook to volume
Change romance to outlook, outlook to volume
Python
mit
tomshen/dearstalker,tomshen/dearstalker
--- +++ @@ -15,29 +15,15 @@ friend_msg_count[sender] += 1 friend_msg_count[current_user['id']] = None max_comments = float(max(friend_msg_count.values())) - def outlook(user): + def volume(user): if user['id'] not in friend_msg_count: print '%s not found in message count' % users[user['id']]['name'] else: return friend_msg_count[user['id']]/max_comments * 20.0 - 10.0 - """ - current_gender = current_user['gender'] - current_rel_status = current_user['relationship_status'] - current_sig_other = current_user['significant_other']['id'] - def romance(user): - if user['id'] == current_sig_other: - return 10 - elif current_rel_status == "Single" and user['relationship_status'] == 'Single': - return 7 - elif current_gender != user['gender']: - return 3 - else: - return -2 - """ - def romance(user): + def outlook(user): return random.randint(-10,10) return dict([(ui, { - 'outlook': outlook(u), - 'romance': romance(u) + 'volume': volume(u), + 'outlook': outlook(u) }) for ui, u in users.items()])
ebd7a18402168ae7a27f771e1a27daffa88791d0
file_stats.py
file_stats.py
from heapq import heappush, heappushpop, heappop import os from pathlib import Path import sys from typing import List, Tuple N_LARGEST = 50 """Number of long file names to list.""" def main(): try: root = sys.argv[1] except IndexError: root = Path.home() / 'Dropbox (Springboard)' lengths: List[Tuple[int, Path]] = [] sizes: List[Tuple[int, Path]] = [] print('Walking', root) for base, dirs, files in os.walk(root): for f in files: path = Path(base, f).resolve() # Store longest path lengths heap_to_max(lengths, (len(str(path)), path)) # Store largest file sizes heap_to_max(sizes, (path.stat().st_size, path)) print('Path lengths:') print_heap(lengths) print() print('File sizes:') print_heap(sizes) print() def heap_to_max(heap, item, max_size=N_LARGEST): if len(heap) >= max_size: heappushpop(heap, item) else: heappush(heap, item) def print_heap(heap, fmt='{0[0]:<8} {0[1]}'): while True: try: item = heappop(heap) print(fmt.format(item)) except IndexError: break if __name__ == "__main__": main()
from heapq import heappush, heappushpop import os from pathlib import Path import sys from typing import List, Tuple N_LARGEST = 50 """Number of long file names to list.""" def main(): try: root = sys.argv[1] except IndexError: root = Path.home() / 'Dropbox (Springboard)' lengths: List[Tuple[int, Path]] = [] sizes: List[Tuple[int, Path]] = [] print('Walking', root) for base, dirs, files in os.walk(root): for f in files: path = Path(base, f).resolve() # Store longest path lengths heap_to_max(lengths, (len(str(path)), path)) # Store largest file sizes heap_to_max(sizes, (path.stat().st_size, path)) print('Path lengths:') print_heap(lengths) print() print('File sizes:') print_heap(sizes) print() def heap_to_max(heap, item, max_size=N_LARGEST): """Add item to heap. If then heap > N_LARGEST, pop the smallest item off the heap """ if len(heap) >= max_size: heappushpop(heap, item) else: heappush(heap, item) def print_heap(heap, fmt='{0[0]:<8} {0[1]}', ascending=False): sorted_list = sorted(heap, reverse=not ascending) for item in sorted_list: print(fmt.format(item)) if __name__ == "__main__": main()
Print stats highest to lowest
Print stats highest to lowest
Python
apache-2.0
blokeley/dfb,blokeley/backup_dropbox
--- +++ @@ -1,4 +1,4 @@ -from heapq import heappush, heappushpop, heappop +from heapq import heappush, heappushpop import os from pathlib import Path import sys @@ -41,21 +41,22 @@ def heap_to_max(heap, item, max_size=N_LARGEST): - if len(heap) >= max_size: - heappushpop(heap, item) + """Add item to heap. - else: - heappush(heap, item) + If then heap > N_LARGEST, pop the smallest item off the heap + """ + if len(heap) >= max_size: + heappushpop(heap, item) + + else: + heappush(heap, item) -def print_heap(heap, fmt='{0[0]:<8} {0[1]}'): - while True: - try: - item = heappop(heap) - print(fmt.format(item)) - - except IndexError: - break +def print_heap(heap, fmt='{0[0]:<8} {0[1]}', ascending=False): + sorted_list = sorted(heap, reverse=not ascending) + + for item in sorted_list: + print(fmt.format(item)) if __name__ == "__main__":
82ab7f6e618367b5544fe71dea57f793ebb6b453
auth0/v2/client.py
auth0/v2/client.py
from .rest import RestClient class Client(object): """Docstring for Client. """ def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/clients' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def all(self, fields=[], include_fields=True): params = {'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower()} return self.client.get(params=params) def create(self, body): return self.client.post(data=body) def get(self, id, fields=[], include_fields=True): params = {'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower()} return self.client.get(id=id, params=params) def delete(self, id): return self.client.delete(id=id) def update(self, id, body): return self.client.patch(id=id, data=body)
from .rest import RestClient class Client(object): """Docstring for Client. """ def __init__(self, domain, jwt_token): url = 'https://%s/api/v2/clients' % domain self.client = RestClient(endpoint=url, jwt=jwt_token) def all(self, fields=[], include_fields=True): """Retrieves a list of all client applications. Important: The client_secret and encryption_key attributes can only be retrieved with the read:client_keys scope. Args: fields (list of str, optional): A list of fields to include or exclude from the result (depending on include_fields). Empty to retrieve all fields. include_fields (bool, optional): True if the fields specified are to be include in the result, False otherwise. """ params = {'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower()} return self.client.get(params=params) def create(self, body): return self.client.post(data=body) def get(self, id, fields=[], include_fields=True): params = {'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower()} return self.client.get(id=id, params=params) def delete(self, id): return self.client.delete(id=id) def update(self, id, body): return self.client.patch(id=id, data=body)
Add docstring for Client.all() method
Add docstring for Client.all() method
Python
mit
auth0/auth0-python,auth0/auth0-python
--- +++ @@ -11,6 +11,20 @@ self.client = RestClient(endpoint=url, jwt=jwt_token) def all(self, fields=[], include_fields=True): + """Retrieves a list of all client applications. + + Important: The client_secret and encryption_key attributes can only be + retrieved with the read:client_keys scope. + + Args: + fields (list of str, optional): A list of fields to include or + exclude from the result (depending on include_fields). Empty to + retrieve all fields. + + include_fields (bool, optional): True if the fields specified are + to be include in the result, False otherwise. + """ + params = {'fields': ','.join(fields) or None, 'include_fields': str(include_fields).lower()}
e5a0fcb1fac87ea23bf032bfb266f5eea89d4c21
pyranha/__init__.py
pyranha/__init__.py
# Copyright (c) 2012 John Reese # Licensed under the MIT License from __future__ import absolute_import, division engine = None ui = None def async_engine_command(command, network=None, params=None): """Send a command to the current backend engine.""" return engine.async_command(command, network, params) def async_ui_message(message_type, network=None, content=None): """Send a message to the current frontend user interface.""" return ui.async_message(message_type, network, content) def start(frontend='stdout'): """Initialize both the backend and frontend, and wait for them to mutually exit.""" global engine global ui import signal def sigint(signum, frame): print 'stopping' if engine: engine.stop() if ui: ui.stop() signal.signal(signal.SIGINT, sigint) frontend = frontend.lower() if frontend == 'stdout': from pyranha.ui.stdout import StdoutUI ui = StdoutUI() elif frontend == 'gtk': from pyranha.ui.gtk import GtkUI ui = GtkUI() else: raise Exception('unsupported frontend type "{0}"'.format(frontend)) from pyranha.engine.engine import Engine engine = Engine() engine.start() ui.start() while engine.is_alive(): engine.join() while ui.is_alive(): ui.join()
# Copyright (c) 2012 John Reese # Licensed under the MIT License from __future__ import absolute_import, division engine = None ui = None def async_engine_command(command, network=None, params=None): """Send a command to the current backend engine.""" return engine.async_command(command, network, params) def async_ui_message(message_type, network=None, content=None): """Send a message to the current frontend user interface.""" return ui.async_message(message_type, network, content) def start(frontend='gtk'): """Initialize both the backend and frontend, and wait for them to mutually exit.""" global engine global ui import signal def sigint(signum, frame): print 'stopping' if engine: engine.stop() if ui: ui.stop() signal.signal(signal.SIGINT, sigint) frontend = frontend.lower() if frontend == 'stdout': from pyranha.ui.stdout import StdoutUI ui = StdoutUI() elif frontend == 'gtk': from pyranha.ui.gtk import GtkUI ui = GtkUI() else: raise Exception('unsupported frontend type "{0}"'.format(frontend)) from pyranha.engine.engine import Engine engine = Engine() engine.start() ui.start() while engine.is_alive(): engine.join() while ui.is_alive(): ui.join()
Use gtk ui by default
Use gtk ui by default
Python
mit
jreese/pyranha
--- +++ @@ -14,7 +14,7 @@ """Send a message to the current frontend user interface.""" return ui.async_message(message_type, network, content) -def start(frontend='stdout'): +def start(frontend='gtk'): """Initialize both the backend and frontend, and wait for them to mutually exit.""" global engine global ui
c7af37a407a2cab7319f910830c6149addcde7d1
djangoautoconf/tastypie_utils.py
djangoautoconf/tastypie_utils.py
from tastypie.authorization import DjangoAuthorization from tastypie.resources import ModelResource from req_with_auth import DjangoUserAuthentication def create_tastypie_resource_class(class_inst): resource_class = type(class_inst.__name__ + "Resource", (ModelResource, ), { "Meta": type("Meta", (), { "queryset": class_inst.objects.all(), "resource_name": 'equip', "authentication": DjangoUserAuthentication(), "authorization": DjangoAuthorization(), }) }) return resource_class
from tastypie.authorization import DjangoAuthorization from tastypie.resources import ModelResource from req_with_auth import DjangoUserAuthentication import re def class_name_to_low_case(class_name): s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', class_name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() def create_tastypie_resource_class(class_inst, resource_name=None): if resource_name is None: resource_name = class_name_to_low_case(class_inst.__name__) resource_class = type(class_inst.__name__ + "Resource", (ModelResource, ), { "Meta": type("Meta", (), { "queryset": class_inst.objects.all(), "resource_name": resource_name, "authentication": DjangoUserAuthentication(), "authorization": DjangoAuthorization(), }) }) return resource_class def create_tastypie_resource(class_inst): return create_tastypie_resource_class(class_inst)()
Fix tastypie resource name issue.
Fix tastypie resource name issue.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
--- +++ @@ -1,15 +1,27 @@ from tastypie.authorization import DjangoAuthorization from tastypie.resources import ModelResource from req_with_auth import DjangoUserAuthentication +import re -def create_tastypie_resource_class(class_inst): +def class_name_to_low_case(class_name): + s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', class_name) + return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() + + +def create_tastypie_resource_class(class_inst, resource_name=None): + if resource_name is None: + resource_name = class_name_to_low_case(class_inst.__name__) resource_class = type(class_inst.__name__ + "Resource", (ModelResource, ), { "Meta": type("Meta", (), { "queryset": class_inst.objects.all(), - "resource_name": 'equip', + "resource_name": resource_name, "authentication": DjangoUserAuthentication(), "authorization": DjangoAuthorization(), }) }) return resource_class + + +def create_tastypie_resource(class_inst): + return create_tastypie_resource_class(class_inst)()
b60fabed64fc926066fc41f59a637dbfe2ac0bf9
emstrack/forms.py
emstrack/forms.py
from django.contrib.gis.forms import widgets class LeafletPointWidget(widgets.BaseGeometryWidget): template_name = 'leaflet/leaflet.html' class Media: css = { 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css', 'leaflet/css/location_form.css', 'leaflet/css/LeafletWidget.css') } js = ( 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.js', 'leaflet/js/LeafletWidget.js' ) def render(self, name, value, attrs=None): # add point if value: attrs.update({ 'point': { 'x': value.x, 'y': value.y, 'z': value.z, 'srid': value.srid } }) return super().render(name, value, attrs)
from django.contrib.gis.forms import widgets class LeafletPointWidget(widgets.BaseGeometryWidget): template_name = 'leaflet/leaflet.html' class Media: css = { 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css', 'leaflet/css/location_form.css', 'leaflet/css/LeafletWidget.css') } js = ( 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js', 'leaflet/js/LeafletWidget.js' ) def render(self, name, value, attrs=None): # add point if value: attrs.update({ 'point': { 'x': value.x, 'y': value.y, 'z': value.z, 'srid': value.srid } }) return super().render(name, value, attrs)
Update leaflet request to be over https
Update leaflet request to be over https
Python
bsd-3-clause
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
--- +++ @@ -5,12 +5,12 @@ class Media: css = { - 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css', + 'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css', 'leaflet/css/location_form.css', 'leaflet/css/LeafletWidget.css') } js = ( - 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.js', + 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js', 'leaflet/js/LeafletWidget.js' )
20d63ba3fa1a9780d4a13c5119ae97a772efb502
teardown_tests.py
teardown_tests.py
#!/usr/bin/env python import os import shutil import sys if not os.environ.get("TEST_NOTEBOOKS"): sys.exit(0) for each in list(sys.argv[1:]) + [ "reg.h5", "reg_sub.h5", "reg_f_f0.h5", "reg_wt.h5", "reg_norm.h5", "reg_dict.h5", "reg_post.h5", "reg_traces.h5", "reg_rois.h5", "reg_proj.h5", "reg_proj.html"]: if os.path.isfile(each): os.remove(each) elif os.path.isdir(each): shutil.rmtree(each)
#!/usr/bin/env python import os import shutil import sys if not os.environ.get("TEST_NOTEBOOKS"): sys.exit(0) for each in list(sys.argv[1:]) + [ "reg.h5", "reg_sub.h5", "reg_f_f0.h5", "reg_wt.h5", "reg_norm.h5", "reg_dict.h5", "reg_post.h5", "reg_traces.h5", "reg_rois.h5", "reg_proj.h5", "reg.zarr", "reg_sub.zarr", "reg_f_f0.zarr", "reg_wt.zarr", "reg_norm.zarr", "reg_dict.zarr", "reg_post.zarr", "reg_traces.zarr", "reg_rois.zarr", "reg_proj.zarr", "reg_proj.html"]: if os.path.isfile(each): os.remove(each) elif os.path.isdir(each): shutil.rmtree(each)
Remove test Zarr files after completion.
Remove test Zarr files after completion.
Python
apache-2.0
nanshe-org/nanshe_workflow,DudLab/nanshe_workflow
--- +++ @@ -20,6 +20,16 @@ "reg_traces.h5", "reg_rois.h5", "reg_proj.h5", + "reg.zarr", + "reg_sub.zarr", + "reg_f_f0.zarr", + "reg_wt.zarr", + "reg_norm.zarr", + "reg_dict.zarr", + "reg_post.zarr", + "reg_traces.zarr", + "reg_rois.zarr", + "reg_proj.zarr", "reg_proj.html"]: if os.path.isfile(each): os.remove(each)
b0105f42f13b81741b4be2b52e295b906aa0c144
service/__init__.py
service/__init__.py
import logging from logging import config from flask import Flask import dateutil import dateutil.parser import json from flask_login import LoginManager from config import CONFIG_DICT app = Flask(__name__) app.config.update(CONFIG_DICT) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = '/login' def format_datetime(value): return dateutil.parser.parse(value).strftime("%d %B %Y at %H:%M:%S") def setup_logging(logging_config_file_path): if CONFIG_DICT['LOGGING']: try: with open(logging_config_file_path, 'rt') as file: config = json.load(file) logging.config.dictConfig(config) except IOError as e: raise(Exception('Failed to load logging configuration', e)) app.jinja_env.filters['datetime'] = format_datetime setup_logging(app.config['LOGGING_CONFIG_FILE_PATH'])
import logging from logging import config from flask import Flask import dateutil import dateutil.parser import json from flask_login import LoginManager from config import CONFIG_DICT app = Flask(__name__) app.config.update(CONFIG_DICT) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = '/login' login_manager.session_protection = "strong" def format_datetime(value): return dateutil.parser.parse(value).strftime("%d %B %Y at %H:%M:%S") def setup_logging(logging_config_file_path): if CONFIG_DICT['LOGGING']: try: with open(logging_config_file_path, 'rt') as file: config = json.load(file) logging.config.dictConfig(config) except IOError as e: raise(Exception('Failed to load logging configuration', e)) app.jinja_env.filters['datetime'] = format_datetime setup_logging(app.config['LOGGING_CONFIG_FILE_PATH'])
Set cookie protection mode to strong
Set cookie protection mode to strong
Python
mit
LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend,LandRegistry/digital-register-frontend
--- +++ @@ -15,6 +15,7 @@ login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = '/login' +login_manager.session_protection = "strong" def format_datetime(value):
58b5a991d91101b9149014def8e93fe70852ae32
measurement/views.py
measurement/views.py
from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response class CurrentPatientMeasurements(APIView): permission_classes = (IsAuthenticated, IsPatient,) def get(self, request, format=None): type = self.request.QUERY_PARAMS.get('type', None) if type is None: raise ParseError(detail="Query string 'type' is not specified") if not type in ['A', 'O', 'P', 'T']: raise ParseError(detail="type must be one of the following values: 'A', 'O', 'P', 'T'") patient = request.user.patient if 'A' == type and not patient.activity_access: raise PermissionDenied() if 'O' == type and not patient.o2_access: raise PermissionDenied() if 'P' == type and not patient.pulse_access: raise PermissionDenied() if 'T' == type and not patient.temperature_access: raise PermissionDenied() queryset = Measurement.objects.filter(patient__id=patient.id, type=type) serializer = MeasurementGraphSeriesSerializer(queryset, many=True) return Response(serializer.data)
from .models import Measurement from rest_framework import viewsets from graph.serializers import MeasurementGraphSeriesSerializer from rest_framework.exceptions import ParseError from api.permissions import IsPatient from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response from patient.serializers import PatientGraphSeriesSerializer class CurrentPatientMeasurements(APIView): permission_classes = (IsAuthenticated, IsPatient,) def get(self, request, format=None): type = self.request.QUERY_PARAMS.get('type', None) if type is None: raise ParseError(detail="Query string 'type' is not specified") if not type in ['A', 'O', 'P', 'T']: raise ParseError(detail="type must be one of the following values: 'A', 'O', 'P', 'T'") patient = request.user.patient if 'A' == type and not patient.activity_access: raise PermissionDenied() if 'O' == type and not patient.o2_access: raise PermissionDenied() if 'P' == type and not patient.pulse_access: raise PermissionDenied() if 'T' == type and not patient.temperature_access: raise PermissionDenied() serializer = PatientGraphSeriesSerializer(instance=patient, context={'type': type}) return Response(serializer.data)
Update measurements endpoint of current patient
Update measurements endpoint of current patient
Python
mit
sigurdsa/angelika-api
--- +++ @@ -7,6 +7,7 @@ from rest_framework.views import APIView from django.core.exceptions import PermissionDenied from rest_framework.response import Response +from patient.serializers import PatientGraphSeriesSerializer class CurrentPatientMeasurements(APIView): @@ -29,6 +30,5 @@ if 'T' == type and not patient.temperature_access: raise PermissionDenied() - queryset = Measurement.objects.filter(patient__id=patient.id, type=type) - serializer = MeasurementGraphSeriesSerializer(queryset, many=True) + serializer = PatientGraphSeriesSerializer(instance=patient, context={'type': type}) return Response(serializer.data)
68086a879b13040d62a8958bcb4839d6661f9d0c
knowledge_repo/app/auth_providers/ldap.py
knowledge_repo/app/auth_providers/ldap.py
from flask import request, render_template, redirect, url_for from ldap3 import Server, Connection, ALL from ldap3.core.exceptions import LDAPSocketOpenError from ..models import User from ..auth_provider import KnowledgeAuthProvider class LdapAuthProvider(KnowledgeAuthProvider): _registry_keys = ['ldap'] def init(self): if not self.app.config.get('LDAP_SERVER'): raise RuntimeError( "Use of LDAP authentication requires specification of the LDAP_SERVER configuration variable.") self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL) def prompt(self): return render_template('auth-login-form.html', skip_password=False) def authorize(self): user = self.get_user() if user is None: raise RuntimeError("No such user or invalid credentials") if self.validate(user) is False: return render_template("auth-login-form.html", error_message="Uh-oh, it looks like something in your credentials was wrong...") self._perform_login(user) return redirect(url_for('index.render_feed')) def validate(self, user): userdn = self.app.config['LDAP_USERDN_SCHEMA'].format(user_id=user.identifier) password = request.form['password'] conn = Connection(self.server, user=userdn, password=password) return conn.bind() def get_user(self): return User(identifier=request.form['username'])
from ..auth_provider import KnowledgeAuthProvider from ..models import User from flask import ( redirect, render_template, request, url_for, ) from ldap3 import Server, Connection, ALL class LdapAuthProvider(KnowledgeAuthProvider): _registry_keys = ['ldap'] def init(self): if not self.app.config.get('LDAP_SERVER'): raise RuntimeError( "Use of LDAP authentication requires specification of the LDAP_SERVER configuration variable.") self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL) def prompt(self): return render_template('auth-login-form.html', skip_password=False) def authorize(self): user = self.get_user() if user is None: raise RuntimeError("No such user or invalid credentials") if self.validate(user) is False: return render_template("auth-login-form.html", error_message="Uh-oh, it looks like something in your credentials was wrong...") self._perform_login(user) return redirect(url_for('index.render_feed')) def validate(self, user): userdn = self.app.config['LDAP_USERDN_SCHEMA'].format(user_id=user.identifier) password = request.form['password'] conn = Connection(self.server, user=userdn, password=password) return conn.bind() def get_user(self): return User(identifier=request.form['username'])
Sort import statements in another file
Sort import statements in another file
Python
apache-2.0
airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo
--- +++ @@ -1,9 +1,12 @@ -from flask import request, render_template, redirect, url_for +from ..auth_provider import KnowledgeAuthProvider +from ..models import User +from flask import ( + redirect, + render_template, + request, + url_for, +) from ldap3 import Server, Connection, ALL -from ldap3.core.exceptions import LDAPSocketOpenError - -from ..models import User -from ..auth_provider import KnowledgeAuthProvider class LdapAuthProvider(KnowledgeAuthProvider):
1c6b06f240d4388b3e140e3d9ab610711616f539
src/python/expedient/clearinghouse/resources/models.py
src/python/expedient/clearinghouse/resources/models.py
''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice class Resource(Extendable): ''' Generic model of a resource. @param aggregate: The L{Aggregate} that controls/owns this resource @type aggregate: L{models.ForeignKey} to L{Aggregate} @param name: A human-readable name for the resource @type name: L{str} ''' name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) status_change_timestamp = models.DateTimeField(editable=False) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice. ''' resource = models.ForeignKey( Resource, verbose_name="Resource this sliver is part of") slice = models.ForeignKey( Slice, verbose_name="Slice this sliver is part of")
''' @author: jnaous ''' from django.db import models from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice from datetime import datetime class Resource(Extendable): ''' Generic model of a resource. @param aggregate: The L{Aggregate} that controls/owns this resource @type aggregate: L{models.ForeignKey} to L{Aggregate} @param name: A human-readable name for the resource @type name: L{str} ''' name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) status_change_timestamp = models.DateTimeField( editable=False, auto_now_add=True) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") def update_timestamp(self): self.status_change_timestamp = datetime.now() def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice. ''' resource = models.ForeignKey( Resource, verbose_name="Resource this sliver is part of") slice = models.ForeignKey( Slice, verbose_name="Slice this sliver is part of")
Add functions to manage status change timestamp better
Add functions to manage status change timestamp better
Python
bsd-3-clause
avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf
--- +++ @@ -5,6 +5,7 @@ from expedient.clearinghouse.aggregate.models import Aggregate from expedient.common.extendable.models import Extendable from expedient.clearinghouse.slice.models import Slice +from datetime import datetime class Resource(Extendable): ''' @@ -18,16 +19,20 @@ name = models.CharField(max_length=200) available = models.BooleanField("Available", default=True, editable=False) - status_change_timestamp = models.DateTimeField(editable=False) + status_change_timestamp = models.DateTimeField( + editable=False, auto_now_add=True) aggregate = models.ForeignKey( Aggregate, verbose_name="Aggregate the resource belongs to") slice_set = models.ManyToManyField( Slice, through="Sliver", verbose_name="Slices this resource is used in") + def update_timestamp(self): + self.status_change_timestamp = datetime.now() + def __unicode__(self): return u"Resource: %s belonging to aggregate %s." % ( self.name, self.aggregate) - + class Sliver(Extendable): ''' Information on the reservation of a particular resource for a slice.
570264014456ea0405af28feb92af7639fb7b7e3
metaopt/invoker/util/determine_package.py
metaopt/invoker/util/determine_package.py
""" Utility that detects the package of a given object. """ from __future__ import division, print_function, with_statement import inspect import os def determine_package(some_object): """ Resolves a call by object to a call by package. - Determine absolute package name of the given object. - When the task gets executed, the worker process will import it. """ # expand the module's path to an absolute import filename = inspect.getsourcefile(some_object) module_path, module_filename = os.path.split(filename) module_name, _ = os.path.splitext(module_filename) prefix = [] for directory in module_path.split(os.sep)[::-1]: prefix.append(directory) candidate = ".".join(prefix[::-1] + [module_name]) try: __import__(name=candidate, globals=globals(), locals=locals(), fromlist=[], level=0) some_object = candidate return some_object except ImportError: pass raise ImportError("Could not determine the package of the given " + "object. This should not happen.")
""" Utility that detects the package of a given object. """ from __future__ import division, print_function, with_statement import inspect import os def determine_package(some_object): """ Resolves a call by object to a call by package. - Determine absolute package name of the given object. - When the task gets executed, the worker process will import it. """ # expand the module's path to an absolute import filename = inspect.getsourcefile(some_object) module_path, module_filename = os.path.split(filename) module_name, _ = os.path.splitext(module_filename) prefix = [] for directory in module_path.split(os.sep)[::-1]: prefix.append(directory) candidate = ".".join(prefix[::-1] + [module_name]) if candidate.startswith("."): candidate = candidate[1:] try: __import__(name=candidate, globals=globals(), locals=locals(), fromlist=[], level=0) some_object = candidate return some_object except ImportError: pass raise ImportError("Could not determine the package of the given " + "object. This should not happen.")
Fix a bug (?) in detmine_package
Fix a bug (?) in detmine_package Canditates have their first character removed if it is ".".
Python
bsd-3-clause
cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt
--- +++ @@ -22,6 +22,10 @@ for directory in module_path.split(os.sep)[::-1]: prefix.append(directory) candidate = ".".join(prefix[::-1] + [module_name]) + + if candidate.startswith("."): + candidate = candidate[1:] + try: __import__(name=candidate, globals=globals(), locals=locals(), fromlist=[], level=0)
5ee2d734ac3279e142ba7df561ee13c64f236cb8
tests/testtrim.py
tests/testtrim.py
from __future__ import print_function, division from cutadapt.seqio import ColorspaceSequence from cutadapt.adapters import ColorspaceAdapter, PREFIX from cutadapt.scripts.cutadapt import AdapterCutter def test_cs_5p(): read = ColorspaceSequence("name", "0123", "DEFG", "T") adapter = ColorspaceAdapter("CG", PREFIX, 0.1) cutter = AdapterCutter([adapter]) matches = cutter.find_matches(read) # no assertion here, just make sure the above code runs without # an exception
from __future__ import print_function, division from cutadapt.seqio import ColorspaceSequence, Sequence from cutadapt.adapters import Adapter, ColorspaceAdapter, PREFIX, BACK from cutadapt.scripts.cutadapt import AdapterCutter def test_cs_5p(): read = ColorspaceSequence("name", "0123", "DEFG", "T") adapter = ColorspaceAdapter("CG", PREFIX, 0.1) cutter = AdapterCutter([adapter]) matches = cutter.find_matches(read) # no assertion here, just make sure the above code runs without # an exception def test_statistics(): read = Sequence('name', 'AAAACCCCGGGG') adapters = [Adapter('CCCC', BACK, 0.1), Adapter('TTTT', BACK, 0.1)] cutter = AdapterCutter(adapters, times=3) trimmed_read = cutter(read) # TODO make this a lot simpler trimmed_bp = 0 for adapter in adapters: for d in (adapter.lengths_front, adapter.lengths_back): trimmed_bp += sum(seqlen * count for (seqlen, count) in d.items()) assert trimmed_bp <= len(read), trimmed_bp
Test for bug: too many trimmed bases reported
Test for bug: too many trimmed bases reported
Python
mit
Chris7/cutadapt,marcelm/cutadapt
--- +++ @@ -1,7 +1,7 @@ from __future__ import print_function, division -from cutadapt.seqio import ColorspaceSequence -from cutadapt.adapters import ColorspaceAdapter, PREFIX +from cutadapt.seqio import ColorspaceSequence, Sequence +from cutadapt.adapters import Adapter, ColorspaceAdapter, PREFIX, BACK from cutadapt.scripts.cutadapt import AdapterCutter def test_cs_5p(): @@ -11,3 +11,16 @@ matches = cutter.find_matches(read) # no assertion here, just make sure the above code runs without # an exception + + +def test_statistics(): + read = Sequence('name', 'AAAACCCCGGGG') + adapters = [Adapter('CCCC', BACK, 0.1), Adapter('TTTT', BACK, 0.1)] + cutter = AdapterCutter(adapters, times=3) + trimmed_read = cutter(read) + # TODO make this a lot simpler + trimmed_bp = 0 + for adapter in adapters: + for d in (adapter.lengths_front, adapter.lengths_back): + trimmed_bp += sum(seqlen * count for (seqlen, count) in d.items()) + assert trimmed_bp <= len(read), trimmed_bp
729cea9ae07f7264b765813cac00e869f66069ff
tools/allBuild.py
tools/allBuild.py
import os import buildFirefox import buildChrome os.chdir(os.path.dirname(os.path.abspath(__file__))) buildFirefox.run() buildChrome.run()
import os import buildFirefox import buildChrome os.chdir(os.path.dirname(os.path.abspath(__file__))) filenames = ['header.js', 'guild_page.js', 'core.js'] with open('tgarmory.js', 'w') as outfile: for fname in filenames: with open(fname) as infile: outfile.write(infile.read()) buildFirefox.run() buildChrome.run()
Prepare for file concat build system
Prepare for file concat build system
Python
mit
ZergRael/tgarmory
--- +++ @@ -3,5 +3,12 @@ import buildChrome os.chdir(os.path.dirname(os.path.abspath(__file__))) + +filenames = ['header.js', 'guild_page.js', 'core.js'] +with open('tgarmory.js', 'w') as outfile: + for fname in filenames: + with open(fname) as infile: + outfile.write(infile.read()) + buildFirefox.run() buildChrome.run()
b53ebee86c36dfe52e8a11fb8c4f3cec99878fc9
gitlabform/gitlab/merge_requests.py
gitlabform/gitlab/merge_requests.py
from gitlabform.gitlab.core import GitLabCore class GitLabMergeRequests(GitLabCore): def create_mr(self, project_and_group_name, source_branch, target_branch, title, description=None): pid = self._get_project_id(project_and_group_name) data = { "id": pid, "source_branch": source_branch, "target_branch": target_branch, "title": title, "description": description, } return self._make_requests_to_api("projects/%s/merge_requests" % pid, method='POST', data=data, expected_codes=201) def accept_mr(self, project_and_group_name, mr_id): # NOT iid, like API docs suggest! pid = self._get_project_id(project_and_group_name) return self._make_requests_to_api("projects/%s/merge_request/%s/merge" % (pid, mr_id), method='PUT') def get_mrs(self, project_and_group_name): pid = self._get_project_id(project_and_group_name) return self._make_requests_to_api("projects/%s/merge_requests" % pid, paginated=True)
from gitlabform.gitlab.core import GitLabCore class GitLabMergeRequests(GitLabCore): def create_mr(self, project_and_group_name, source_branch, target_branch, title, description=None): pid = self._get_project_id(project_and_group_name) data = { "id": pid, "source_branch": source_branch, "target_branch": target_branch, "title": title, "description": description, } return self._make_requests_to_api("projects/%s/merge_requests" % pid, method='POST', data=data, expected_codes=201) def accept_mr(self, project_and_group_name, mr_id): # NOT iid, like API docs suggest! pid = self._get_project_id(project_and_group_name) return self._make_requests_to_api("projects/%s/merge_request/%s/merge" % (pid, mr_id), method='PUT') def update_mr(self, project_and_group_name, mr_id, data): # NOT iid, like API docs suggest! pid = self._get_project_id(project_and_group_name) self._make_requests_to_api("projects/%s/merge_request/%s" % (pid, mr_id), method='PUT', data=data) def get_mrs(self, project_and_group_name): pid = self._get_project_id(project_and_group_name) return self._make_requests_to_api("projects/%s/merge_requests" % pid, paginated=True)
Add update MR method (for internal use for now)
Add update MR method (for internal use for now)
Python
mit
egnyte/gitlabform,egnyte/gitlabform
--- +++ @@ -19,6 +19,10 @@ pid = self._get_project_id(project_and_group_name) return self._make_requests_to_api("projects/%s/merge_request/%s/merge" % (pid, mr_id), method='PUT') + def update_mr(self, project_and_group_name, mr_id, data): # NOT iid, like API docs suggest! + pid = self._get_project_id(project_and_group_name) + self._make_requests_to_api("projects/%s/merge_request/%s" % (pid, mr_id), method='PUT', data=data) + def get_mrs(self, project_and_group_name): pid = self._get_project_id(project_and_group_name) return self._make_requests_to_api("projects/%s/merge_requests" % pid, paginated=True)
badc84447ad6a596317c93e7c393e6021da8a18f
park_api/security.py
park_api/security.py
def file_is_allowed(file): t = file.endswith(".py") t &= "__Init__" not in file.title() t &= "Sample_City" not in file.title() return t
def file_is_allowed(file): t = file.endswith(".py") t &= "__Init__" not in file.title() t &= "Sample_City" not in file.title() t &= "Frankfurt" not in file.title() # See offenesdresden/ParkAPI#153 return t
Disable Frankfurt until requests is fixed
Disable Frankfurt until requests is fixed ref #153
Python
mit
offenesdresden/ParkAPI,offenesdresden/ParkAPI
--- +++ @@ -2,4 +2,5 @@ t = file.endswith(".py") t &= "__Init__" not in file.title() t &= "Sample_City" not in file.title() + t &= "Frankfurt" not in file.title() # See offenesdresden/ParkAPI#153 return t
7cf37b966049cfc47ef200ad8ae69763d98185c5
collector/description/normal/L2.py
collector/description/normal/L2.py
from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp from .L1 import phase_description # Normalised distances and L2-normalised (Euclidean norm) collector sets collector_weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized'))
from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp from .L1 import descriptions # Normalised distances and L2-normalised (Euclidean norm) collector sets weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized'))
Update secondary collector description module
Update secondary collector description module
Python
mit
davidfoerster/schema-matching
--- +++ @@ -1,10 +1,10 @@ from __future__ import absolute_import import math, utilities.operator from ...weight import WeightDict, normalize_exp -from .L1 import phase_description +from .L1 import descriptions # Normalised distances and L2-normalised (Euclidean norm) collector sets -collector_weights = \ +weights = \ WeightDict(normalize_exp, (utilities.operator.square, math.sqrt), tags=('normalized'))
eb57469f1b14dfd5c2e74f2bbb774513e0662a6c
installer/installer_config/forms.py
installer/installer_config/forms.py
from django import forms from django.forms.models import ModelForm from installer_config.models import EnvironmentProfile, UserChoice class EnvironmentForm(ModelForm): packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=UserChoice.objects.all()) class Meta: model = EnvironmentProfile exclude = ('user',)
from django import forms from django.forms.models import ModelForm from installer_config.models import EnvironmentProfile, UserChoice class EnvironmentForm(ModelForm): choices = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=UserChoice.objects.all()) class Meta: model = EnvironmentProfile exclude = ('user', 'steps', )
Remove steps from Env Prof form
Remove steps from Env Prof form
Python
mit
alibulota/Package_Installer,ezPy-co/ezpy,alibulota/Package_Installer,ezPy-co/ezpy
--- +++ @@ -4,9 +4,9 @@ class EnvironmentForm(ModelForm): - packages = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, + choices = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=UserChoice.objects.all()) class Meta: model = EnvironmentProfile - exclude = ('user',) + exclude = ('user', 'steps', )
4e94cef9f6617827341af443ac428b9ccc190535
lib/recommend-by-url.py
lib/recommend-by-url.py
# -*- coding: utf-8 -*- from newspaper import Article from goose import Goose import json import sys article = Article(sys.argv[1]) article.download() article.parse() article.nlp() published = '' if article.publish_date: published = article.publish_date.strftime("%Y-%m-%d %H:%M:%S") # Get body with goose g = Goose() goose_article = g.extract(raw_html=article.html) body = goose_article.cleaned_text summary = goose_article.meta_description # Maybe use https://github.com/xiaoxu193/PyTeaser if not summary: summary = article.summary if not body or len(body) < len(article.text): body = article.text json_str = json.dumps({ 'author': ", ".join(article.authors), 'image': article.top_image, 'keywords': article.keywords, 'published': published, 'summary': summary, 'body': body, 'title': article.title, 'videos': article.movies }, sort_keys=True, ensure_ascii=False) print(json_str)
# -*- coding: utf-8 -*- from newspaper import Article from goose import Goose import requests import json import sys article = Article(sys.argv[1]) article.download() if not article.html: r = requests.get(sys.argv[1], verify=False, headers={ 'User-Agent': 'Mozilla/5.0' }) article.set_html(r.text) article.parse() article.nlp() published = '' if article.publish_date: published = article.publish_date.strftime("%Y-%m-%d %H:%M:%S") # Get body with goose g = Goose() goose_article = g.extract(raw_html=article.html) body = goose_article.cleaned_text summary = goose_article.meta_description # Maybe use https://github.com/xiaoxu193/PyTeaser if not summary: summary = article.summary if not body or len(body) < len(article.text): body = article.text json_str = json.dumps({ 'author': ", ".join(article.authors), 'image': article.top_image, 'keywords': article.keywords, 'published': published, 'summary': summary, 'body': body, 'title': article.title, 'videos': article.movies }, sort_keys=True, ensure_ascii=False) print(json_str)
Improve reliablity of python article fetcher
Improve reliablity of python article fetcher
Python
mit
lateral/feed-feeder,lateral/feed-feeder,lateral/feed-feeder,lateral/feed-feeder
--- +++ @@ -1,12 +1,17 @@ # -*- coding: utf-8 -*- from newspaper import Article from goose import Goose +import requests import json import sys article = Article(sys.argv[1]) article.download() +if not article.html: + r = requests.get(sys.argv[1], verify=False, headers={ 'User-Agent': 'Mozilla/5.0' }) + article.set_html(r.text) + article.parse() article.nlp()
c6de39b01b8eac10edbb6f95d86285075bf8a9ab
conanfile.py
conanfile.py
from conans import ConanFile class ArgsConan(ConanFile): name = "cfgfile" version = "0.2.8.2" url = "https://github.com/igormironchik/cfgfile.git" license = "MIT" description = "Header-only library for reading/saving configuration files with schema defined in sources." exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp" def package(self): self.copy("COPYING", src=".", dst=".") self.copy("*", src="cfgfile", dst="cfgfile") self.copy("*", src="generator", dst="generator") self.copy("*.hpp", src="3rdparty/Args/Args", dst="3rdparty/Args/Args") def package_info(self): self.cpp_info.includedirs = ["."]
from conans import ConanFile, CMake class ArgsConan(ConanFile): name = "cfgfile" version = "0.2.8.2" url = "https://github.com/igormironchik/cfgfile.git" license = "MIT" description = "Header-only library for reading/saving configuration files with schema defined in sources." exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp" def build(self): cmake = CMake(self) cmake.configure(source_folder="generator") cmake.build() def package(self): self.copy("COPYING", src=".", dst=".") self.copy("*", src="cfgfile", dst="cfgfile") self.copy("*", src="generator", dst="generator") self.copy("*.hpp", src="3rdparty/Args/Args", dst="3rdparty/Args/Args") def package_info(self): self.cpp_info.includedirs = ["."]
Add build step into Conan recipe.
Add build step into Conan recipe.
Python
mit
igormironchik/cfgfile
--- +++ @@ -1,4 +1,4 @@ -from conans import ConanFile +from conans import ConanFile, CMake class ArgsConan(ConanFile): @@ -8,6 +8,11 @@ license = "MIT" description = "Header-only library for reading/saving configuration files with schema defined in sources." exports = "cfgfile/*", "COPYING", "generator/*", "3rdparty/Args/Args/*.hpp" + + def build(self): + cmake = CMake(self) + cmake.configure(source_folder="generator") + cmake.build() def package(self): self.copy("COPYING", src=".", dst=".")
222e2a70f9c2d4ce7cb4a26d717c6bcce1e3f344
tests/utils.py
tests/utils.py
import os import pytest from tests.consts import examples_path from valohai_yaml import parse def _load_config(filename, roundtrip): with open(os.path.join(examples_path, filename), 'r') as infp: config = parse(infp) if roundtrip: config = parse(config.serialize()) return config def config_fixture(name): @pytest.fixture(params=[False, True]) def _config_fixture(request): return _load_config(name, roundtrip=request.param) return _config_fixture
import os import pytest from tests.consts import examples_path from valohai_yaml import parse def _load_config(filename, roundtrip): with open(os.path.join(examples_path, filename), 'r') as infp: config = parse(infp) if roundtrip: config = parse(config.serialize()) return config def config_fixture(name): @pytest.fixture(params=[False, True], ids=['direct', 'roundtrip']) def _config_fixture(request): return _load_config(name, roundtrip=request.param) return _config_fixture
Add nicer ids for tests
Add nicer ids for tests
Python
mit
valohai/valohai-yaml
--- +++ @@ -15,7 +15,7 @@ def config_fixture(name): - @pytest.fixture(params=[False, True]) + @pytest.fixture(params=[False, True], ids=['direct', 'roundtrip']) def _config_fixture(request): return _load_config(name, roundtrip=request.param)
fa9e488c3fa008fa2c9b08a787ea9c2655bd3d02
tests/test_discuss.py
tests/test_discuss.py
import pytest from web_test_base import * class TestIATIDiscuss(WebTestBase): requests_to_load = { 'IATI Discuss': { 'url': 'http://discuss.iatistandard.org/' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org/" in result
import pytest from web_test_base import * class TestIATIDiscuss(WebTestBase): requests_to_load = { 'IATI Discuss': { 'url': 'http://discuss.iatistandard.org/' } , 'IATI Discuss Welcome Thread': { 'url': 'http://discuss.iatistandard.org/t/welcome-to-iati-discuss/6' } } def test_contains_links(self, loaded_request): """ Test that each page contains links to the defined URLs. """ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org/" in result @pytest.mark.parametrize("target_request", ["IATI Discuss Welcome Thread"]) def test_welcome_thread_welcomingness(self, target_request): """ Tests that the Welcome Thread is sufficiently welcoming. """ req = self.loaded_request_from_test_name(target_request) title_xpath = '/html/head/title' heading_xpath = '//*[@id="main-outlet"]/h1/a' subtitle_xpath = '//*[@id="main-outlet"]/div[1]/div[2]/h1' post_body_xpath = '//*[@id="main-outlet"]/div[1]/div[2]/p' title_text = utility.get_text_from_xpath(req, title_xpath) heading_text = utility.get_text_from_xpath(req, heading_xpath) subtitle_text = utility.get_text_from_xpath(req, subtitle_xpath) post_body_text = utility.get_text_from_xpath(req, post_body_xpath) assert utility.substring_in_list('Welcome to IATI Discuss', title_text) assert utility.substring_in_list('Welcome to IATI Discuss', heading_text) assert utility.substring_in_list('Welcome', subtitle_text) assert utility.substring_in_list('Welcome', post_body_text)
Add test for Discuss Welcome
Add test for Discuss Welcome This ensures the welcome post is sufficiently welcoming. The XPaths are based on the page with Javascript disabled. As such, they will not correctly match if Javascript is enabled.
Python
mit
IATI/IATI-Website-Tests
--- +++ @@ -5,6 +5,9 @@ requests_to_load = { 'IATI Discuss': { 'url': 'http://discuss.iatistandard.org/' + } + , 'IATI Discuss Welcome Thread': { + 'url': 'http://discuss.iatistandard.org/t/welcome-to-iati-discuss/6' } } @@ -15,3 +18,24 @@ result = utility.get_links_from_page(loaded_request) assert "http://iatistandard.org/" in result + + @pytest.mark.parametrize("target_request", ["IATI Discuss Welcome Thread"]) + def test_welcome_thread_welcomingness(self, target_request): + """ + Tests that the Welcome Thread is sufficiently welcoming. + """ + req = self.loaded_request_from_test_name(target_request) + title_xpath = '/html/head/title' + heading_xpath = '//*[@id="main-outlet"]/h1/a' + subtitle_xpath = '//*[@id="main-outlet"]/div[1]/div[2]/h1' + post_body_xpath = '//*[@id="main-outlet"]/div[1]/div[2]/p' + + title_text = utility.get_text_from_xpath(req, title_xpath) + heading_text = utility.get_text_from_xpath(req, heading_xpath) + subtitle_text = utility.get_text_from_xpath(req, subtitle_xpath) + post_body_text = utility.get_text_from_xpath(req, post_body_xpath) + + assert utility.substring_in_list('Welcome to IATI Discuss', title_text) + assert utility.substring_in_list('Welcome to IATI Discuss', heading_text) + assert utility.substring_in_list('Welcome', subtitle_text) + assert utility.substring_in_list('Welcome', post_body_text)
0d6d1e735e3c149f6adec370832949a81b930a56
tests/test_driller.py
tests/test_driller.py
import nose import driller import logging l = logging.getLogger("driller.tests.test_driller") import os bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) def test_drilling_cgc(): ''' test drilling on the cgc binary, palindrome. ''' binary = "cgc_scored_event_1/cgc/0b32aa01_01" # fuzzbitmap says every transition is worth satisfying d = driller.Driller(os.path.join(bin_location, binary), "AAAA", "\xff"*65535, "whatever~") new_inputs = d.drill() nose.tools.assert_equal(len(new_inputs), 7) # make sure driller produced a new input which hits the easter egg nose.tools.assert_true(any(filter(lambda x: x[1].startswith('^'), new_inputs))) def run_all(): functions = globals() all_functions = dict(filter((lambda (k, v): k.startswith('test_')), functions.items())) for f in sorted(all_functions.keys()): if hasattr(all_functions[f], '__call__'): all_functions[f]() if __name__ == "__main__": run_all()
import nose import driller import logging l = logging.getLogger("driller.tests.test_driller") import os bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries-private')) def test_drilling_cgc(): ''' test drilling on the cgc binary, palindrome. ''' binary = "cgc_scored_event_1/cgc/0b32aa01_01" # fuzzbitmap says every transition is worth satisfying d = driller.Driller(os.path.join(bin_location, binary), "AAAA", "\xff"*65535, "whatever~") new_inputs = d.drill() nose.tools.assert_equal(len(new_inputs), 7) # make sure driller produced a new input which hits the easter egg nose.tools.assert_true(any(filter(lambda x: x[1].startswith('^'), new_inputs))) def run_all(): functions = globals() all_functions = dict(filter((lambda (k, v): k.startswith('test_')), functions.items())) for f in sorted(all_functions.keys()): if hasattr(all_functions[f], '__call__'): all_functions[f]() if __name__ == "__main__": run_all()
Update binaries path with private repo
Update binaries path with private repo
Python
bsd-2-clause
shellphish/driller
--- +++ @@ -5,7 +5,7 @@ l = logging.getLogger("driller.tests.test_driller") import os -bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries')) +bin_location = str(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../binaries-private')) def test_drilling_cgc(): '''
9ae8283e06b0b72213fc8084909ae9c2c2b3e553
build/android/pylib/gtest/gtest_config.py
build/android/pylib/gtest/gtest_config.py
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Configuration file for android gtest suites.""" # Add new suites here before upgrading them to the stable list below. EXPERIMENTAL_TEST_SUITES = [ 'TestWebKitAPI', 'components_unittests', 'sandbox_linux_unittests', 'webkit_unit_tests', ] # Do not modify this list without approval of an android owner. # This list determines which suites are run by default, both for local # testing and on android trybots running on commit-queue. STABLE_TEST_SUITES = [ 'android_webview_unittests', 'base_unittests', 'cc_unittests', 'content_unittests', 'gpu_unittests', 'ipc_tests', 'media_unittests', 'net_unittests', 'sql_unittests', 'sync_unit_tests', 'ui_unittests', 'unit_tests', 'webkit_compositor_bindings_unittests', ]
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Configuration file for android gtest suites.""" # Add new suites here before upgrading them to the stable list below. EXPERIMENTAL_TEST_SUITES = [ 'TestWebKitAPI', 'sandbox_linux_unittests', 'webkit_unit_tests', ] # Do not modify this list without approval of an android owner. # This list determines which suites are run by default, both for local # testing and on android trybots running on commit-queue. STABLE_TEST_SUITES = [ 'android_webview_unittests', 'base_unittests', 'cc_unittests', 'components_unittests', 'content_unittests', 'gpu_unittests', 'ipc_tests', 'media_unittests', 'net_unittests', 'sql_unittests', 'sync_unit_tests', 'ui_unittests', 'unit_tests', 'webkit_compositor_bindings_unittests', ]
Move component_unittest to android main waterfall and cq
Move component_unittest to android main waterfall and cq These are existing tests that moved to the component_unittest target. They have been running on the FYI bots for a few days without issue. BUG= Android bot script change. Ran through android trybots. NOTRY=true Review URL: https://chromiumcodereview.appspot.com/12092027 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@179263 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
jaruba/chromium.src,fujunwei/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,jaruba/chromium.src,ondra-novak/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,anirudhSK/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,ltilve/chromium,anirudhSK/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk,ondra-novak/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,dushu1203/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,ltilve/chromium,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,anirudhSK/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,jaruba/chromium.src,markYoungH/chromium.src,Just-D/chromium-1,patrickm/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,dednal/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,dednal/chromium.src,dednal/chromium.src,dednal/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,littlstar/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,ltilve/chromium,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,Chilledheart/chromium,mogoweb/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,patrickm/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,anirudhSK/chromium,ondra-novak/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,M4sse/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,Chilledheart/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,ltilve/chromium,littlstar/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,dushu1203/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,M4sse/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,Just-D/chromium-1,dushu1203/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,jaruba/chromium.src,Chilledheart/chromium,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,Jonekee/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src
--- +++ @@ -7,7 +7,6 @@ # Add new suites here before upgrading them to the stable list below. EXPERIMENTAL_TEST_SUITES = [ 'TestWebKitAPI', - 'components_unittests', 'sandbox_linux_unittests', 'webkit_unit_tests', ] @@ -19,6 +18,7 @@ 'android_webview_unittests', 'base_unittests', 'cc_unittests', + 'components_unittests', 'content_unittests', 'gpu_unittests', 'ipc_tests',
f74636d6944b45753d274f6a993678863a368961
tests/test_testapp.py
tests/test_testapp.py
import json import ckanapi import unittest import paste.fixture def wsgi_app(environ, start_response): status = '200 OK' headers = [('Content-type', 'application/json')] path = environ['PATH_INFO'] if path == '/api/action/hello_world': response = {'success': True, 'result': 'how are you?'} elif path == '/api/action/invalid': response = {'success': False, 'error': {'__type': 'Validation Error'}} elif path == '/api/action/echo': response = {'success': True, 'result': json.loads(environ['wsgi.input'].read())['message']} start_response(status, headers) return [json.dumps(response)] class TestTestAPPCKAN(unittest.TestCase): def setUp(self): self.test_app = paste.fixture.TestApp(wsgi_app) self.ckan = ckanapi.TestAppCKAN(self.test_app) def test_simple(self): self.assertEquals( self.ckan.action.hello_world()['result'], 'how are you?') def test_invalid(self): self.assertRaises( ckanapi.ValidationError, self.ckan.action.invalid) def test_data(self): self.assertEquals( self.ckan.action.echo(message='for you')['result'], 'for you') if __name__ == '__main__': unittest.main()
import json import ckanapi import unittest import paste.fixture def wsgi_app(environ, start_response): status = '200 OK' headers = [('Content-type', 'application/json')] path = environ['PATH_INFO'] if path == '/api/action/hello_world': response = {'success': True, 'result': 'how are you?'} elif path == '/api/action/invalid': response = {'success': False, 'error': {'__type': 'Validation Error'}} elif path == '/api/action/echo': response = {'success': True, 'result': json.loads(environ['wsgi.input'].read())['message']} start_response(status, headers) return [json.dumps(response)] class TestTestAPPCKAN(unittest.TestCase): def setUp(self): self.test_app = paste.fixture.TestApp(wsgi_app) self.ckan = ckanapi.TestAppCKAN(self.test_app) def test_simple(self): self.assertEquals( self.ckan.action.hello_world(), 'how are you?') def test_invalid(self): self.assertRaises( ckanapi.ValidationError, self.ckan.action.invalid) def test_data(self): self.assertEquals( self.ckan.action.echo(message='for you'), 'for you') if __name__ == '__main__': unittest.main()
Fix a couple of tests
Fix a couple of tests Fix a couple of tests that were broken by commit 7e068a3.
Python
mit
LaurentGoderre/ckanapi,perceptron-XYZ/ckanapi,xingyz/ckanapi,metaodi/ckanapi,wardi/ckanapi,eawag-rdm/ckanapi
--- +++ @@ -28,16 +28,14 @@ def test_simple(self): self.assertEquals( - self.ckan.action.hello_world()['result'], - 'how are you?') + self.ckan.action.hello_world(), 'how are you?') def test_invalid(self): self.assertRaises( ckanapi.ValidationError, self.ckan.action.invalid) def test_data(self): self.assertEquals( - self.ckan.action.echo(message='for you')['result'], - 'for you') + self.ckan.action.echo(message='for you'), 'for you') if __name__ == '__main__':
210e9a6e6b20f724a6d464b5a1c842c8b71eceae
testsuite/N806_py3.py
testsuite/N806_py3.py
# python3 only #: Okay VAR1, *VAR2, VAR3 = 1, 2, 3 #: Okay [VAR1, *VAR2, VAR3] = (1, 2, 3) #: N806 def extended_unpacking_ok(): Var1, *Var2, Var3 = 1, 2, 3 #: N806 def extended_unpacking_not_ok(): [Var1, *Var2, Var3] = (1, 2, 3) #: Okay def assing_to_unpack_ok(): a, *[b] = 1, 2 #: N806 def assing_to_unpack_not_ok(): a, *[bB] = 1, 2
# python3 only #: Okay VAR1, *VAR2, VAR3 = 1, 2, 3 #: Okay [VAR1, *VAR2, VAR3] = (1, 2, 3) #: N806 def extended_unpacking_not_ok(): Var1, *Var2, Var3 = 1, 2, 3 #: N806 def extended_unpacking_not_ok(): [Var1, *Var2, Var3] = (1, 2, 3) #: Okay def assing_to_unpack_ok(): a, *[b] = 1, 2 #: N806 def assing_to_unpack_not_ok(): a, *[bB] = 1, 2
Fix typo test case name
Fix typo test case name
Python
mit
flintwork/pep8-naming
--- +++ @@ -4,7 +4,7 @@ #: Okay [VAR1, *VAR2, VAR3] = (1, 2, 3) #: N806 -def extended_unpacking_ok(): +def extended_unpacking_not_ok(): Var1, *Var2, Var3 = 1, 2, 3 #: N806 def extended_unpacking_not_ok():
8ae4594d4f4157568db0dc5cad4d07b8f1142218
src/common/utils.py
src/common/utils.py
from passlib.hash import pbkdf2_sha512 class Utils: @staticmethod def hash_password(password): """ Hashes a password using sha512 -> pbkdf2_sha512 encrypted password """ return pbkdf2_sha512.encrypt(password) @staticmethod def check_hashed_password(password, hashed_password): """ Checks the password the user sent matches that of the database. Uses https://en.wikipedia.org/wiki/PBKDF2 """ return pbkdf2_sha512.verify(password, hashed_password)
import re from passlib.hash import pbkdf2_sha512 class Utils: @staticmethod def email_is_valid(email): email_address_matcher = re.compile('^[\w-]+@([\w-]+\.)+[\w]+$') return True if email_address_matcher.match(email) else False @staticmethod def hash_password(password): """ Hashes a password using sha512 -> pbkdf2_sha512 encrypted password """ return pbkdf2_sha512.encrypt(password) @staticmethod def check_hashed_password(password, hashed_password): """ Checks the password the user sent matches that of the database. Uses https://en.wikipedia.org/wiki/PBKDF2 """ return pbkdf2_sha512.verify(password, hashed_password)
Add static method for email address
Add static method for email address
Python
apache-2.0
asimonia/pricing-alerts,asimonia/pricing-alerts
--- +++ @@ -1,6 +1,12 @@ +import re from passlib.hash import pbkdf2_sha512 class Utils: + + @staticmethod + def email_is_valid(email): + email_address_matcher = re.compile('^[\w-]+@([\w-]+\.)+[\w]+$') + return True if email_address_matcher.match(email) else False @staticmethod def hash_password(password):
f4d9e55cf3dbed0cf21661c33a6efbc98093d1f8
paypal.py
paypal.py
#!/usr/bin/env python3 import argparse import csv parser = argparse.ArgumentParser() parser.add_argument('--config', help='path to file containing column header mappings', required=True) parser.add_argument('--csv-file', help='path to CSV file', required=True) parser.add_argument('--skip-headers', help='skip first line of file as headers', action='store_true') args = parser.parse_args() skipped_headers = False with open(args.config, 'r') as config_file: column_headings = config_file.readline().strip() column_headings = column_headings.split() with open(args.csv_file, newline='') as csv_file: csv_reader = csv.DictReader(csv_file, fieldnames=column_headings) print('!Type:Bank') for row in csv_reader: if args.skip_headers and not skipped_headers: skipped_headers = True else: print('D' + row['date']) print('T' + row['gross']) print('P' + row['description']) print('^') # Process fee as separate transaction - PayPal puts it on one line fee = float(row['fee']) if fee < 0 or fee > 0: print('D' + row['date']) print('T' + row['fee']) print('P' + 'PayPal fee') print('^')
#!/usr/bin/env python3 import argparse import csv parser = argparse.ArgumentParser() parser.add_argument('--config', help='path to file containing column header mappings', required=True) parser.add_argument('--csv-file', help='path to CSV file', required=True) parser.add_argument('--skip-headers', help='skip first line of file as headers', action='store_true') args = parser.parse_args() skipped_headers = False with open(args.config, 'r') as config_file: column_headings = config_file.readline().strip() column_headings = column_headings.split() with open(args.csv_file, newline='') as csv_file: csv_reader = csv.DictReader(csv_file, fieldnames=column_headings) print('!Type:Bank') for row in csv_reader: if args.skip_headers and not skipped_headers: skipped_headers = True else: print('D' + row['date']) print('T' + row['gross']) print('P' + row['from_name']) print('M' + row['description']) print('^') # Process fee as separate transaction - PayPal puts it on one line fee = float(row['fee']) if fee < 0 or fee > 0: print('D' + row['date']) print('T' + row['fee']) print('P' + 'PayPal') print('M' + 'PayPal fee') print('^')
Tweak PayPal output to use Payee and Memo fields
Tweak PayPal output to use Payee and Memo fields
Python
mit
pwaring/csv2qif
--- +++ @@ -26,7 +26,8 @@ else: print('D' + row['date']) print('T' + row['gross']) - print('P' + row['description']) + print('P' + row['from_name']) + print('M' + row['description']) print('^') # Process fee as separate transaction - PayPal puts it on one line @@ -35,5 +36,6 @@ if fee < 0 or fee > 0: print('D' + row['date']) print('T' + row['fee']) - print('P' + 'PayPal fee') + print('P' + 'PayPal') + print('M' + 'PayPal fee') print('^')
439cbfbfa6b16fdd0d24f91adb55eb510802ab8c
inbox/ignition.py
inbox/ignition.py
from sqlalchemy import create_engine from inbox.sqlalchemy_ext.util import ForceStrictMode from inbox.config import db_uri, config DB_POOL_SIZE = config.get_required('DB_POOL_SIZE') def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5): engine = create_engine(db_uri(), listeners=[ForceStrictMode()], isolation_level='READ COMMITTED', echo=False, pool_size=pool_size, max_overflow=max_overflow, connect_args={'charset': 'utf8mb4'}) return engine def init_db(): """ Make the tables. This is called only from bin/create-db, which is run during setup. Previously we allowed this to run everytime on startup, which broke some alembic revisions by creating new tables before a migration was run. From now on, we should ony be creating tables+columns via SQLalchemy *once* and all subscequent changes done via migration scripts. """ from inbox.models.base import MailSyncBase engine = main_engine(pool_size=1) MailSyncBase.metadata.create_all(engine)
from sqlalchemy import create_engine from inbox.sqlalchemy_ext.util import ForceStrictMode from inbox.config import db_uri, config DB_POOL_SIZE = config.get_required('DB_POOL_SIZE') def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5): engine = create_engine(db_uri(), listeners=[ForceStrictMode()], isolation_level='READ COMMITTED', echo=False, pool_size=pool_size, pool_recycle=3600, max_overflow=max_overflow, connect_args={'charset': 'utf8mb4'}) return engine def init_db(): """ Make the tables. This is called only from bin/create-db, which is run during setup. Previously we allowed this to run everytime on startup, which broke some alembic revisions by creating new tables before a migration was run. From now on, we should ony be creating tables+columns via SQLalchemy *once* and all subscequent changes done via migration scripts. """ from inbox.models.base import MailSyncBase engine = main_engine(pool_size=1) MailSyncBase.metadata.create_all(engine)
Set pool_recycle to deal with MySQL closing idle connections.
Set pool_recycle to deal with MySQL closing idle connections. See http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#connection-timeouts
Python
agpl-3.0
PriviPK/privipk-sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,closeio/nylas,Eagles2F/sync-engine,EthanBlackburn/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,ErinCall/sync-engine,closeio/nylas,jobscore/sync-engine,EthanBlackburn/sync-engine,nylas/sync-engine,nylas/sync-engine,gale320/sync-engine,gale320/sync-engine,ErinCall/sync-engine,closeio/nylas,Eagles2F/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,wakermahmud/sync-engine,gale320/sync-engine,closeio/nylas,ErinCall/sync-engine,PriviPK/privipk-sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,gale320/sync-engine
--- +++ @@ -12,6 +12,7 @@ isolation_level='READ COMMITTED', echo=False, pool_size=pool_size, + pool_recycle=3600, max_overflow=max_overflow, connect_args={'charset': 'utf8mb4'}) return engine
71324420df350bba5423006a444927e33c1a5ae2
dddp/apps.py
dddp/apps.py
"""Django DDP app config.""" from __future__ import print_function from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured from django.db import DatabaseError from django.db.models import signals from dddp import autodiscover from dddp.models import Connection class DjangoDDPConfig(AppConfig): """Django app config for django-ddp.""" api = None name = 'dddp' verbose_name = 'Django DDP' _in_migration = False def ready(self): """Initialisation for django-ddp (setup lookups and signal handlers).""" if not settings.DATABASES: raise ImproperlyConfigured('No databases configured.') for (alias, conf) in settings.DATABASES.items(): if conf['ENGINE'] != 'django.db.backends.postgresql_psycopg2': raise ImproperlyConfigured( '%r uses %r: django-ddp only works with PostgreSQL.' % ( alias, conf['backend'], ) ) self.api = autodiscover() self.api.ready()
"""Django DDP app config.""" from __future__ import print_function from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured from dddp import autodiscover class DjangoDDPConfig(AppConfig): """Django app config for django-ddp.""" api = None name = 'dddp' verbose_name = 'Django DDP' _in_migration = False def ready(self): """Initialisation for django-ddp (setup lookups and signal handlers).""" if not settings.DATABASES: raise ImproperlyConfigured('No databases configured.') for (alias, conf) in settings.DATABASES.items(): if conf['ENGINE'] != 'django.db.backends.postgresql_psycopg2': raise ImproperlyConfigured( '%r uses %r: django-ddp only works with PostgreSQL.' % ( alias, conf['backend'], ) ) self.api = autodiscover() self.api.ready()
Remove unused imports from AppConfig module.
Remove unused imports from AppConfig module.
Python
mit
commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp,commoncode/django-ddp,django-ddp/django-ddp
--- +++ @@ -4,11 +4,8 @@ from django.apps import AppConfig from django.conf import settings, ImproperlyConfigured -from django.db import DatabaseError -from django.db.models import signals from dddp import autodiscover -from dddp.models import Connection class DjangoDDPConfig(AppConfig):
0f0d404f36115d6410b3ba5eed9e9f9f2fb2461f
carnetdumaker/context_processors.py
carnetdumaker/context_processors.py
""" Extra context processors for the CarnetDuMaker app. """ from django.contrib.sites.shortcuts import get_current_site from django.utils.translation import ugettext_lazy as _ def app_constants(request): """ Constants context processor. :param request: the current request. :return: All constants for the app. """ site = get_current_site(request) return { 'APP': { 'TITLE': _('Carnet du maker - L\'esprit Do It Yourself'), 'TITLE_SHORT': _('Carnet du maker'), 'AUTHOR': 'Fabien Batteix', 'COPYRIGHT': _('TamiaLab 2015'), 'DESCRIPTION': _('L\'esprit du Do It Yourself'), 'TWITTER_USERNAME': 'carnetdumaker', 'GOOGLE_SITE_VERIFICATION_CODE': '', # TODO 'TWITTER_ACCOUNT_ID': '3043075520', 'FACEBOOK_URL': '', # TODO }, 'SITE': { 'NAME': site.name, 'DOMAIN': site.domain, 'PROTO': 'https' if request.is_secure() else 'http', 'CURRENT_URL': request.get_full_path(), } }
""" Extra context processors for the CarnetDuMaker app. """ from django.contrib.sites.shortcuts import get_current_site from django.utils.translation import ugettext_lazy as _ def app_constants(request): """ Constants context processor. :param request: the current request. :return: All constants for the app. """ site = get_current_site(request) return { 'APP': { 'TITLE': _('Carnet du maker - L\'esprit Do It Yourself'), 'TITLE_SHORT': _('Carnet du maker'), 'AUTHOR': 'Fabien Batteix', 'COPYRIGHT': _('TamiaLab 2015'), 'DESCRIPTION': _('L\'esprit du Do It Yourself'), 'TWITTER_USERNAME': 'carnetdumaker', 'GOOGLE_SITE_VERIFICATION_CODE': 't3KwbPbJCHz-enFYH50Hcd8PDN8NWWC9gCMx7uTjhpQ', 'TWITTER_ACCOUNT_ID': '3043075520', 'FACEBOOK_URL': 'https://www.facebook.com/CarnetDuMaker/', }, 'SITE': { 'NAME': site.name, 'DOMAIN': site.domain, 'PROTO': 'https' if request.is_secure() else 'http', 'CURRENT_URL': request.get_full_path(), } }
Add missing facebook and google verif codes
Add missing facebook and google verif codes
Python
agpl-3.0
TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker
--- +++ @@ -21,9 +21,9 @@ 'COPYRIGHT': _('TamiaLab 2015'), 'DESCRIPTION': _('L\'esprit du Do It Yourself'), 'TWITTER_USERNAME': 'carnetdumaker', - 'GOOGLE_SITE_VERIFICATION_CODE': '', # TODO + 'GOOGLE_SITE_VERIFICATION_CODE': 't3KwbPbJCHz-enFYH50Hcd8PDN8NWWC9gCMx7uTjhpQ', 'TWITTER_ACCOUNT_ID': '3043075520', - 'FACEBOOK_URL': '', # TODO + 'FACEBOOK_URL': 'https://www.facebook.com/CarnetDuMaker/', }, 'SITE': { 'NAME': site.name,
b8f9b2664f8782a028ce27a361f2a7a28eb925aa
cloudenvy/commands/envy_snapshot.py
cloudenvy/commands/envy_snapshot.py
from cloudenvy.envy import Envy class EnvySnapshot(object): """Create a snapshot of an ENVy.""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('snapshot', help='snapshot help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='Specify custom name for an ENVy.') return subparser #TODO(jakedahn): The entire UX for this needs to be talked about, refer to # https://github.com/bcwaldon/cloudenvy/issues/27 for any # discussion, if you're curious. def run(self, config, args): envy = Envy(config) envy.snapshot('%s-snapshot' % envy.name)
from cloudenvy.envy import Envy class EnvySnapshot(object): """Create a snapshot of an ENVy.""" def __init__(self, argparser): self._build_subparser(argparser) def _build_subparser(self, subparsers): subparser = subparsers.add_parser('snapshot', help='snapshot help') subparser.set_defaults(func=self.run) subparser.add_argument('-n', '--name', action='store', default='', help='Specify custom name for an ENVy.') return subparser def run(self, config, args): envy = Envy(config) envy.snapshot('%s-snapshot' % envy.name)
Remove out-of-date comment about snapshot UX
Remove out-of-date comment about snapshot UX
Python
apache-2.0
cloudenvy/cloudenvy
--- +++ @@ -16,9 +16,6 @@ return subparser - #TODO(jakedahn): The entire UX for this needs to be talked about, refer to - # https://github.com/bcwaldon/cloudenvy/issues/27 for any - # discussion, if you're curious. def run(self, config, args): envy = Envy(config) envy.snapshot('%s-snapshot' % envy.name)
b0fef4ed92cde72305a2d85f3e96adde93f82547
tests/test_py35/test_resp.py
tests/test_py35/test_resp.py
import pytest import aiohttp from aiohttp import web @pytest.mark.run_loop async def test_await(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) assert resp.status == 200 assert resp.connection is not None await resp.release() assert resp.connection is None @pytest.mark.run_loop async def test_response_context_manager(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) async with resp: assert resp.status == 200 assert resp.connection is not None assert resp.connection is None
import pytest import aiohttp from aiohttp import web @pytest.mark.run_loop async def test_await(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) assert resp.status == 200 assert resp.connection is not None await resp.release() assert resp.connection is None @pytest.mark.run_loop async def test_response_context_manager(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) resp = await aiohttp.get(url+'/', loop=loop) async with resp: assert resp.status == 200 assert resp.connection is not None assert resp.connection is None @pytest.mark.run_loop async def test_client_api_context_manager(create_server, loop): async def handler(request): return web.HTTPOk() app, url = await create_server() app.router.add_route('GET', '/', handler) async with aiohttp.get(url+'/', loop=loop) as resp: assert resp.status == 200 assert resp.connection is not None assert resp.connection is None
Add test for context manager
Add test for context manager
Python
apache-2.0
juliatem/aiohttp,playpauseandstop/aiohttp,juliatem/aiohttp,Eyepea/aiohttp,mind1master/aiohttp,z2v/aiohttp,decentfox/aiohttp,jashandeep-sohi/aiohttp,pfreixes/aiohttp,vaskalas/aiohttp,hellysmile/aiohttp,AraHaanOrg/aiohttp,moden-py/aiohttp,rutsky/aiohttp,z2v/aiohttp,vaskalas/aiohttp,elastic-coders/aiohttp,singulared/aiohttp,arthurdarcet/aiohttp,esaezgil/aiohttp,decentfox/aiohttp,jettify/aiohttp,alex-eri/aiohttp-1,jettify/aiohttp,panda73111/aiohttp,KeepSafe/aiohttp,KeepSafe/aiohttp,mind1master/aiohttp,esaezgil/aiohttp,moden-py/aiohttp,singulared/aiohttp,vaskalas/aiohttp,esaezgil/aiohttp,jashandeep-sohi/aiohttp,hellysmile/aiohttp,AraHaanOrg/aiohttp,Srogozins/aiohttp,mind1master/aiohttp,Insoleet/aiohttp,jashandeep-sohi/aiohttp,arthurdarcet/aiohttp,elastic-coders/aiohttp,pfreixes/aiohttp,alex-eri/aiohttp-1,rutsky/aiohttp,z2v/aiohttp,jettify/aiohttp,flying-sheep/aiohttp,rutsky/aiohttp,panda73111/aiohttp,panda73111/aiohttp,singulared/aiohttp,arthurdarcet/aiohttp,moden-py/aiohttp,decentfox/aiohttp,elastic-coders/aiohttp,KeepSafe/aiohttp,alex-eri/aiohttp-1
--- +++ @@ -32,3 +32,18 @@ assert resp.status == 200 assert resp.connection is not None assert resp.connection is None + + +@pytest.mark.run_loop +async def test_client_api_context_manager(create_server, loop): + + async def handler(request): + return web.HTTPOk() + + app, url = await create_server() + app.router.add_route('GET', '/', handler) + + async with aiohttp.get(url+'/', loop=loop) as resp: + assert resp.status == 200 + assert resp.connection is not None + assert resp.connection is None
e1e7189bbe859d6dfa6f883d2ff46ff1faed4842
scrape.py
scrape.py
import scholarly import requests _SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}' def search(query, start_year, end_year): """Search by scholar query and return a generator of Publication objects""" soup = scholarly._get_soup( _SEARCH.format(requests.utils.quote(query), str(start_year), str(end_year))) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", 2015, 2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
import scholarly import requests _EXACT_SEARCH = '/scholar?q="{}"' _START_YEAR = '&as_ylo={}' _END_YEAR = '&as_yhi={}' def search(query, exact=True, start_year=None, end_year=None): """Search by scholar query and return a generator of Publication objects""" url = _EXACT_SEARCH.format(requests.utils.quote(query)) if start_year: url += _START_YEAR.format(start_year) if end_year: url += _END_YEAR.format(end_year) soup = scholarly._get_soup(url) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015) num = 0 for x in s: x.fill() stuff = ['title', 'author', 'journal', 'volume', 'issue'] for thing in stuff: if thing in x.bib: print("{}: {}".format(thing, x.bib[thing])) num += 1 print("Number of results:", num)
Make year range arguments optional in search
Make year range arguments optional in search
Python
mit
Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker
--- +++ @@ -1,16 +1,21 @@ import scholarly import requests -_SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}' -def search(query, start_year, end_year): +_EXACT_SEARCH = '/scholar?q="{}"' +_START_YEAR = '&as_ylo={}' +_END_YEAR = '&as_yhi={}' +def search(query, exact=True, start_year=None, end_year=None): """Search by scholar query and return a generator of Publication objects""" - soup = scholarly._get_soup( - _SEARCH.format(requests.utils.quote(query), - str(start_year), str(end_year))) + url = _EXACT_SEARCH.format(requests.utils.quote(query)) + if start_year: + url += _START_YEAR.format(start_year) + if end_year: + url += _END_YEAR.format(end_year) + soup = scholarly._get_soup(url) return scholarly._search_scholar_soup(soup) if __name__ == '__main__': - s = search("Cure Alzheimer's Fund", 2015, 2015) + s = search("Cure Alzheimer's Fund", start_year=2015, end_year=2015) num = 0 for x in s: x.fill()
182c02b28a6ffee8744b48e39d378dca505f9287
testsuite/error-dupes/run.py
testsuite/error-dupes/run.py
#!/usr/bin/env python command = "echo 'Without repeated errors:' >> out.txt 2>&1 ;\n" command += testshade("-g 2 2 test") command += "echo 'With repeated errors:' >> out.txt 2>&1 ;\n" command += testshade("--options error_repeats=1 -g 2 2 test")
#!/usr/bin/env python command = "echo Without repeated errors:>> out.txt 2>&1 ;\n" command += testshade("-g 2 2 test") command += "echo With repeated errors:>> out.txt 2>&1 ;\n" command += testshade("--options error_repeats=1 -g 2 2 test")
Fix test output to not fail on Windows
Fix test output to not fail on Windows
Python
bsd-3-clause
aconty/OpenShadingLanguage,brechtvl/OpenShadingLanguage,aconty/OpenShadingLanguage,lgritz/OpenShadingLanguage,aconty/OpenShadingLanguage,brechtvl/OpenShadingLanguage,lgritz/OpenShadingLanguage,lgritz/OpenShadingLanguage,brechtvl/OpenShadingLanguage,lgritz/OpenShadingLanguage,aconty/OpenShadingLanguage,imageworks/OpenShadingLanguage,imageworks/OpenShadingLanguage,imageworks/OpenShadingLanguage,imageworks/OpenShadingLanguage,aconty/OpenShadingLanguage,brechtvl/OpenShadingLanguage,lgritz/OpenShadingLanguage,brechtvl/OpenShadingLanguage,imageworks/OpenShadingLanguage
--- +++ @@ -1,7 +1,7 @@ #!/usr/bin/env python -command = "echo 'Without repeated errors:' >> out.txt 2>&1 ;\n" +command = "echo Without repeated errors:>> out.txt 2>&1 ;\n" command += testshade("-g 2 2 test") -command += "echo 'With repeated errors:' >> out.txt 2>&1 ;\n" +command += "echo With repeated errors:>> out.txt 2>&1 ;\n" command += testshade("--options error_repeats=1 -g 2 2 test")
a6b9077bf093b64f3b993d032b166586195ae011
pyutrack/cli/util.py
pyutrack/cli/util.py
import collections import click def admin_command(fn): fn.__doc__ += ' [Admin only]' return fn class PyutrackContext(object): def __init__(self, connection, config, debug=False): self.connection = connection self.config = config self.debug = debug self.format = None def render(self, data, format=None): format = self.format or format oneline = format == 'oneline' line_sep = '\n' if format else '\n\n' if isinstance(data, collections.Iterable): resp = line_sep.join( k.format(format, oneline=oneline) for k in data ) if len(data) > 0 else click.style( 'No results', fg='yellow' ) elif data: resp = data.format(format, oneline=oneline) click.echo(resp)
import collections import click def admin_command(fn): fn.__doc__ += ' [Admin only]' return fn class PyutrackContext(object): def __init__(self, connection, config, debug=False): self.connection = connection self.config = config self.debug = debug self.format = None def render(self, data, format=None): format = self.format or format oneline = format == 'oneline' line_sep = '\n' if format else '\n\n' resp = '' if isinstance(data, six.string_types): resp = data elif isinstance(data, collections.Iterable): resp = line_sep.join( k.format(format, oneline=oneline) for k in data ) if len(data) > 0 else click.style( 'No results', fg='yellow' ) elif data: resp = data.format(format, oneline=oneline) click.echo(resp)
Fix issue with uninitialised response
Fix issue with uninitialised response
Python
mit
alisaifee/pyutrack,alisaifee/pyutrack
--- +++ @@ -19,7 +19,10 @@ format = self.format or format oneline = format == 'oneline' line_sep = '\n' if format else '\n\n' - if isinstance(data, collections.Iterable): + resp = '' + if isinstance(data, six.string_types): + resp = data + elif isinstance(data, collections.Iterable): resp = line_sep.join( k.format(format, oneline=oneline) for k in data ) if len(data) > 0 else click.style(
667a3d2803529c5b14fd17c6877961646615f2fd
python2/raygun4py/middleware/wsgi.py
python2/raygun4py/middleware/wsgi.py
import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") try: chunk = self.app(environ, start_response) except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise try: for event in chunk: yield event except Exception as e: request = build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if chunk and hasattr(chunk, 'close') and callable(chunk.close): try: chunk.close() except Exception as e: request = build_request(environ) self.send_exception(exception=e, request=request) def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request
import logging from raygun4py import raygunprovider log = logging.getLogger(__name__) class Provider(object): def __init__(self, app, apiKey): self.app = app self.sender = raygunprovider.RaygunSender(apiKey) def __call__(self, environ, start_response): if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") iterable = None try: iterable = self.app(environ, start_response) for event in iterable: yield event except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise finally: if hasattr(iterable, 'close'): try: iterable.close() except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) raise def build_request(self, environ): request = {} try: request = { 'httpMethod': environ['REQUEST_METHOD'], 'url': environ['PATH_INFO'], 'ipAddress': environ['REMOTE_ADDR'], 'hostName': environ['HTTP_HOST'].replace(' ', ''), 'queryString': environ['QUERY_STRING'], 'headers': {}, 'form': {}, 'rawData': {} } except Exception: pass for key, value in environ.items(): if key.startswith('HTTP_'): request['headers'][key] = value return request
Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly
Fix WSGI middleware to call close() on the iterable instead of checking if it's callable, and reraising the exception if one results as per spec. Also call sender correctly
Python
mit
MindscapeHQ/raygun4py
--- +++ @@ -16,29 +16,26 @@ if not self.sender: log.error("Raygun-WSGI: Cannot send as provider not attached") + iterable = None + try: - chunk = self.app(environ, start_response) + iterable = self.app(environ, start_response) + for event in iterable: + yield event + except Exception as e: request = self.build_request(environ) self.sender.send_exception(exception=e, request=request) - raise - try: - for event in chunk: - yield event - except Exception as e: - request = build_request(environ) - self.sender.send_exception(exception=e, request=request) - - raise finally: - if chunk and hasattr(chunk, 'close') and callable(chunk.close): + if hasattr(iterable, 'close'): try: - chunk.close() + iterable.close() except Exception as e: - request = build_request(environ) - self.send_exception(exception=e, request=request) + request = self.build_request(environ) + self.sender.send_exception(exception=e, request=request) + raise def build_request(self, environ): request = {}
95bb764e78e623310dff1ae48eabf4271b452406
penchy/jobs/__init__.py
penchy/jobs/__init__.py
from penchy.jobs import jvms, tools, filters, workloads from penchy.jobs.job import Job, SystemComposition, NodeSetting from penchy.jobs.dependency import Edge JVM = jvms.JVM # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'NodeSetting', 'SystemComposition', # dependencies 'Edge', # jvms 'JVM', # modules 'jvms', 'filters', 'workloads', 'tools' ]
from penchy.jobs import jvms, tools, filters, workloads from penchy.jobs.job import Job, SystemComposition, NodeSetting JVM = jvms.JVM # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'NodeSetting', 'SystemComposition', # jvms 'JVM', # modules 'jvms', 'filters', 'workloads', 'tools' ]
Remove Edge from jobs package.
jobs: Remove Edge from jobs package. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
Python
mit
fhirschmann/penchy,fhirschmann/penchy
--- +++ @@ -1,6 +1,5 @@ from penchy.jobs import jvms, tools, filters, workloads from penchy.jobs.job import Job, SystemComposition, NodeSetting -from penchy.jobs.dependency import Edge JVM = jvms.JVM @@ -10,8 +9,6 @@ 'Job', 'NodeSetting', 'SystemComposition', - # dependencies - 'Edge', # jvms 'JVM', # modules
dbc16598a87403f52324bca3d50132fc9303ee90
reviewboard/hostingsvcs/gitorious.py
reviewboard/hostingsvcs/gitorious.py
from django import forms from django.utils.translation import ugettext_lazy as _ from reviewboard.hostingsvcs.forms import HostingServiceForm from reviewboard.hostingsvcs.service import HostingService class GitoriousForm(HostingServiceForm): gitorious_project_name = forms.CharField( label=_('Project name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) gitorious_repo_name = forms.CharField( label=_('Repository name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) class Gitorious(HostingService): name = 'Gitorious' form = GitoriousForm supported_scmtools = ['Git'] supports_repositories = True repository_fields = { 'Git': { 'path': 'git://gitorious.org/%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'mirror_path': 'http://git.gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'raw_file_url': 'http://git.gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s/blobs/raw/<revision>' }, }
from django import forms from django.utils.translation import ugettext_lazy as _ from reviewboard.hostingsvcs.forms import HostingServiceForm from reviewboard.hostingsvcs.service import HostingService class GitoriousForm(HostingServiceForm): gitorious_project_name = forms.CharField( label=_('Project name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) gitorious_repo_name = forms.CharField( label=_('Repository name'), max_length=64, required=True, widget=forms.TextInput(attrs={'size': '60'})) class Gitorious(HostingService): name = 'Gitorious' form = GitoriousForm supported_scmtools = ['Git'] supports_repositories = True repository_fields = { 'Git': { 'path': 'git://gitorious.org/%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'mirror_path': 'https://gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', 'raw_file_url': 'https://gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s/blobs/raw/<revision>' }, }
Fix the raw paths for Gitorious
Fix the raw paths for Gitorious Gitorious have changed the raw orl paths, making impossible to use a Gitorious repository. This patch has been tested in production at http://reviewboard.chakra-project.org/r/27/diff/#index_header Reviewed at http://reviews.reviewboard.org/r/3649/diff/#index_header
Python
mit
KnowNo/reviewboard,brennie/reviewboard,1tush/reviewboard,chipx86/reviewboard,davidt/reviewboard,brennie/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,reviewboard/reviewboard,beol/reviewboard,1tush/reviewboard,brennie/reviewboard,custode/reviewboard,sgallagher/reviewboard,1tush/reviewboard,1tush/reviewboard,chipx86/reviewboard,1tush/reviewboard,davidt/reviewboard,davidt/reviewboard,sgallagher/reviewboard,beol/reviewboard,1tush/reviewboard,reviewboard/reviewboard,1tush/reviewboard,KnowNo/reviewboard,custode/reviewboard,brennie/reviewboard,chipx86/reviewboard,beol/reviewboard,custode/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,reviewboard/reviewboard,1tush/reviewboard,bkochendorfer/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,bkochendorfer/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,1tush/reviewboard,davidt/reviewboard,beol/reviewboard
--- +++ @@ -28,10 +28,10 @@ 'Git': { 'path': 'git://gitorious.org/%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', - 'mirror_path': 'http://git.gitorious.org/' + 'mirror_path': 'https://gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s.git', - 'raw_file_url': 'http://git.gitorious.org/' + 'raw_file_url': 'https://gitorious.org/' '%(gitorious_project_name)s/' '%(gitorious_repo_name)s/blobs/raw/<revision>' },
318e322fbc29dd20d56dc311c71ae60e010a7cdf
ooni/resources/__init__.py
ooni/resources/__init__.py
from ooni.settings import config from ooni.utils import unzip, gunzip from ooni.deckgen.processors import citizenlab_test_lists from ooni.deckgen.processors import namebench_dns_servers config.read_config_file() __version__ = "0.0.1" inputs = { "namebench-dns-servers.csv": { "url": "https://namebench.googlecode.com/svn/trunk/config/servers.csv", "action": None, "action_args": [], "processor": namebench_dns_servers, }, "citizenlab-test-lists.zip": { "url": "https://github.com/citizenlab/test-lists/archive/master.zip", "action": unzip, "action_args": [config.resources_directory], "processor": citizenlab_test_lists } } geoip = { "GeoIPASNum.dat.gz": { "url": "http://www.maxmind.com/download/" "geoip/database/asnum/GeoIPASNum.dat.gz", "action": gunzip, "action_args": [config.advanced.geoip_data_dir], "processor": None }, "GeoIP.dat.gz": { "url": "http://geolite.maxmind.com/" "download/geoip/database/GeoLiteCountry/GeoIP.dat.gz", "action": gunzip, "action_args": [config.advanced.geoip_data_dir], "processor": None } }
from ooni.settings import config from ooni.utils import unzip, gunzip from ooni.deckgen.processors import citizenlab_test_lists from ooni.deckgen.processors import namebench_dns_servers config.read_config_file() __version__ = "0.0.1" inputs = { "namebench-dns-servers.csv": { "url": "https://namebench.googlecode.com/svn/trunk/config/servers.csv", "action": None, "action_args": [], "processor": namebench_dns_servers, }, "citizenlab-test-lists.zip": { "url": "https://github.com/citizenlab/test-lists/archive/master.zip", "action": unzip, "action_args": [config.resources_directory], "processor": citizenlab_test_lists } } geoip = { "GeoIPASNum.dat.gz": { "url": "https://www.maxmind.com/download/" "geoip/database/asnum/GeoIPASNum.dat.gz", "action": gunzip, "action_args": [config.advanced.geoip_data_dir], "processor": None }, "GeoIP.dat.gz": { "url": "https://geolite.maxmind.com/" "download/geoip/database/GeoLiteCountry/GeoIP.dat.gz", "action": gunzip, "action_args": [config.advanced.geoip_data_dir], "processor": None } }
Use HTTPS URLs for MaxMind resources
Use HTTPS URLs for MaxMind resources
Python
bsd-2-clause
lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe
--- +++ @@ -25,14 +25,14 @@ geoip = { "GeoIPASNum.dat.gz": { - "url": "http://www.maxmind.com/download/" + "url": "https://www.maxmind.com/download/" "geoip/database/asnum/GeoIPASNum.dat.gz", "action": gunzip, "action_args": [config.advanced.geoip_data_dir], "processor": None }, "GeoIP.dat.gz": { - "url": "http://geolite.maxmind.com/" + "url": "https://geolite.maxmind.com/" "download/geoip/database/GeoLiteCountry/GeoIP.dat.gz", "action": gunzip, "action_args": [config.advanced.geoip_data_dir],
ae55577e4cea64a0052eb0c219641435c9c0210c
samples/model-builder/init_sample.py
samples/model-builder/init_sample.py
# Copyright 2021 Google LLC # # 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 # # https://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 typing import Optional from google.auth import credentials as auth_credentials from google.cloud import aiplatform # [START aiplatform_sdk_init_sample] def init_sample( project: Optional[str] = None, location: Optional[str] = None, experiment: Optional[str] = None, staging_bucket: Optional[str] = None, credentials: Optional[auth_credentials.Credentials] = None, encryption_spec_key_name: Optional[str] = None, ): aiplatform.init( project=project, location=location, experiment=experiment, staging_bucket=staging_bucket, credentials=credentials, encryption_spec_key_name=encryption_spec_key_name, ) # [END aiplatform_sdk_init_sample]
# Copyright 2021 Google LLC # # 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 # # https://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 typing import Optional from google.auth import credentials as auth_credentials # [START aiplatform_sdk_init_sample] def init_sample( project: Optional[str] = None, location: Optional[str] = None, experiment: Optional[str] = None, staging_bucket: Optional[str] = None, credentials: Optional[auth_credentials.Credentials] = None, encryption_spec_key_name: Optional[str] = None, ): from google.cloud import aiplatform aiplatform.init( project=project, location=location, experiment=experiment, staging_bucket=staging_bucket, credentials=credentials, encryption_spec_key_name=encryption_spec_key_name, ) # [END aiplatform_sdk_init_sample]
Update init sample to import inside of function.
chore: Update init sample to import inside of function. PiperOrigin-RevId: 485079470
Python
apache-2.0
googleapis/python-aiplatform,googleapis/python-aiplatform
--- +++ @@ -15,7 +15,6 @@ from typing import Optional from google.auth import credentials as auth_credentials -from google.cloud import aiplatform # [START aiplatform_sdk_init_sample] @@ -27,6 +26,9 @@ credentials: Optional[auth_credentials.Credentials] = None, encryption_spec_key_name: Optional[str] = None, ): + + from google.cloud import aiplatform + aiplatform.init( project=project, location=location,
cba8ec4754ed3516ba3f873b0879c8379e8f93ab
data_structures/bitorrent/server/udp.py
data_structures/bitorrent/server/udp.py
#!/usr/bin/env python import struct from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor class Announce(DatagramProtocol): def parse_connection(self, data): connection, action, transaction_id = struct.unpack("!qii", data) message = struct.pack('!iiq', action, transaction_id, connection) return message def parse_announce(self, data): message = struct.unpack("!qii20s20sqqqiIIiH", data) print message return message def datagramReceived(self, data, (host, port)): if len(data) < 90: data = self.parse_connection(data) else: data = self.parse_announce(data) self.transport.write(data, (host, port)) reactor.listenUDP(9999, Announce()) reactor.run()
#!/usr/bin/env python import struct from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor from announce.torrent import Torrent class Announce(DatagramProtocol): def parse_connection(self, data): connection, action, transaction_id = struct.unpack("!qii", data) message = struct.pack('!iiq', action, transaction_id, connection) return message def parse_announce(self, data, host, port): connection_id, action, transaction_id, info_hash, peer_id, downloaded, \ left, uploaded, event, ip, key, num_want, \ port = struct.unpack("!qii40s20sqqqiIIiH", data) torrent = Torrent(info_hash) if not torrent.can_announce(peer_id): error_message = "You need to wait 5 minutes to reannounce yourself" response = struct.pack('!ii%ss' % len(error_message), action, transaction_id, error_message) else: torrent.peers = "%s:%s" % (host, port) torrent.set_announce(peer_id) response = struct.pack('!iiiii', action, transaction_id, 5 * 60, torrent.leechers, torrent.seeders) response += torrent.binary_peers return response def datagramReceived(self, data, (host, port)): if len(data) < 90: data = self.parse_connection(data) else: data = self.parse_announce(data, host, port) self.transport.write(data, (host, port)) reactor.listenUDP(9999, Announce()) reactor.run()
Send back announce response to client
Send back announce response to client
Python
apache-2.0
vtemian/university_projects,vtemian/university_projects,vtemian/university_projects
--- +++ @@ -3,6 +3,8 @@ from twisted.internet.protocol import DatagramProtocol from twisted.internet import reactor + +from announce.torrent import Torrent class Announce(DatagramProtocol): @@ -12,16 +14,31 @@ message = struct.pack('!iiq', action, transaction_id, connection) return message - def parse_announce(self, data): - message = struct.unpack("!qii20s20sqqqiIIiH", data) - print message - return message + def parse_announce(self, data, host, port): + connection_id, action, transaction_id, info_hash, peer_id, downloaded, \ + left, uploaded, event, ip, key, num_want, \ + port = struct.unpack("!qii40s20sqqqiIIiH", data) + + torrent = Torrent(info_hash) + + if not torrent.can_announce(peer_id): + error_message = "You need to wait 5 minutes to reannounce yourself" + response = struct.pack('!ii%ss' % len(error_message), action, + transaction_id, error_message) + else: + torrent.peers = "%s:%s" % (host, port) + torrent.set_announce(peer_id) + response = struct.pack('!iiiii', action, transaction_id, 5 * 60, + torrent.leechers, torrent.seeders) + response += torrent.binary_peers + + return response def datagramReceived(self, data, (host, port)): if len(data) < 90: data = self.parse_connection(data) else: - data = self.parse_announce(data) + data = self.parse_announce(data, host, port) self.transport.write(data, (host, port))
2ef0ccfbf337d0ef1870c5a1191b2bcdcffd1f9e
dbaas/backup/admin/log_configuration.py
dbaas/backup/admin/log_configuration.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib import admin import logging LOG = logging.getLogger(__name__) class LogConfigurationAdmin(admin.ModelAdmin): list_filter = ("environment", "engine_type") list_display = ("environment", "engine_type", "retention_days", "filer_path", "mount_point_path", "log_path")
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.contrib import admin import logging LOG = logging.getLogger(__name__) class LogConfigurationAdmin(admin.ModelAdmin): list_filter = ("environment", "engine_type") list_display = ("environment", "engine_type", "retention_days", "filer_path", "mount_point_path", "log_path", "cron_minute", "cron_hour")
Add new fields on LogConfiguration model
Add new fields on LogConfiguration model
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
--- +++ @@ -12,4 +12,5 @@ list_filter = ("environment", "engine_type") list_display = ("environment", "engine_type", "retention_days", - "filer_path", "mount_point_path", "log_path") + "filer_path", "mount_point_path", "log_path", + "cron_minute", "cron_hour")
446923b12942f351f2f40d035f0c1e6f9dcb8813
__init__.py
__init__.py
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys # Add the third_party/ dir to our search path so that we can find the # modules in there automatically. This isn't normal, so don't replicate # this pattern elsewhere. _third_party = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath( __file__)), 'third_party')) sys.path.insert(0, _third_party) # List of third_party packages that might need subpaths added to search. _paths = [ 'pyelftools', ] for _path in _paths: sys.path.insert(1, os.path.join(_third_party, _path))
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys # Add the third_party/ dir to our search path so that we can find the # modules in there automatically. This isn't normal, so don't replicate # this pattern elsewhere. _chromite_dir = os.path.normpath(os.path.dirname(os.path.realpath(__file__))) _containing_dir = os.path.dirname(_chromite_dir) _third_party_dirs = [os.path.join(_chromite_dir, 'third_party')] # If chromite is living inside the Chrome checkout under # <chrome_root>/src/third_party/chromite, its dependencies will be checked out # to <chrome_root>/src/third_party instead of the normal chromite/third_party # location due to git-submodule limitations (a submodule cannot be contained # inside another submodule's workspace), so we want to add that to the # search path. if os.path.basename(_containing_dir) == 'third_party': _third_party_dirs.append(_containing_dir) # List of third_party packages that might need subpaths added to search. _paths = [ 'pyelftools', ] for _path in _paths: for _third_party in _third_party_dirs[:]: _component = os.path.join(_third_party, _path) if os.path.isdir(_component): _third_party_dirs.append(_component) sys.path = _third_party_dirs + sys.path
Add <chrome>/src/third_party dir to PYTHONPATH for Chrome checkouts.
Add <chrome>/src/third_party dir to PYTHONPATH for Chrome checkouts. If chromite is living inside the Chrome checkout under <chrome_root>/src/third_party/chromite, its dependencies will be checked out to <chrome_root>/src/third_party instead of the normal chromite/third_party location due to git-submodule limitations (a submodule cannot be contained inside another submodule's workspace), so we want to add that to the search path. BUG=None TEST=Local Change-Id: I10a12bcddc88e509c1c7015a95c54d578fb8b122 Reviewed-on: https://gerrit.chromium.org/gerrit/43066 Reviewed-by: Mike Frysinger <8f3f75c74bd5184edcfa6534cab3c13a00a2f794@chromium.org> Commit-Queue: Ryan Cui <5ce1592d53754a87a44fc2eb7b63d5f77cf50fdb@chromium.org> Tested-by: Ryan Cui <5ce1592d53754a87a44fc2eb7b63d5f77cf50fdb@chromium.org>
Python
bsd-3-clause
coreos/chromite,bpsinc-native/src_third_party_chromite,bpsinc-native/src_third_party_chromite,bpsinc-native/src_third_party_chromite,zhang0137/chromite,chadversary/chromiumos.chromite,coreos/chromite,zhang0137/chromite,coreos/chromite,zhang0137/chromite,chadversary/chromiumos.chromite
--- +++ @@ -8,14 +8,26 @@ # Add the third_party/ dir to our search path so that we can find the # modules in there automatically. This isn't normal, so don't replicate # this pattern elsewhere. -_third_party = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath( - __file__)), 'third_party')) -sys.path.insert(0, _third_party) +_chromite_dir = os.path.normpath(os.path.dirname(os.path.realpath(__file__))) +_containing_dir = os.path.dirname(_chromite_dir) +_third_party_dirs = [os.path.join(_chromite_dir, 'third_party')] +# If chromite is living inside the Chrome checkout under +# <chrome_root>/src/third_party/chromite, its dependencies will be checked out +# to <chrome_root>/src/third_party instead of the normal chromite/third_party +# location due to git-submodule limitations (a submodule cannot be contained +# inside another submodule's workspace), so we want to add that to the +# search path. +if os.path.basename(_containing_dir) == 'third_party': + _third_party_dirs.append(_containing_dir) # List of third_party packages that might need subpaths added to search. _paths = [ - 'pyelftools', + 'pyelftools', ] + for _path in _paths: - sys.path.insert(1, os.path.join(_third_party, _path)) - + for _third_party in _third_party_dirs[:]: + _component = os.path.join(_third_party, _path) + if os.path.isdir(_component): + _third_party_dirs.append(_component) +sys.path = _third_party_dirs + sys.path
16cd3b501755c6d45b39b46ca8179cc0dc015125
main/admin/lan.py
main/admin/lan.py
from django.contrib import admin from django.forms import model_to_dict from django.utils.timezone import now from main.models import Lan, Event class EventInline(admin.TabularInline): model = Event show_change_link = True fields = ('name', 'url', 'start', 'end') @admin.register(Lan) class LanAdmin(admin.ModelAdmin): list_display = ('name', 'start', 'seats_count', 'is_open') fieldsets = ( ('Tider', { 'fields': (('start', 'end'), 'open', 'show_calendar') }), ('Pladser', { 'fields': ('seats',) }), ('Tekst', { 'fields': ('name', 'schedule', 'blurb') }), ('Betaling', { 'fields': ('paytypes', 'price', 'payphone') }), ('Madbestilling', { 'fields': ('food_open', 'food_phone') }), ) inlines = [ EventInline ] def get_changeform_initial_data(self, request): try: prev_lan = Lan.objects.filter(start__lt=now()).order_by("-start")[0] return model_to_dict(prev_lan, ['blurb', 'seats', 'schedule']) except (Lan.DoesNotExist, AttributeError, IndexError): return {}
from django.contrib import admin from django.forms import model_to_dict from django.utils.timezone import now from main.models import Lan, Event class EventInline(admin.TabularInline): model = Event show_change_link = True fields = ('name', 'url', 'start', 'end') @admin.register(Lan) class LanAdmin(admin.ModelAdmin): list_display = ('name', 'start', 'seats_count', 'is_open') fieldsets = ( ('Tider', { 'fields': (('start', 'end'), 'open', 'show_calendar') }), ('Pladser', { 'fields': ('seats',) }), ('Tekst', { 'fields': ('name', 'blurb') }), ('Betaling', { 'fields': ('paytypes', 'price', 'payphone') }), ('Madbestilling', { 'fields': ('food_open', 'food_phone') }), ) inlines = [ EventInline ] def get_changeform_initial_data(self, request): try: prev_lan = Lan.objects.filter(start__lt=now()).order_by("-start")[0] return model_to_dict(prev_lan, ['blurb', 'seats', 'schedule']) except (Lan.DoesNotExist, AttributeError, IndexError): return {}
Remove schedule from admin too
Remove schedule from admin too
Python
mit
bomjacob/htxaarhuslan,bomjacob/htxaarhuslan,bomjacob/htxaarhuslan
--- +++ @@ -24,7 +24,7 @@ 'fields': ('seats',) }), ('Tekst', { - 'fields': ('name', 'schedule', 'blurb') + 'fields': ('name', 'blurb') }), ('Betaling', { 'fields': ('paytypes', 'price', 'payphone')
f497259869ba0f920d8a7eaac45bd320566c4808
examples/Interactivity/circlepainter.py
examples/Interactivity/circlepainter.py
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
size(800, 800) import time colormode(RGB) speed(60) def setup(): # ovallist is the list of ovals we created by moving the mouse. global ovallist stroke(0) strokewidth(1) ovallist = [] class Blob: def __init__(self, x, y, c, r): self.x, self.y = x, y self.color = c self.radius = r def draw(self): fill(self.color) stroke(0) strokewidth(1) circle(self.x, self.y, self.radius) # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) def draw(): global ovallist x = MOUSEX y = MOUSEY if 0: if x > WIDTH or y > HEIGHT: return b = mousedown if b: d = random() r = random(10, 20) c = color(0,d,0,0.4) ovallist.append( Blob(x,y,c,r) ) for blob in ovallist: blob.draw()
Use of circle() instead of oval()
Use of circle() instead of oval()
Python
mit
karstenw/nodebox-pyobjc,karstenw/nodebox-pyobjc
--- +++ @@ -21,7 +21,8 @@ fill(self.color) stroke(0) strokewidth(1) - oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2) + circle(self.x, self.y, self.radius) + # oval(self.x-self.radius, self.y-self.radius, self.radius*2, self.radius*2)