commit,old_file,new_file,old_contents,new_contents,subject,message,lang,license,repos 0b152333c30d061df64376bb036c5fcd20896c36,go/billing/urls.py,go/billing/urls.py,"from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^(?P[\d]+)', views.statement_view, name='pdf_statement') ) ","from django.conf.urls import patterns, url from go.billing import views urlpatterns = patterns( '', url( r'^statement/(?P[\d]+)', views.statement_view, name='pdf_statement') ) ",Move statement PDF URL off the root of the billing URL namespace.,"Move statement PDF URL off the root of the billing URL namespace. ",Python,bsd-3-clause,"praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go" cc379cb3e68ddf5a110eef139282c83dc8b8e9d1,tests/test_queue/test_queue.py,tests/test_queue/test_queue.py,"import unittest from aids.queue.queue import Queue class QueueTestCase(unittest.TestCase): ''' Unit tests for the Queue data structure ''' def setUp(self): self.test_queue = Queue() def test_queue_initialization(self): self.assertTrue(isinstance(self.test_queue, Queue)) def test_queue_is_empty(self): self.assertTrue(self.test_queue.is_empty()) def tearDown(self): pass ","import unittest from aids.queue.queue import Queue class QueueTestCase(unittest.TestCase): ''' Unit tests for the Queue data structure ''' def setUp(self): self.test_queue = Queue() def test_queue_initialization(self): self.assertTrue(isinstance(self.test_queue, Queue)) def test_queue_is_empty(self): self.assertTrue(self.test_queue.is_empty()) def test_queue_enqueue(self): self.test_queue.enqueue(1) self.assertEqual(len(self.test_queue), 1) def test_queue_dequeue(self): self.test_queue.enqueue(1) self.assertEqual(self.test_queue.dequeue(), 1) def test_queue_len(self): self.test_queue.enqueue(1) self.assertEqual(len(self.test_queue), 1) def tearDown(self): pass ","Add unit tests for enqueue, dequeue and length for Queue","Add unit tests for enqueue, dequeue and length for Queue ",Python,mit,ueg1990/aids 6dde06470c9cd868319b1b4615d3065b61a6bc2c,sqlcop/cli.py,sqlcop/cli.py,"import sys import sqlparse from .checks import has_cross_join def parse_file(filename): import json with open(filename, 'r') as fh: return json.load(fh) CHECKS = ( (has_cross_join, 'query contains cross join'), ) def check_query(el): """""" Run each of the defined checks on a query. """""" stmt = sqlparse.parse(el) for check in CHECKS: if check[0](stmt[0]): return False, check[1] return True, '' def main(): argv = sys.argv try: queries = parse_file(argv[1]) except IndexError: raise Exception('Filename required') failed = False for query, tests in queries.iteritems(): passed, message = check_query(query) if not passed: failed = True print_message(message, tests, query) sys.exit(255 if failed else 0) def print_message(message, tests, query): print ""FAILED - %s"" % (message) print ""-----------------------------------------------------------------"" print ""Test Methods:"" print ""%s"" % ""\n"".join(tests) print print ""Query:"" print ""%s"" % query ","import sys import sqlparse from .checks import has_cross_join def parse_file(filename): return open(filename, 'r').readlines() CHECKS = ( (has_cross_join, 'query contains cross join'), ) def check_query(el): """""" Run each of the defined checks on a query. """""" stmt = sqlparse.parse(el) for check in CHECKS: if check[0](stmt[0]): return False, check[1] return True, '' def main(): argv = sys.argv try: queries = parse_file(argv[1]) except IndexError: raise Exception('Filename required') failed = False for query in queries: passed, message = check_query(query) if not passed: failed = True print_message(message, query) sys.exit(255 if failed else 0) def print_message(message, query): print ""FAILED - %s"" % (message) print ""-----------------------------------------------------------------"" print print ""Query:"" print ""%s"" % query ",Work with plain SQL files,"Work with plain SQL files ",Python,bsd-3-clause,freshbooks/sqlcop 1963012ba4628f1f66d495e777275243dc7248e4,.CI/trigger_conda-forge.github.io.py,.CI/trigger_conda-forge.github.io.py,""""""" Trigger the conda-forge.github.io Travis job to restart. """""" import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers[""Accept""] = ""application/json"" headers[""Travis-API-Version""] = ""3"" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={""request"": {""branch"": ""master""}}, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io') ",""""""" Trigger the conda-forge.github.io Travis job to restart. """""" import os import requests import six import conda_smithy.ci_register def rebuild_travis(repo_slug): headers = conda_smithy.ci_register.travis_headers() # If we don't specify the API version, we get a 404. # Also fix the accepted content type. headers[""Accept""] = ""application/json"" headers[""Travis-API-Version""] = ""3"" # Trigger a build on `master`. encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='') url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug) response = requests.post( url, json={ ""request"": { ""branch"": ""master"", ""message"": ""Triggering build from staged-recipes"", } }, headers=headers ) if response.status_code != 201: response.raise_for_status() if __name__ == '__main__': rebuild_travis('conda-forge/conda-forge.github.io') ",Add message to webpage repo trigger,"Add message to webpage repo trigger Should fix triggering builds on the webpage repo even when the most recent commit message skip the CI build. Also should make it easier to identify builds started by this trigger. [ci skip] [skip ci] ",Python,bsd-3-clause,"jakirkham/staged-recipes,Cashalow/staged-recipes,dschreij/staged-recipes,scopatz/staged-recipes,stuertz/staged-recipes,conda-forge/staged-recipes,guillochon/staged-recipes,hadim/staged-recipes,SylvainCorlay/staged-recipes,mcs07/staged-recipes,scopatz/staged-recipes,sodre/staged-recipes,pmlandwehr/staged-recipes,sannykr/staged-recipes,shadowwalkersb/staged-recipes,sodre/staged-recipes,larray-project/staged-recipes,sodre/staged-recipes,patricksnape/staged-recipes,birdsarah/staged-recipes,NOAA-ORR-ERD/staged-recipes,pmlandwehr/staged-recipes,jochym/staged-recipes,chohner/staged-recipes,ceholden/staged-recipes,rmcgibbo/staged-recipes,hadim/staged-recipes,goanpeca/staged-recipes,barkls/staged-recipes,Cashalow/staged-recipes,kwilcox/staged-recipes,sannykr/staged-recipes,jjhelmus/staged-recipes,glemaitre/staged-recipes,isuruf/staged-recipes,mariusvniekerk/staged-recipes,larray-project/staged-recipes,jakirkham/staged-recipes,mariusvniekerk/staged-recipes,jochym/staged-recipes,chrisburr/staged-recipes,Juanlu001/staged-recipes,patricksnape/staged-recipes,petrushy/staged-recipes,rvalieris/staged-recipes,ReimarBauer/staged-recipes,synapticarbors/staged-recipes,rvalieris/staged-recipes,glemaitre/staged-recipes,guillochon/staged-recipes,petrushy/staged-recipes,Juanlu001/staged-recipes,asmeurer/staged-recipes,isuruf/staged-recipes,birdsarah/staged-recipes,conda-forge/staged-recipes,kwilcox/staged-recipes,barkls/staged-recipes,chrisburr/staged-recipes,jjhelmus/staged-recipes,mcs07/staged-recipes,basnijholt/staged-recipes,asmeurer/staged-recipes,ReimarBauer/staged-recipes,basnijholt/staged-recipes,cpaulik/staged-recipes,goanpeca/staged-recipes,johanneskoester/staged-recipes,shadowwalkersb/staged-recipes,synapticarbors/staged-recipes,SylvainCorlay/staged-recipes,igortg/staged-recipes,stuertz/staged-recipes,cpaulik/staged-recipes,NOAA-ORR-ERD/staged-recipes,ocefpaf/staged-recipes,johanneskoester/staged-recipes,rmcgibbo/staged-recipes,igortg/staged-recipes,ocefpaf/staged-recipes,chohner/staged-recipes,dschreij/staged-recipes,ceholden/staged-recipes" ddb3bcf4e5d5eb5dc4f8bb74313f333e54c385d6,scripts/wall_stop.py,scripts/wall_stop.py,"#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = LightSensorValues() rospy.Subscriber('/lightsensors', LightSensorValues, self.callback_lightsensors) def callback_lightsensors(self,messages): self.sensor_values = messages def run(self): rate = rospy.Rate(10) data = Twist() while not rospy.is_shutdown(): data.linear.x = 0.2 if self.sensor_values.sum_all < 500 else 0.0 self.cmd_vel.publish(data) rate.sleep() if __name__ == '__main__': rospy.init_node('wall_stop') rospy.wait_for_service('/motor_on') rospy.wait_for_service('/motor_off') rospy.on_shutdown(rospy.ServiceProxy('/motor_off',Trigger).call) rospy.ServiceProxy('/motor_on',Trigger).call() WallStop().run() ","#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse from pimouse_ros.msg import LightSensorValues class WallStop(): def __init__(self): self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1) self.sensor_values = LightSensorValues() rospy.Subscriber('/lightsensors', LightSensorValues, self.callback) def callback(self,messages): self.sensor_values = messages def run(self): rate = rospy.Rate(10) data = Twist() while not rospy.is_shutdown(): data.linear.x = 0.2 if self.sensor_values.sum_all < 500 else 0.0 self.cmd_vel.publish(data) rate.sleep() if __name__ == '__main__': rospy.init_node('wall_stop') rospy.wait_for_service('/motor_on') rospy.wait_for_service('/motor_off') rospy.on_shutdown(rospy.ServiceProxy('/motor_off',Trigger).call) rospy.ServiceProxy('/motor_on',Trigger).call() WallStop().run() ",Reduce the name of a function,"Reduce the name of a function ",Python,mit,"citueda/pimouse_run_corridor,citueda/pimouse_run_corridor" 7917716ebd11770c5d4d0634b39e32e4f577ab71,tests/test_urls.py,tests/test_urls.py,"from unittest import TestCase class TestURLs(TestCase): pass ","from unittest import TestCase from django.contrib.auth import views from django.core.urlresolvers import resolve, reverse class URLsMixin(object): """""" A TestCase Mixin with a check_url helper method for testing urls. Pirated with slight modifications from incuna_test_utils https://github.com/incuna/incuna-test-utils/blob/master/incuna_test_utils/testcases/urls.py """""" def check_url(self, view_method, expected_url, url_name, url_args=None, url_kwargs=None): """""" Assert a view's url is correctly configured Check the url_name reverses to give a correctly formated expected_url. Check the expected_url resolves to the correct view. """""" reversed_url = reverse(url_name, args=url_args, kwargs=url_kwargs) self.assertEqual(reversed_url, expected_url) # Look for a method rather than a class here # (just because of what we're testing) resolved_view_method = resolve(expected_url).func self.assertEqual(resolved_view_method, view_method) class TestURLs(URLsMixin, TestCase): def test_login(self): self.check_url( views.login, '/login/', 'login', ) def test_logout(self): self.check_url( views.logout, '/logout/', 'logout', ) def test_password_change(self): self.check_url( views.password_change, '/password/change/', 'password_change', ) def test_password_change_done(self): self.check_url( views.password_change_done, '/password/change/done/', 'password_change_done', ) def test_password_reset(self): self.check_url( views.password_reset, '/password/reset/', 'password_reset', ) def test_password_reset_done(self): self.check_url( views.password_reset_done, '/password/reset/done/', 'password_reset_done', ) def test_password_reset_complete(self): self.check_url( views.password_reset_complete, '/password/reset/complete/', 'password_reset_complete', ) ",Add lots of URL tests.,"Add lots of URL tests. * The URLsMixin from incuna_test_utils/testcases/urls.py isn't quite doing what we want here, so rip it off and make a small modification (resolve(...).func.cls -> resolve(...).func). * Add lots of tests for the django.contrib.auth views that we're using (the others are more complex). ",Python,bsd-2-clause,"incuna/incuna-auth,ghickman/incuna-auth,ghickman/incuna-auth,incuna/incuna-auth" 4c6f40f3d1394fff9ed9a4c6fe3ffd0ae5cb6230,jsondb/file_writer.py,jsondb/file_writer.py,"from .compat import decode, encode def read_data(path): """""" Reads a file and returns a json encoded representation of the file. """""" db = open(path, ""r+"") content = db.read() obj = decode(content) db.close() return obj def write_data(path, obj): """""" Writes to a file and returns the updated file content. """""" with open(path, ""w+"") as db: db.write(encode(obj)) return obj def is_valid(file_path): """""" Check to see if a file exists or is empty """""" from os import path, stat return path.exists(file_path) and stat(file_path).st_size > 0 ","from .compat import decode, encode def read_data(file_path): """""" Reads a file and returns a json encoded representation of the file. """""" if not is_valid(file_path): write_data(file_path, {}) db = open(file_path, ""r+"") content = db.read() obj = decode(content) db.close() return obj def write_data(path, obj): """""" Writes to a file and returns the updated file content. """""" with open(path, ""w+"") as db: db.write(encode(obj)) return obj def is_valid(file_path): """""" Check to see if a file exists or is empty. """""" from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(file_path) and is_file and stat(file_path).st_size > 0 ",Create a new file if the path is invalid.,"Create a new file if the path is invalid. ",Python,bsd-3-clause,gunthercox/jsondb 074f76547fbc01137e135f5de57b28fee82b810c,pylibui/core.py,pylibui/core.py,""""""" Python wrapper for libui. """""" from . import libui class App: def __init__(self): """""" Creates a new pylibui app. """""" options = libui.uiInitOptions() libui.uiInit(options) def start(self): """""" Starts the application main loop. :return: None """""" libui.uiMain() def stop(self): """""" Stops the application main loop. :return: None """""" libui.uiQuit() def close(self): """""" Closes the application and frees resources. :return: None """""" libui.uiUninit() ",""""""" Python wrapper for libui. """""" from . import libui class App: def __init__(self): """""" Creates a new pylibui app. """""" options = libui.uiInitOptions() libui.uiInit(options) def __enter__(self): self.start() def start(self): """""" Starts the application main loop. :return: None """""" libui.uiMain() def __exit__(self, exc_type, exc_val, exc_tb): self.stop() self.close() def stop(self): """""" Stops the application main loop. :return: None """""" libui.uiQuit() def close(self): """""" Closes the application and frees resources. :return: None """""" libui.uiUninit() ",Make App a context manager,"Make App a context manager This means it can be used either as it is now unchanged or like this: with libui.App(): ... # code Note that (1) the build instructions for libui appear to be wrong ""make"" vs ""cmake .""; and (2) I can't build libui because of a bug in it or Ubuntu 14.04's cmake I don't know which. So this change is untested.",Python,mit,"joaoventura/pylibui,superzazu/pylibui,superzazu/pylibui,joaoventura/pylibui" f0984c9855a6283de27e717fad73bb4f1b6394ab,flatten-array/flatten_array.py,flatten-array/flatten_array.py,"def flatten(lst): """"""Completely flatten an arbitrarily-deep list"""""" return [*_flatten(lst)] def _flatten(lst): """"""Generator for flattening arbitrarily-deep lists"""""" if isinstance(lst, (list, tuple)): for item in lst: if item is None: continue else: yield from _flatten(item) else: yield lst ","def flatten(lst): """"""Completely flatten an arbitrarily-deep list"""""" return [*_flatten(lst)] def _flatten(lst): """"""Generator for flattening arbitrarily-deep lists"""""" for item in lst: if isinstance(item, (list, tuple)): yield from _flatten(item) elif item is not None: yield item ",Tidy and simplify generator code,"Tidy and simplify generator code ",Python,agpl-3.0,CubicComet/exercism-python-solutions 6fc5a47efbd4b760672b13292c5c4886842fbdbd,tests/local_test.py,tests/local_test.py,"from nose.tools import istest, assert_equal from spur import LocalShell shell = LocalShell() @istest def output_of_run_is_stored(): result = shell.run([""echo"", ""hello""]) assert_equal(""hello\n"", result.output) @istest def cwd_of_run_can_be_set(): result = shell.run([""pwd""], cwd=""/"") assert_equal(""/\n"", result.output) ","from nose.tools import istest, assert_equal from spur import LocalShell shell = LocalShell() @istest def output_of_run_is_stored(): result = shell.run([""echo"", ""hello""]) assert_equal(""hello\n"", result.output) @istest def cwd_of_run_can_be_set(): result = shell.run([""pwd""], cwd=""/"") assert_equal(""/\n"", result.output) @istest def environment_variables_can_be_added_for_run(): result = shell.run([""sh"", ""-c"", ""echo $NAME""], update_env={""NAME"": ""Bob""}) assert_equal(""Bob\n"", result.output) ",Add test for LocalShell.run with update_env,"Add test for LocalShell.run with update_env ",Python,bsd-2-clause,mwilliamson/spur.py 8d313884a52b06e2fdf9a3c0d152b9e711ff02c2,kkbox/trac/secretticket.py,kkbox/trac/secretticket.py,"from trac.core import Component, implements from trac.perm import IPermissionRequestor class KKBOXSecretTicketsPolicy(Component): implements(IPermissionRequestor) def get_permission_actions(self): return ['SECRET_VIEW'] ","from trac.ticket.model import Ticket from trac.core import Component, implements, TracError from trac.perm import IPermissionPolicy class KKBOXSecretTicketsPolicy(Component): implements(IPermissionPolicy) def __init__(self): config = self.env.config self.sensitive_keyword = config.get('kkbox', 'sensitive_keyword').strip() def check_permission(self, action, user, resource, perm): while resource: if 'ticket' == resource.realm: break resource = resource.parent if resource and 'ticket' == resource.realm and resource.id: return self.check_ticket_access(perm, resource) def check_ticket_access(self, perm, res): if not self.sensitive_keyword: return None try: ticket = Ticket(self.env, res.id) keywords = [k.strip() for k in ticket['keywords'].split(',')] if self.sensitive_keyword in keywords: cc_list = [cc.strip() for cc in ticket['cc'].split(',')] if perm.username == ticket['reporter'] or \ perm.username == ticket['owner'] or \ perm.username in cc_list: return None else: return False except TracError as e: self.log.error(e.message) return None ",Mark ticket as sensitive by keyword,"Mark ticket as sensitive by keyword Set sensitive_keyword in trac.ini as following example, These ticket has ""secret"" keyword are viewable by reporter, owner and cc. [kkbox] sensitive_keyword = secret ",Python,bsd-3-clause,KKBOX/trac-keyword-secret-ticket-plugin 0e400261b2dad04dc9f290cdbc5b16222487d4e3,setup.py,setup.py,"#!/usr/bin/env python from setuptools import setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name=""pysovo"", version=""0.4.1"", packages=['pysovo', 'pysovo.comms', 'pysovo.tests', 'pysovo.tests.resources'], package_data={'pysovo':['tests/resources/*.xml', 'templates/*.txt']}, description=""Utility scripts for reacting to received VOEvent packets"", author=""Tim Staley"", author_email=""timstaley337@gmail.com"", url=""https://github.com/timstaley/pysovo"", install_requires=required ) ","#!/usr/bin/env python from setuptools import setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name=""pysovo"", version=""0.4.1"", packages=['pysovo', 'pysovo.comms', 'pysovo.triggers', 'pysovo.tests', 'pysovo.tests.resources'], package_data={'pysovo':['tests/resources/*.xml', 'templates/*.txt']}, description=""Utility scripts for reacting to received VOEvent packets"", author=""Tim Staley"", author_email=""timstaley337@gmail.com"", url=""https://github.com/timstaley/pysovo"", install_requires=required ) ",Add triggers module to install.,"Add triggers module to install. ",Python,bsd-2-clause,timstaley/pysovo 0f6913f09b61acef4e464f81558f19982f98697e,getPortfolio.py,getPortfolio.py,,"#!/usr/bin/env python """""" Retrieves current list of ticker symbols that are in portfolio. All symbols are in lower-case. """""" #TODO: Get portfolio list from a text file. #TODO: Handle command line parms. import sys def get_portfolio(): """"""Return a list of ticker symbols for entire portfolio"""""" # Currently this list is hardcoded to match my spreadsheet layout portfolio = [ 'BTC' ,'LTC' ,'ETH' ,'' ,'' ,'ZRC' ,'NMC' ,'MSC' ,'ANC' ,'NXT' ,'XCP' ,'' ,'' ,'PTS' ,'BTSX' ,'' ,'' ,'XPM' ,'PPC' ,'FTC' ,'SWARMPRE' ,'DRK' ,'MAID' ,'TOR' ,'' ,'' ,'DOGE' ,'MEC' ,'QRK' ,'XRP' ] # Convert to lowercase for index, ticker in enumerate(portfolio): portfolio[index] = ticker.lower() return portfolio def main(): """"""Parse command line options (TODO)"""""" print get_portfolio() if __name__ == ""__main__"": main() ",Make ticker symbols lower case,"Make ticker symbols lower case ",Python,mit,SimonJester/portfolio e93939c9b0aee674ed9003727a267f6844d8ece6,DungeonsOfNoudar486/make_palette.py,DungeonsOfNoudar486/make_palette.py,,"import glob from PIL import Image from math import floor palette = [[0,0,0]]; def transform( pixel ): return [ 20 * ( pixel[ 0 ] / 20), 20 * ( pixel[ 1 ] / 20), 20 * ( pixel[ 2 ] / 20 ) ] def add_to_palette( filename ): imgFile = Image.open( filename ) img = imgFile.load() for y in range( 0, imgFile.height ): for x in range( 0, imgFile.width ): pixel = img[ x, y ] adjusted = transform( pixel ) if pixel[ 3 ] < 254: adjusted = [ 255, 0, 255 ] if palette.count( adjusted ) == 0: palette.append( adjusted ) for filename in glob.glob('res/*.png'): add_to_palette( filename ) palette.sort() print len( palette ) for pixel in palette: print str(pixel[ 0 ] ) + ""\t"" + str(pixel[ 1 ] ) + ""\t"" + str(pixel[ 2 ] ) ",Add utility to extract palette for the DOS version,"Add utility to extract palette for the DOS version ",Python,bsd-2-clause,"TheFakeMontyOnTheRun/dungeons-of-noudar,TheFakeMontyOnTheRun/dungeons-of-noudar" cbd9c312b857565bfebc2d9f8452453ca333ba92,giles.py,giles.py,"#!/usr/bin/env python2 # Giles: giles.py, the main loop. # Copyright 2012 Phil Bordelon # # 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 . import giles.server server = giles.server.Server() server.instantiate() server.loop() ","#!/usr/bin/env python2 # Giles: giles.py, the main loop. # Copyright 2012 Phil Bordelon # # 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 . import giles.server import sys server = giles.server.Server() if len(sys.argv) == 2: port = int(sys.argv[1]) else: port = 9435 server.instantiate(port) server.loop() ",Support choosing a port on the command line.,"Support choosing a port on the command line. Just put a number as the only CLI for now. Useful for me testing changes now that I'm actually keeping the server running. ",Python,agpl-3.0,sunfall/giles 68b0f560322884967b817ad87cef8c1db9600dbd,app/main/errors.py,app/main/errors.py,"from flask import render_template from app.main import main @main.app_errorhandler(400) def page_not_found(e): return _render_error_page(500) @main.app_errorhandler(404) def page_not_found(e): return _render_error_page(404) @main.app_errorhandler(500) def exception(e): return _render_error_page(500) @main.app_errorhandler(503) def service_unavailable(e): return _render_error_page(503) def _render_error_page(status_code): template_map = { 404: ""errors/404.html"", 500: ""errors/500.html"", 503: ""errors/500.html"", } if status_code not in template_map: status_code = 500 template_data = main.config['BASE_TEMPLATE_DATA'] return render_template(template_map[status_code], **template_data), status_code ","from flask import render_template from app.main import main @main.app_errorhandler(400) def page_not_found(e): print(e.message) return _render_error_page(500) @main.app_errorhandler(404) def page_not_found(e): print(e.message) return _render_error_page(404) @main.app_errorhandler(500) def exception(e): print(e.message) return _render_error_page(500) @main.app_errorhandler(503) def service_unavailable(e): print(e.message) return _render_error_page(503) def _render_error_page(status_code): template_map = { 404: ""errors/404.html"", 500: ""errors/500.html"", 503: ""errors/500.html"", } if status_code not in template_map: status_code = 500 template_data = main.config['BASE_TEMPLATE_DATA'] return render_template(template_map[status_code], **template_data), status_code ",Add print statements for all error types,"Add print statements for all error types ",Python,mit,"alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend,alphagov/notify-frontend" d852781fe93c7a37b90387e2b388bf18ed3823d1,command/install_ext.py,command/install_ext.py,"""""""install_ext Implement the Distutils ""install_ext"" command to install extension modules."""""" # created 1999/09/12, Greg Ward __revision__ = ""$Id$"" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = ""install C/C++ extension modules"" user_options = [ ('install-dir=', 'd', ""directory to install to""), ('build-dir=','b', ""build directory (where to install from)""), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire ""build/platlib"" directory (or whatever it really # is; ""build/platlib"" is the default) to the installation target # (eg. ""/usr/local/lib/python1.5/site-packages""). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt ","""""""install_ext Implement the Distutils ""install_ext"" command to install extension modules."""""" # created 1999/09/12, Greg Ward __revision__ = ""$Id$"" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = ""install C/C++ extension modules"" user_options = [ ('install-dir=', 'd', ""directory to install to""), ('build-dir=','b', ""build directory (where to install from)""), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire ""build/platlib"" directory (or whatever it really # is; ""build/platlib"" is the default) to the installation target # (eg. ""/usr/local/lib/python1.5/site-packages""). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt ","Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.","Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well. ",Python,mit,"pypa/setuptools,pypa/setuptools,pypa/setuptools" 29b26aa8b44ea5820cfcd20e324d2c3631338228,portal/models/research_protocol.py,portal/models/research_protocol.py,"""""""Research Protocol module"""""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """"""ResearchProtocol model for tracking QB versions"""""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError(""missing required name field"") rp = ResearchProtocol.query.filter_by(name=data['name']).first() if not rp: rp = cls(data['name']) return rp def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d ","""""""Research Protocol module"""""" from datetime import datetime from ..database import db from ..date_tools import FHIR_datetime class ResearchProtocol(db.Model): """"""ResearchProtocol model for tracking QB versions"""""" __tablename__ = 'research_protocols' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.Text, nullable=False, unique=True) created_at = db.Column(db.DateTime, nullable=False) def __init__(self, name): self.name = name self.created_at = datetime.utcnow() @classmethod def from_json(cls, data): if 'name' not in data: raise ValueError(""missing required name field"") instance = cls(data['name']) return instance.update_from_json(data) def update_from_json(self, data): self.name = data['name'] if 'created_at' in data: self.created_at = data['created_at'] return self def as_json(self): d = {} d['id'] = self.id d['resourceType'] = 'ResearchProtocol' d['name'] = self.name d['created_at'] = FHIR_datetime.as_fhir(self.created_at) return d ",Implement common pattern from_json calls update_from_json,"Implement common pattern from_json calls update_from_json ",Python,bsd-3-clause,"uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal" c9f8b832761525c2f04a71515b743be87f2e4a58,setup.py,setup.py,"from distutils.core import setup setup(name='q', version='2.3', py_modules=['q'], description='Quick-and-dirty debugging output for tired programmers', author='Ka-Ping Yee', author_email='ping@zesty.ca', license='Apache License 2.0', url='http://github.com/zestyping/q', classifiers=[ 'Programming Language :: Python', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License' ]) ","from distutils.core import setup setup(name='q', version='2.4', py_modules=['q'], description='Quick-and-dirty debugging output for tired programmers', author='Ka-Ping Yee', author_email='ping@zesty.ca', license='Apache License 2.0', url='http://github.com/zestyping/q', classifiers=[ 'Programming Language :: Python', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License' ]) ",Advance PyPI version to 2.4.,"Advance PyPI version to 2.4. ",Python,apache-2.0,zestyping/q 597000dac85ef0760e04f3c6d885bde531fa86a2,Lib/test/crashers/decref_before_assignment.py,Lib/test/crashers/decref_before_assignment.py,,""""""" General example for an attack against code like this: Py_DECREF(obj->attr); obj->attr = ...; here in Module/_json.c:scanner_init(). Explanation: if the first Py_DECREF() calls either a __del__ or a weakref callback, it will run while the 'obj' appears to have in 'obj->attr' still the old reference to the object, but not holding the reference count any more. Status: progress has been made replacing these cases, but there is an infinite number of such cases. """""" import _json, weakref class Ctx1(object): encoding = ""utf8"" strict = None object_hook = None object_pairs_hook = None parse_float = None parse_int = None parse_constant = None class Foo(unicode): pass def delete_me(*args): print scanner.encoding.__dict__ class Ctx2(Ctx1): @property def encoding(self): global wref f = Foo(""utf8"") f.abc = globals() wref = weakref.ref(f, delete_me) return f scanner = _json.make_scanner(Ctx1()) scanner.__init__(Ctx2()) ","Add a crasher for the documented issue of calling ""Py_DECREF(self->xxx)"";","Add a crasher for the documented issue of calling ""Py_DECREF(self->xxx)""; ",Python,mit,"sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator" 491ddec4c429993b9149eb61139fe71d691f697f,mysite/search/models.py,mysite/search/models.py,"from django.db import models # Create your models here. class Project(models.Model): name = models.CharField(max_length=200) language = models.CharField(max_length=200) icon_url = models.URLField(max_length=200) class Bug(models.Model): project = models.ForeignKey(Project) title = models.CharField(max_length=200) description = models.TextField() status = models.CharField(max_length=200) importance = models.CharField(max_length=200) people_involved = models.IntegerField() date_reported = models.DateTimeField() last_touched = models.DateTimeField() last_polled = models.DateTimeField() submitter_username = models.CharField(max_length=200) submitter_realname = models.CharField(max_length=200) ","from django.db import models # Create your models here. class Project(models.Model): name = models.CharField(max_length=200) language = models.CharField(max_length=200) icon_url = models.URLField(max_length=200) class Bug(models.Model): project = models.ForeignKey(Project) title = models.CharField(max_length=200) description = models.TextField() status = models.CharField(max_length=200) importance = models.CharField(max_length=200) people_involved = models.IntegerField() date_reported = models.DateTimeField() last_touched = models.DateTimeField() last_polled = models.DateTimeField() submitter_username = models.CharField(max_length=200) submitter_realname = models.CharField(max_length=200) canonical_bug_link = models.URLField(max_length=200) ",Add a bug link field,"Add a bug link field ",Python,agpl-3.0,"onceuponatimeforever/oh-mainline,nirmeshk/oh-mainline,moijes12/oh-mainline,SnappleCap/oh-mainline,openhatch/oh-mainline,nirmeshk/oh-mainline,SnappleCap/oh-mainline,Changaco/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,Changaco/oh-mainline,vipul-sharma20/oh-mainline,nirmeshk/oh-mainline,ojengwa/oh-mainline,Changaco/oh-mainline,moijes12/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,willingc/oh-mainline,heeraj123/oh-mainline,mzdaniel/oh-mainline,mzdaniel/oh-mainline,openhatch/oh-mainline,ojengwa/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,waseem18/oh-mainline,vipul-sharma20/oh-mainline,mzdaniel/oh-mainline,SnappleCap/oh-mainline,sudheesh001/oh-mainline,sudheesh001/oh-mainline,heeraj123/oh-mainline,eeshangarg/oh-mainline,onceuponatimeforever/oh-mainline,onceuponatimeforever/oh-mainline,campbe13/openhatch,sudheesh001/oh-mainline,willingc/oh-mainline,campbe13/openhatch,vipul-sharma20/oh-mainline,Changaco/oh-mainline,sudheesh001/oh-mainline,onceuponatimeforever/oh-mainline,openhatch/oh-mainline,ehashman/oh-mainline,willingc/oh-mainline,ojengwa/oh-mainline,jledbetter/openhatch,jledbetter/openhatch,Changaco/oh-mainline,vipul-sharma20/oh-mainline,ehashman/oh-mainline,openhatch/oh-mainline,sudheesh001/oh-mainline,mzdaniel/oh-mainline,jledbetter/openhatch,waseem18/oh-mainline,onceuponatimeforever/oh-mainline,jledbetter/openhatch,waseem18/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,ojengwa/oh-mainline,moijes12/oh-mainline,eeshangarg/oh-mainline,willingc/oh-mainline,openhatch/oh-mainline,eeshangarg/oh-mainline,heeraj123/oh-mainline,nirmeshk/oh-mainline,jledbetter/openhatch,heeraj123/oh-mainline,moijes12/oh-mainline,SnappleCap/oh-mainline,willingc/oh-mainline,ojengwa/oh-mainline,ehashman/oh-mainline,campbe13/openhatch,moijes12/oh-mainline,SnappleCap/oh-mainline,ehashman/oh-mainline,campbe13/openhatch,heeraj123/oh-mainline,vipul-sharma20/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch" 77cdf4de05b3edfe3231ffd831af38b290b178a1,signals.py,signals.py,"from django.core.signals import Signal process_completed = Signal(providing_args=['result_text', 'result_data', 'files', 'profile','logs']) process_aborted = Signal(providing_args=['error_text','result_data','profile','logs']) ","from django.core.signals import Signal process_finished = Signal(providing_args=['result_text', 'result_data', 'files', 'profile','logs']) process_aborted = Signal(providing_args=['error_text','result_data','profile','logs']) ",Add a little doc and callbacks,"Add a little doc and callbacks ",Python,bsd-3-clause,"hydroshare/django_docker_processes,JeffHeard/django_docker_processes" e783dfef25eb1e3b06064fb2bd125cef4f56ec08,linter.py,linter.py,"# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-gjslint # License: MIT # """"""This module exports the GJSLint plugin linter class."""""" from SublimeLinter.lint import Linter class GJSLint(Linter): """"""Provides an interface to the gjslint executable."""""" language = ('javascript', 'html') cmd = 'gjslint --nobeep --nosummary' regex = r'^Line (?P\d+), (?:(?PE)|(?PW)):\d+: (?P[^""]+(?P""[^""]+"")?)$' comment_re = r'\s*/[/*]' defaults = { '--jslint_error:,+': '', '--disable:,': '', '--max_line_length:': None } inline_settings = 'max_line_length' inline_overrides = 'disable' tempfile_suffix = 'js' selectors = { 'html': 'source.js.embedded.html' } ","# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Aparajita Fishman # Copyright (c) 2013 Aparajita Fishman # # Project: https://github.com/SublimeLinter/SublimeLinter-contrib-gjslint # License: MIT # """"""This module exports the GJSLint plugin linter class."""""" from SublimeLinter.lint import Linter class GJSLint(Linter): """"""Provides an interface to the gjslint executable."""""" syntax = ('javascript', 'html') cmd = 'gjslint --nobeep --nosummary' regex = r'^Line (?P\d+), (?:(?PE)|(?PW)):\d+: (?P[^""]+(?P""[^""]+"")?)$' comment_re = r'\s*/[/*]' defaults = { '--jslint_error:,+': '', '--disable:,': '', '--max_line_length:': None } inline_settings = 'max_line_length' inline_overrides = 'disable' tempfile_suffix = 'js' selectors = { 'html': 'source.js.embedded.html' } ","Change 'language' to 'syntax', that is more precise terminology.","Change 'language' to 'syntax', that is more precise terminology. ",Python,mit,SublimeLinter/SublimeLinter-gjslint 9763156fbf2ccfbc5679c2264593917aa416bc24,tests/unit/test_soundcloud_track.py,tests/unit/test_soundcloud_track.py,,"from nose.tools import * # noqa import datetime from pmg.models.soundcloud_track import SoundcloudTrack from pmg.models import db, File, Event, EventFile from tests import PMGTestCase class TestUser(PMGTestCase): def test_get_unstarted_query(self): event = Event( date=datetime.datetime.today(), title=""Test event"", type=""committee-meeting"", ) file = File( title=""Test Audio"", file_mime=""audio/mp3"", file_path=""tmp/file"", file_bytes=""1"", origname=""Test file"", description=""Test file"", playtime=""3min"", # event_files=db.relationship(""EventFile"", lazy=True), ) event_file = EventFile( event=event, file=file ) db.session.add(event) db.session.add(file) db.session.add(event_file) db.session.commit() query = SoundcloudTrack.get_unstarted_query() self.assertEquals(1, query.count()) self.assertIn(file, query.all()) ",Add unit test for Soundcloud get_unstarted_query function,"Add unit test for Soundcloud get_unstarted_query function ",Python,apache-2.0,"Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2" 9dce07895a773998469aeed8c1cfb8476d4264eb,application.py,application.py,"#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) if __name__ == '__main__': manager.run() ","#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'development') manager = Manager(application) manager.add_command(""runserver"", Server(port=5001)) if __name__ == '__main__': manager.run() ",Update to run on port 5001,"Update to run on port 5001 For development we will want to run multiple apps, so they should each bind to a different port number. ",Python,mit,"RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,RichardKnop/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api" d83c9cd2633f08c75a3f1a6767984d663c6f6f28,setup.py,setup.py,"#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-sensible-caching', url=""https://chris-lamb.co.uk/projects/django-sensible-caching"", version='2.0.1', description=""Non-magical object caching for Django."", author=""Chris Lamb"", author_email=""chris@chris-lamb.co.uk"", license=""BSD"", packages=find_packages(), ) ","#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-sensible-caching', url=""https://chris-lamb.co.uk/projects/django-sensible-caching"", version='2.0.1', description=""Non-magical object caching for Django."", author=""Chris Lamb"", author_email=""chris@chris-lamb.co.uk"", license=""BSD"", packages=find_packages(), install_requires=( 'Django>=1.8', ), ) ",Update Django requirement to latest LTS,"Update Django requirement to latest LTS ",Python,bsd-3-clause,lamby/django-sensible-caching 4320eecc294fa1233a2ad7b4cdec1e2dc1e83b37,testing/test_simbad.py,testing/test_simbad.py,"import pytest import vcr try: from unittest import mock except ImportError: import mock from k2catalogue.models import EPIC, create_session from k2catalogue.simbad import Simbad @pytest.fixture def session(): return create_session() @pytest.fixture def epic(session): return session.query(EPIC).filter(EPIC.epic_id == 201763507).first() @pytest.fixture def simbad(epic): return Simbad(epic) @pytest.fixture def form_data(simbad): return simbad.form_data(radius=5.) @vcr.use_cassette('.cassettes/response.yml') @pytest.fixture def response(simbad): return simbad.send_request() def test_form_data(form_data): assert form_data['Coord'] == '169.18 4.72' def test_response(response): assert response.status_code == 200 def test_open(simbad): with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open: simbad.open(radius=10) url, = mock_open.call_args[0] assert 'file://' in url and 'html' in url ","import pytest import vcr try: from unittest import mock except ImportError: import mock from k2catalogue.models import EPIC, create_session from k2catalogue.simbad import Simbad @pytest.fixture def session(): return create_session() @pytest.fixture def epic(session): return mock.Mock(ra=123.456, dec=-56.789) @pytest.fixture def simbad(epic): return Simbad(epic) @pytest.fixture def form_data(simbad): return simbad.form_data(radius=5.) @vcr.use_cassette('.cassettes/response.yml') @pytest.fixture def response(simbad): return simbad.send_request() def test_form_data(form_data): assert form_data['Coord'] == '123.46 -56.79' def test_response(response): assert response.status_code == 200 def test_open(simbad): with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open: simbad.open(radius=10) url, = mock_open.call_args[0] assert 'file://' in url and 'html' in url ",Remove real database during testing,"Remove real database during testing ",Python,mit,mindriot101/k2catalogue affbf76e62427080c52a42fe6fb17dd42df81d9b,setup.py,setup.py,"from setuptools import setup, find_packages setup( name='gdcdatamodel', packages=find_packages(), install_requires=[ 'pytz==2016.4', 'graphviz==0.4.2', 'jsonschema==2.5.1', 'python-dateutil==2.4.2', 'psqlgraph', 'gdcdictionary', 'dictionaryutils>=2.0.0,<3.0.0', 'cdisutils', ], package_data={ ""gdcdatamodel"": [ ""xml_mappings/*.yaml"", ] }, dependency_links=[ 'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils', 'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph', 'git+https://github.com/NCI-GDC/gdcdictionary.git@1.14.0#egg=gdcdictionary', ], entry_points={ 'console_scripts': [ 'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main' ] }, ) ","from setuptools import setup, find_packages setup( name='gdcdatamodel', packages=find_packages(), install_requires=[ 'pytz==2016.4', 'graphviz==0.4.2', 'jsonschema==2.5.1', 'python-dateutil==2.4.2', 'psqlgraph', 'gdcdictionary', 'dictionaryutils>=2.0.0,<3.0.0', 'cdisutils', ], package_data={ ""gdcdatamodel"": [ ""xml_mappings/*.yaml"", ] }, dependency_links=[ 'git+https://github.com/NCI-GDC/cdisutils.git@863ce13772116b51bcf5ce7e556f5df3cb9e6f63#egg=cdisutils', 'git+https://github.com/NCI-GDC/psqlgraph.git@1.2.0#egg=psqlgraph', 'git+https://github.com/NCI-GDC/gdcdictionary.git@release/marvin#egg=gdcdictionary', ], entry_points={ 'console_scripts': [ 'gdc_postgres_admin=gdcdatamodel.gdc_postgres_admin:main' ] }, ) ",Update pins for marvin release,"release(marvin): Update pins for marvin release ",Python,apache-2.0,"NCI-GDC/gdcdatamodel,NCI-GDC/gdcdatamodel" 020b2518efce2d973093a366e0a9abfadbd602fd,main/forms.py,main/forms.py,"from django import forms class IndexForm(forms.Form): usos_auth_pin = forms.IntegerField(label='USOS Authorization PIN') id_list = forms.CharField( widget=forms.Textarea, label='ID List', help_text='List of students IDs to query, one per line.') student_id_regex = forms.CharField( label='Student ID regex', help_text='Regular expression used to match the student ID in each ' 'line. If cannot match (or a student is not found in the ' 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'})) ","from django import forms class IndexForm(forms.Form): usos_auth_pin = forms.IntegerField( label='USOS Authorization PIN', help_text='If not filled out, then only the cache is used. Note that ' 'this means that some IDs may fail to be looked up.', required=False) id_list = forms.CharField( widget=forms.Textarea, label='ID List', help_text='List of students IDs to query, one per line.') student_id_regex = forms.CharField( label='Student ID regex', help_text='Regular expression used to match the student ID in each ' 'line. If cannot match (or a student is not found in the ' 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'})) ",Add help_text and required=False to the PIN field,"Add help_text and required=False to the PIN field ",Python,mit,"m4tx/usos-id-mapper,m4tx/usos-id-mapper" 9b8cbfcf33ba644670a42490db7de4249e5ff080,invocations/docs.py,invocations/docs.py,"import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run(""rm -rf %s"" % build) @task def browse_docs(): run(""open %s"" % os.path.join(build, 'index.html')) @task def docs(clean=False, browse=False): if clean: clean_docs.body() run(""sphinx-build %s %s"" % (docs_dir, build), pty=True) if browse: browse_docs.body() ","import os from invoke.tasks import task from invoke.runner import run docs_dir = 'docs' build = os.path.join(docs_dir, '_build') @task def clean_docs(): run(""rm -rf %s"" % build) @task def browse_docs(): run(""open %s"" % os.path.join(build, 'index.html')) @task def docs(clean=False, browse=False): if clean: clean_docs() run(""sphinx-build %s %s"" % (docs_dir, build), pty=True) if browse: browse_docs() ",Leverage __call__ on task downstream,"Leverage __call__ on task downstream ",Python,bsd-2-clause,"mrjmad/invocations,alex/invocations,pyinvoke/invocations,singingwolfboy/invocations" 02095500794565fc84aee8272bfece1b39bc270f,examples/example_architecture_upload.py,examples/example_architecture_upload.py,"from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import glob import datetime from teamscale_client import TeamscaleClient from teamscale_client.constants import CoverageFormats TEAMSCALE_URL = ""http://localhost:8080"" USERNAME = ""admin"" PASSWORD = ""admin"" PROJECT_NAME = ""test"" if __name__ == '__main__': client = TeamscaleClient(TEAMSCALE_URL, USERNAME, PASSWORD, PROJECT_NAME) client.upload_architectures({""architectures/system.architecture"": ""/home/user/a/path/to/system.architecture""}, datetime.datetime.now(), ""Upload architecture"", ""test-partition"") ","from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import glob import datetime from teamscale_client import TeamscaleClient from teamscale_client.constants import CoverageFormats TEAMSCALE_URL = ""http://localhost:8080"" USERNAME = ""admin"" PASSWORD = ""F0VzQ_2Q2wqGmBFBrI6EIVWVK4QxR55o"" PROJECT_NAME = ""test"" if __name__ == '__main__': client = TeamscaleClient(TEAMSCALE_URL, USERNAME, PASSWORD, PROJECT_NAME) client.upload_architectures({""archs/abap.architecture"": ""/home/kinnen/repos/conqat-cqse_bmw/engine/eu.cqse.conqat.engine.abap/abap_exporter.architecture""}, datetime.datetime.now(), ""Upload architecture"") ",Update example for architecture upload,"Update example for architecture upload ",Python,apache-2.0,cqse/teamscale-client-python eddf3ec729fd385fd3ec2ec425db1d777a302e46,tensorprob/distributions/exponential.py,tensorprob/distributions/exponential.py,"import tensorflow as tf from .. import config from ..distribution import Distribution @Distribution def Exponential(lambda_, name=None): X = tf.placeholder(config.dtype, name=name) Distribution.logp = tf.log(lambda_) - lambda_*X def cdf(lim): return tf.constant(1, dtype=config.dtype) - tf.exp(-lambda_*lim) Distribution.integral = lambda lower, upper: cdf(upper) - cdf(lower) return X ","import tensorflow as tf from .. import config from ..distribution import Distribution @Distribution def Exponential(lambda_, name=None): X = tf.placeholder(config.dtype, name=name) Distribution.logp = tf.log(lambda_) - lambda_*X def integral(lower, upper): return tf.exp(-lambda_*lower) - tf.exp(-lambda_*upper) Distribution.integral = integral return X ",Correct integral used for Exponential distributon,"Correct integral used for Exponential distributon ",Python,mit,"ibab/tensorprob,tensorprob/tensorprob,ibab/tensorfit" ff9a4f89d81c2059f51f7346700ce16972f04e36,django_basic_tinymce_flatpages/admin.py,django_basic_tinymce_flatpages/admin.py,"from django.conf import settings from django.contrib import admin from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin from django.contrib.flatpages.models import FlatPage from django.utils.module_loading import import_string FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.TinyMCE') FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', default={'attrs': {'cols': 100, 'rows': 15}}) class PageForm(FlatpageForm): class Meta: model = FlatPage widgets = { 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), } class PageAdmin(FlatPageAdmin): """""" Page Admin """""" form = PageForm admin.site.unregister(FlatPage) admin.site.register(FlatPage, PageAdmin) ","from django.conf import settings from django.contrib import admin from django.contrib.flatpages.admin import FlatpageForm, FlatPageAdmin from django.contrib.flatpages.models import FlatPage from django.utils.module_loading import import_string FLATPAGE_WIDGET = getattr(settings, 'FLATPAGE_WIDGET', 'tinymce.widgets.TinyMCE') FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', {'attrs': {'cols': 100, 'rows': 15}}) class PageForm(FlatpageForm): class Meta: model = FlatPage widgets = { 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), } class PageAdmin(FlatPageAdmin): """""" Page Admin """""" form = PageForm admin.site.unregister(FlatPage) admin.site.register(FlatPage, PageAdmin) ",Fix getattr() takes no keyword arguments,"Fix getattr() takes no keyword arguments ",Python,bsd-3-clause,ad-m/django-basic-tinymce-flatpages 8ecc24ab865ff9dec647fe69d78af0a63f0a902a,nap/rest/models.py,nap/rest/models.py,"from __future__ import unicode_literals from .. import http from .publisher import Publisher from django.db import transaction from django.shortcuts import get_object_or_404 class ModelPublisher(Publisher): '''A Publisher with useful methods to publish Models''' @property def model(self): '''By default, we try to get the model from our serialiser''' # XXX Should this call get_serialiser? return self.serialiser._meta.model # Auto-build serialiser from model class? def get_object_list(self): return self.model.objects.all() def get_object(self, object_id): return get_object_or_404(self.get_object_list(), pk=object_id) def list_post_default(self, request, **kwargs): data = self.get_request_data() serialiser = self.get_serialiser() serialiser_kwargs = self.get_serialiser_kwargs() try: with transaction.atomic(): obj = serialiser.object_inflate(data, **serialiser_kwargs) except ValueError as e: return http.BadRequest(str(e)) return self.render_single_object(obj, serialiser) ","from __future__ import unicode_literals from .. import http from ..shortcuts import get_object_or_404 from .publisher import Publisher from django.db import transaction class ModelPublisher(Publisher): '''A Publisher with useful methods to publish Models''' @property def model(self): '''By default, we try to get the model from our serialiser''' # XXX Should this call get_serialiser? return self.serialiser._meta.model # Auto-build serialiser from model class? def get_object_list(self): return self.model.objects.all() def get_object(self, object_id): return get_object_or_404(self.get_object_list(), pk=object_id) def list_post_default(self, request, **kwargs): data = self.get_request_data() serialiser = self.get_serialiser() serialiser_kwargs = self.get_serialiser_kwargs() try: with transaction.atomic(): obj = serialiser.object_inflate(data, **serialiser_kwargs) except ValueError as e: return http.BadRequest(str(e)) return self.render_single_object(obj, serialiser) ",Use our own get_object_or_404 for ModelPublisher.get_object,"Use our own get_object_or_404 for ModelPublisher.get_object ",Python,bsd-3-clause,"MarkusH/django-nap,limbera/django-nap" 9c381721f4b4febef64276a2eb83c5a9169f7b8c,meta-analyze.py,meta-analyze.py,"#!/usr/bin/env python import argparse def parsed_command_line(): """"""Returns an object that results from parsing the command-line for this program argparse.ArgumentParser(...).parse_ags() """""" parser = argparse.ArgumentParser( description='Run multiple network snp analysis algorithms'); parser.add_argument('--plink_in', type=argparse.FileType('r'), help='Path to a plink association file https://www.cog-genomics.org/plink2/formats#assoc') return parser.parse_args() def input_files(parsed_args): """"""Returns a list of input files that were passed on the command line parsed_args: the result of parsing the command-line arguments """""" if parsed_args.plink_in: print ""Plink input: ""+str(parsed_args.plink_in.name); parsed = parsed_command_line() input_files(parsed) ","#!/usr/bin/env python import argparse class InputFile: """"""Represents a data in a specified format"""""" def __init__(self, file_format, path): self.file_format = file_format self.path = path def __repr__(self): return ""InputFile('{}','{}')"".format(self.file_format, self.path) def parsed_command_line(): """"""Returns an object that results from parsing the command-line for this program argparse.ArgumentParser(...).parse_ags() """""" parser = argparse.ArgumentParser( description='Run multiple network snp analysis algorithms'); parser.add_argument('--plink_assoc_in', type=argparse.FileType('r'), help='Path to a plink association file https://www.cog-genomics.org/plink2/formats#assoc') return parser.parse_args() def input_files(parsed_args): """"""Returns a list of input files that were passed on the command line parsed_args: the result of parsing the command-line arguments """""" files=[] if parsed_args.plink_assoc_in: files.append(InputFile(""plink_assoc"", parsed_args.plink_assoc_in.name)) return files def plink_assoc_to_networkx(input_path, output_path): """"""Create a new networkx formatted file at output_path"""""" pass converters = {('plink_assoc','networkx'):plink_assoc_to_networkx} parsed = parsed_command_line() print "","".join([str(i) for i in input_files(parsed)]) ",Add input file and converter abstraction,"Add input file and converter abstraction ",Python,cc0-1.0,"NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs" 6dab43543e1b6a1e1e8119db9b38cc685dd81f82,ckanext/qa/controllers/base.py,ckanext/qa/controllers/base.py,"from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): def __init__(self, *args, **kwargs): super(QAController, self).__init(*args, **kwargs)","from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): pass ",Fix typo in constructor. Seems unnecessary anyway.,"Fix typo in constructor. Seems unnecessary anyway. ",Python,mit,"ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa" 24d742e444c84df99629d8a6aff7ca7e6c90f995,scheduler/misc/detect_stuck_active_invs.py,scheduler/misc/detect_stuck_active_invs.py,,"#!/usr/bin/env python # Copyright 2018 The LUCI Authors. # # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """"""Finds jobs with old entries (>1d) in ActiveInvocations list. Usage: prpc login ./detect_stuck_active_invs.py luci-scheduler-dev.appspot.com Requires the caller to be in 'administrators' group. """""" import json import subprocess import sys import time def prpc(host, method, body): p = subprocess.Popen( ['prpc', 'call', host, method], stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, _ = p.communicate(json.dumps(body)) if p.returncode: raise Exception('Call to %s failed' % method) return json.loads(out) def check_job(host, job_ref): print 'Checking %s/%s' % (job_ref['project'], job_ref['job']) state = prpc(host, 'internal.admin.Admin.GetDebugJobState', job_ref) active_invs = state.get('activeInvocations', []) if not active_invs: print ' No active invocations' return [] stuck = [] for inv_id in active_invs: print ' ...checking %s' % inv_id inv = prpc(host, 'scheduler.Scheduler.GetInvocation', { 'jobRef': job_ref, 'invocationId': inv_id, }) started = time.time() - int(inv['startedTs']) / 1000000.0 if started > 24 * 3600: print ' it is stuck!' stuck.append((job_ref, inv_id)) return stuck def main(): if len(sys.argv) != 2: print >> sys.stderr, 'Usage: %s ' % sys.argv[0] return 1 host = sys.argv[1] stuck = [] for job in prpc(host, 'scheduler.Scheduler.GetJobs', {})['jobs']: stuck.extend(check_job(host, job['jobRef'])) if not stuck: print 'No invocations are stuck' return print print 'All stuck invocations: ' for job_ref, inv_id in stuck: print '%s/%s %s' % (job_ref['project'], job_ref['job'], inv_id) return 0 if __name__ == '__main__': sys.exit(main()) ",Add adhoc script to detect jobs with stuck ActiveInvocations list.,"[scheduler] Add adhoc script to detect jobs with stuck ActiveInvocations list. R=a30c74fa30536fe7ea81ed6dec202e35e149e1fd@chromium.org BUG=852142 Change-Id: Idae7f05c5045a72ff85db8587f8bd74c0b80fb06 Reviewed-on: https://chromium-review.googlesource.com/1098463 Reviewed-by: Andrii Shyshkalov Commit-Queue: Vadim Shtayura <9f116ddb1b24f6fc1916a676eb17161b6c07dfc1@chromium.org> ",Python,apache-2.0,"luci/luci-go,luci/luci-go,luci/luci-go,luci/luci-go,luci/luci-go,luci/luci-go" 3ebb2731d6389170e0bef0dab66dc7c4ab41152e,thread_pool_test.py,thread_pool_test.py,,"import thread_pool import unittest from six.moves import queue class TestThreadPool(unittest.TestCase): def _producer_thread(self, results): for i in range(10): results.put(i) def _consumer_thread(self, results): for i in range(10): self.assertEqual(results.get(), i) def testContextManager(self): results = queue.Queue(maxsize=1) with thread_pool.ThreadPool(2) as pool: pool.add(self._producer_thread, results) pool.add(self._consumer_thread, results) def testJoin(self): results = queue.Queue(maxsize=1) pool = thread_pool.ThreadPool(2) pool.add(self._producer_thread, results) pool.add(self._consumer_thread, results) pool.join() ",Add a unit-test for thread_pool.py.,"Add a unit-test for thread_pool.py. ",Python,mit,graveljp/smugcli 93373242eab8d387a9b13c567239fa2e36b10ffa,mqtt_logger/management/commands/runmqttlistener.py,mqtt_logger/management/commands/runmqttlistener.py,"from django.core.management.base import BaseCommand, CommandError from mqtt_logger.models import * class Command(BaseCommand): help = 'Start listening to mqtt subscriptions and save messages in database.' def add_arguments(self, parser): pass def handle(self, *args, **options): self.stdout.write(""Starting MQTT listener..."") clients = MQTTSubscription.subscribe_all(start_loop=True) for c in clients: self.stdout.write("" %s:%s %s""%(c.host, c.port, c.topics)) self.stdout.write(""MQTT listener started."") self.stdout.write(""Hit to quit."") wait = raw_input() ","from django.core.management.base import BaseCommand, CommandError from mqtt_logger.models import * import time class Command(BaseCommand): help = 'Start listening to mqtt subscriptions and save messages in database.' def add_arguments(self, parser): pass def handle(self, *args, **options): self.stdout.write(""Starting MQTT listener..."") subs = list(MQTTSubscription.objects.filter(active=True)) for s in subs: self.stdout.write("" Connecting to %s:%s %s""%(s.server, s.port, s.topic)) s.client = s.subscribe(start_loop=True) while(True): time.sleep(10) newsubs = MQTTSubscription.objects.filter(active=True) for s in subs: if s not in newsubs: self.stdout.write("" Disconnecting from %s:%s %s""%(s.server, s.port, s.topic)) s.client.disconnect() subs.remove(s) for s in newsubs: if s not in subs: self.stdout.write("" Connecting to %s:%s %s""%(s.server, s.port, s.topic)) s.client = s.subscribe(start_loop=True) subs.append(s) ",Make the listener automatically update the subscriptions.,"Make the listener automatically update the subscriptions. ",Python,mit,"ast0815/mqtt-hub,ast0815/mqtt-hub" e84d6dc5be2e2ac2d95b81e4df18bc0ad939916a,__init__.py,__init__.py,"import os from flask import Flask, redirect, request, render_template from flask_mail import Mail, Message app = Flask (__name__) ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg']) mail = Mail(app) @app.route(""/"") def index(): return render_template('in-development.html.j2') if __name__ == ""__main__"": app.run(host='0.0.0.0') ","import os from flask import Flask, redirect, request, render_template from flask_mail import Mail, Message app = Flask (__name__) ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg']) mail = Mail(app) @app.route(""/"") def index(): return render_template('index.html.j2') if __name__ == ""__main__"": app.run() ",Split into new branch for development of the main site,"Split into new branch for development of the main site ",Python,mit,"JonathanPeterCole/Tech-Support-Site,JonathanPeterCole/Tech-Support-Site" 14aba0695514866439164f48fe1f66390719431f,scripts/select_gamma.py,scripts/select_gamma.py,,"#!/usr/bin/python # -*- coding: utf-8 -*- """""" Created on Fri Oct 18 10:13:48 2013 @author: amnon ### 80 char max please Look at all the gammaproteobacteria and select candidate contamination sequence OTUs output: a list of sorted gammaproteobacteria (or other) otuids, according to mean frequency """""" import sys import argparse import numpy as np # to load a BIOM table from biom.parse import parse_biom_table from biom.util import biom_open def TestAll(biomfile, outputfile, taxonomyclass, taxonomyname,level): """"""doc string here, a one liner ...and then more detail """""" odat=[] t = parse_biom_table(biom_open(biomfile,'U')) t2 = t.normObservationBySample() # to iterate over the table by observation, doing something based on the # taxonomy: class_idx = taxonomyclass for values, ids, metadata in t2.iterObservations(): tname=metadata['taxonomy'][class_idx].lstrip() if tname == taxonomyname: mv = np.mean(values) odat.append((ids,mv)) # odat.sort(key=lambda tup: tup[1], reverse=True) odat.sort(key=lambda tup: tup[1]) csum=[(odat[0][0],odat[0][1],odat[0][1])] for cval in odat[1:]: csum.append((cval[0],cval[1],csum[-1][2]+cval[1])) # no get it from big to small csum.reverse() # and write everything above the threshold (to filter) snames=open(outputfile,'w') for cval in csum: if cval[2]>=level: snames.write(cval[0]+""\t""+str(cval[1])+""\t""+str(cval[2])+'\n') snames.close() def main(argv): parser=argparse.ArgumentParser(description='Select Gammaproteobacteria (or other group) contamination candidates') parser.add_argument('-i','--biom',help='biom file of the experiment') parser.add_argument('-o','--output',help='output file name') parser.add_argument('-c','--classpos',help='class of taxonomy name (0-kingdom,1-phylum etc.',default=2) parser.add_argument('-t','--taxonomy',help='taxonomy name (including c__ or equivalent)',default='c__Gammaproteobacteria') parser.add_argument('-l','--level',help='minimal cumulative level for OTUs to filter (use 0 to get all of them)',default='0.03') args=parser.parse_args(argv) TestAll(args.biom,args.output,int(args.classpos),args.taxonomy,float(args.level)) if __name__ == ""__main__"": main(sys.argv[1:]) ",Add selcet_gamma.py (authored by Amnon),"Add selcet_gamma.py (authored by Amnon) Used in the filtering notebook. ",Python,bsd-3-clause,"EmbrietteH/American-Gut,wasade/American-Gut,JWDebelius/American-Gut,mortonjt/American-Gut,wasade/American-Gut,biocore/American-Gut,EmbrietteH/American-Gut,biocore/American-Gut,JWDebelius/American-Gut" 8a394794c5c663ef11ef9e44df5448d00c859357,interface/plugin/farmanager/01autoguid/__init__.py,interface/plugin/farmanager/01autoguid/__init__.py,,""""""" Need to change all GUIDs for your every new plugin, is daunting, so let's generate them from strings that are unique for plugins. Low-level Far Manager API is here: * https://api.farmanager.com/en/exported_functions/getglobalinfow.html """""" # --- utility functions --- import hashlib def getuuid(data): """"""Generate UUID from `data` string"""""" if type(data) != bytes: data = data.encode('utf-8') h = hashlib.sha256(data).hexdigest()[:32].upper() for i, pos in enumerate([8, 12, 16, 20]): h = h[:i+pos] + '-' + h[i+pos:] return h # --- plugin interface def GetGlobalInfoW(info): """""" Called by Far Manager, plugin needs to fill the info """""" info[""Title""] = ""____"" # should be set and non-empty info[""Author""] = ""_"" # should be set and non-empty info[""Description""] = ""Simple Python plugin"" # should be set info[""Guid""] = getuuid(info[""Title""]) def GetPluginInfoW(info): info[""MenuString""] = ""01autoguid"" info[""Guid""] = getuuid(info[""MenuString""]) def OpenW(info): print(""[open] "" + __file__) ",Add 01autoguid/ plugin with own GUIDs autogenerated,"Add 01autoguid/ plugin with own GUIDs autogenerated ",Python,unlicense,"techtonik/discovery,techtonik/discovery,techtonik/discovery" f54fd0bf65d731b4f25cfc2ddffb8d6f472e0d7c,examples/eiger_use_case.py,examples/eiger_use_case.py,"'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files),) + sh, dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File(""eiger_vds.h5"", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) ","'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' import h5py import numpy as np files = ['1.h5', '2.h5', '3.h5', '4.h5', '5.h5'] entry_key = 'data' # where the data is inside of the source files. sh = h5py.File(files[0], 'r')[entry_key].shape # get the first ones shape. layout = h5py.VirtualLayout(shape=(len(files) * sh[0], ) + sh[1:], dtype=np.float) M_start = 0 for i, filename in enumerate(files): M_end = M_start + sh[0] vsource = h5py.VirtualSource(filename, entry_key, shape=sh) layout[M_start:M_end:1, :, :] = vsource M_start = M_end with h5py.File(""eiger_vds.h5"", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) ",Fix layout for Eiger example,"Fix layout for Eiger example ",Python,bsd-3-clause,"h5py/h5py,h5py/h5py,h5py/h5py" 33154ad8decc2848ce30444ec51615397a4d8d37,src/clusto/test/testbase.py,src/clusto/test/testbase.py,"import sys import os sys.path.insert(0, os.curdir) import unittest import clusto import ConfigParser DB='sqlite:///:memory:' ECHO=False class ClustoTestResult(unittest.TestResult): def addError(self, test, err): """"""Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """""" print >>sys.stderr, ""ERROR HERE!"" clusto.rollback_transaction() self.errors.append((test, self._exc_info_to_string(err, test))) class ClustoTestBase(unittest.TestCase): def data(self): pass def setUp(self): conf = ConfigParser.ConfigParser() conf.add_section('clusto') conf.set('clusto', 'dsn', DB) clusto.connect(conf,echo=ECHO) clusto.clear() clusto.SESSION.close() clusto.init_clusto() self.data() def tearDown(self): if clusto.SESSION.is_active: raise Exception(""SESSION IS STILL ACTIVE in %s"" % str(self.__class__)) clusto.clear() clusto.disconnect() clusto.METADATA.drop_all(clusto.SESSION.bind) def defaultTestResult(self): if not hasattr(self._testresult): self._testresult = ClustoTestResult() return self._testresult ","import sys import os sys.path.insert(0, os.curdir) import unittest import clusto import ConfigParser DB='sqlite:///:memory:' ECHO=False class ClustoTestResult(unittest.TestResult): def addError(self, test, err): """"""Called when an error has occurred. 'err' is a tuple of values as returned by sys.exc_info(). """""" print >>sys.stderr, ""ERROR HERE!"" clusto.rollback_transaction() self.errors.append((test, self._exc_info_to_string(err, test))) class ClustoTestBase(unittest.TestCase): def data(self): pass def setUp(self): conf = ConfigParser.ConfigParser() conf.add_section('clusto') conf.set('clusto', 'dsn', DB) conf.set('clusto', 'versioning', '1') clusto.connect(conf,echo=ECHO) clusto.clear() clusto.SESSION.close() clusto.init_clusto() self.data() def tearDown(self): if clusto.SESSION.is_active: raise Exception(""SESSION IS STILL ACTIVE in %s"" % str(self.__class__)) clusto.clear() clusto.disconnect() clusto.METADATA.drop_all(clusto.SESSION.bind) def defaultTestResult(self): if not hasattr(self._testresult): self._testresult = ClustoTestResult() return self._testresult ",Enable versioning during unit tests,"Enable versioning during unit tests ",Python,bsd-3-clause,"clusto/clusto,thekad/clusto,sloppyfocus/clusto,sloppyfocus/clusto,motivator/clusto,JTCunning/clusto,motivator/clusto,clusto/clusto,thekad/clusto,JTCunning/clusto" e4fcebfe4e87b57ae8505437f54c69f3afd59c04,python/tests.py,python/tests.py,"#!/usr/bin/env python """""" Created on Thu 6 March 2014 Contains testing routines for `SolarCoreModel.py`. @author Kristoffer Braekken """""" import SolarCoreModel from numpy import log10 def opacity_test(tol=1.e-10): """""" Function for testing that the opacity is fetched correctly. """""" # Test values T = 10**(5.) # Feth 5.00 row rho = 1.e-6 # Fetch -5.0 column ans = log10(SolarCoreModel.kappa(T, rho)) if abs(ans - (-0.068)) < tol: print 'Sucess.' else: print 'Fail.\n10**kappa =', ans, 'and not -0.068.' if __name__ == '__main__': opacity_test() ","#!/usr/bin/env python """""" Created on Thu 6 March 2014 Contains testing routines for `SolarCoreModel.py`. @author Kristoffer Braekken """""" import SolarCoreModel from numpy import log10 def opacity_test(tol=1.e-10): """""" Function for testing that the opacity is fetched correctly. """""" # Test values T = 10**(5.) # Feth 5.00 row rho = 1.e-6 # Fetch -5.0 column rho /= 1.e3; rho *= 1./1e6 # Convert to SI units [kg m^-3] ans = log10(SolarCoreModel.kappa(T, rho)) if abs(ans - (-0.068)) < tol: print 'Sucess.' else: print 'Fail.\n10**kappa =', ans, 'and not -0.068.' if __name__ == '__main__': opacity_test() ",Fix test to take care of units.,"TODO: Fix test to take care of units. ",Python,mit,"PaulMag/AST3310-Prj01,PaulMag/AST3310-Prj01" ac0267d318939e4e7a62342b5dc6a09c3264ea74,flocker/node/_deploy.py,flocker/node/_deploy.py,"# Copyright Hybrid Logic Ltd. See LICENSE file for details. # -*- test-case-name: flocker.node.test.test_deploy -*- """""" Deploy applications on nodes. """""" class Deployment(object): """""" """""" _gear_client = None def start_container(self, application): """""" Launch the supplied application as a `gear` unit. """""" def stop_container(self, application): """""" Stop and disable the application. """""" ","# Copyright Hybrid Logic Ltd. See LICENSE file for details. # -*- test-case-name: flocker.node.test.test_deploy -*- """""" Deploy applications on nodes. """""" from .gear import GearClient class Deployment(object): """""" """""" def __init__(self, gear_client=None): """""" :param IGearClient gear_client: The gear client API to use in deployment operations. Default ``GearClient``. """""" if gear_client is None: gear_client = GearClient(hostname=b'127.0.0.1') self._gear_client = gear_client def start_container(self, application): """""" Launch the supplied application as a `gear` unit. """""" def stop_container(self, application): """""" Stop and disable the application. """""" ",Allow a fake gear client to be supplied,"Allow a fake gear client to be supplied ",Python,apache-2.0,"wallnerryan/flocker-profiles,hackday-profilers/flocker,lukemarsden/flocker,Azulinho/flocker,w4ngyi/flocker,hackday-profilers/flocker,LaynePeng/flocker,lukemarsden/flocker,AndyHuu/flocker,beni55/flocker,mbrukman/flocker,1d4Nf6/flocker,w4ngyi/flocker,beni55/flocker,adamtheturtle/flocker,hackday-profilers/flocker,achanda/flocker,moypray/flocker,achanda/flocker,runcom/flocker,LaynePeng/flocker,achanda/flocker,agonzalezro/flocker,1d4Nf6/flocker,LaynePeng/flocker,jml/flocker,beni55/flocker,jml/flocker,Azulinho/flocker,runcom/flocker,adamtheturtle/flocker,moypray/flocker,lukemarsden/flocker,agonzalezro/flocker,wallnerryan/flocker-profiles,adamtheturtle/flocker,agonzalezro/flocker,AndyHuu/flocker,w4ngyi/flocker,moypray/flocker,Azulinho/flocker,1d4Nf6/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,mbrukman/flocker,jml/flocker,runcom/flocker,AndyHuu/flocker" 1e76a9c7ee030875929a65d9f30194166dcd62ef,docs/reencode.py,docs/reencode.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. """"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""""" import argparse import pathlib def _main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False) parser.add_argument('input', type=pathlib.Path) parser.add_argument('output', type=pathlib.Path) opts = parser.parse_args() text = opts.input.read_text(encoding='utf-8') with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file: file.write(text) if __name__ == '__main__': _main() ","# 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. """"""Helper binary to reencode a text file from UTF-8 to ISO-8859-1."""""" import argparse import pathlib def _main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False) parser.add_argument('input', type=pathlib.Path) parser.add_argument('output', type=pathlib.Path) opts = parser.parse_args() text = opts.input.read_text(encoding='utf-8') # Force Unix-style line endings for consistent results. See # https://github.com/bazelbuild/stardoc/issues/110. with opts.output.open(mode='xt', encoding='latin-1', newline='\n') as file: file.write(text) if __name__ == '__main__': _main() ",Add a comment about line endings in Stardoc files.,"Add a comment about line endings in Stardoc files. ",Python,apache-2.0,"phst/rules_elisp,phst/rules_elisp,phst/rules_elisp,phst/rules_elisp,phst/rules_elisp" 324beaae091b2bc4699d4840ccd313aa0645b07e,nets.py,nets.py,"class FeedForwardNet: pass ","from layers import InputLayer, Layer, OutputLayer import math import random class FeedForwardNet(object): def __init__(self, inlayersize, layersize, outlayersize): self._inlayer = InputLayer(inlayersize) self._middlelayer = Layer(layersize) self._outlayer = OutputLayer(outlayersize) self._inlayer.connect_layer(self._middlelayer) self._middlelayer.connect_layer(self._outlayer) @property def neurons(self): return [self._inlayer.neurons, self._middlelayer.neurons, self._outlayer.neurons] def train(self, inputs, targets, verbose=False): ''' inputs: a sequence of floats that map to the input neurons targetlabels: a sequence of floats that are the desired output neuron values. ''' self._inlayer.inputs = inputs self._middlelayer.propagate() self._outlayer.propagate() self._outlayer.backpropagate1(targets) self._middlelayer.backpropagate1() self._outlayer.backpropagate2() self._middlelayer.backpropagate2() if verbose: print(""Training results"") print(""\tInput: {0}"".format(inputs)) print(""\tTarget output: {0}"".format(targets)) print(""\tActual output: {0}"".format(self._outlayer.outputs)) self.display_signals() print("""") raw_input() def predict(self, inputs): ''' inputs: a sequence of floats that map to the input neurons return: a sequence of floats mapped from the output neurons ''' self._inlayer.inputs = inputs self._middlelayer.propagate() self._outlayer.propagate() return self._outlayer.outputs def display_signals(self): col1 = self._inlayer.inputs col2 = [x.signal for x in self._middlelayer.neurons] col3 = self._outlayer.outputs numrows = max(len(col1), len(col2), len(col3)) roundto = 3 #round to print(""Signals"") print(""\tInput\tHidden\tOutput"") for row in range(numrows): line = [] for col in col1, col2, col3: if len(col)-1 < row: line.append("""") else: element = round(col[row], roundto) element = str(element) line.append(element) print('\t' + '\t'.join(line)) if __name__ == '__main__': f = FeedForwardNet(1, 2, 1) for i in range(50000): f.train((1, 1), (0,)) f.train((1, 0), (1,)) f.train((0, 1), (1,)) f.train((0, 0), (0,)) while True: x = input(""Input: "") y = f.predict(x) print(""Output: {0}"".format(y)) ",Add main code and feed forward net class,"Add main code and feed forward net class It can XOR, but sin function still fails ",Python,mit,tmerr/trevornet 1db05fb528295456e2127be5ba5225d697655676,metashare/accounts/urls.py,metashare/accounts/urls.py,"from django.conf.urls.defaults import patterns from metashare.settings import DJANGO_BASE urlpatterns = patterns('metashare.accounts.views', (r'create/$', 'create'), (r'confirm/(?P[0-9a-f]{32})/$', 'confirm'), (r'contact/$', 'contact'), (r'reset/(?:(?P[0-9a-f]{32})/)?$', 'reset'), (r'profile/$', 'edit_profile'), (r'editor_group_application/$', 'editor_group_application'), (r'organization_application/$', 'organization_application'), (r'add_default_editor_groups/$', 'add_default_editor_groups'), (r'remove_default_editor_groups/$', 'remove_default_editor_groups'), ) urlpatterns += patterns('django.contrib.auth.views', (r'^profile/change_password/$', 'password_change', {'post_change_redirect' : '/{0}accounts/profile/change_password/done/'.format(DJANGO_BASE), 'template_name': 'accounts/change_password.html'}), (r'^profile/change_password/done/$', 'password_change_done', {'template_name': 'accounts/change_password_done.html'}), ) ","from django.conf.urls.defaults import patterns from metashare.settings import DJANGO_BASE urlpatterns = patterns('metashare.accounts.views', (r'create/$', 'create'), (r'confirm/(?P[0-9a-f]{32})/$', 'confirm'), (r'contact/$', 'contact'), (r'reset/(?:(?P[0-9a-f]{32})/)?$', 'reset'), (r'profile/$', 'edit_profile'), (r'editor_group_application/$', 'editor_group_application'), (r'organization_application/$', 'organization_application'), (r'update_default_editor_groups/$', 'update_default_editor_groups'), ) urlpatterns += patterns('django.contrib.auth.views', (r'^profile/change_password/$', 'password_change', {'post_change_redirect' : '/{0}accounts/profile/change_password/done/'.format(DJANGO_BASE), 'template_name': 'accounts/change_password.html'}), (r'^profile/change_password/done/$', 'password_change_done', {'template_name': 'accounts/change_password_done.html'}), ) ",Manage default editor group on a single page,"Manage default editor group on a single page ",Python,bsd-3-clause,"zeehio/META-SHARE,MiltosD/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEFELRC,MiltosD/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEFELRC,MiltosD/CEF-ELRC,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,MiltosD/CEFELRC,zeehio/META-SHARE,JuliBakagianni/META-SHARE,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE,JuliBakagianni/CEF-ELRC,zeehio/META-SHARE,JuliBakagianni/META-SHARE,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,JuliBakagianni/META-SHARE,JuliBakagianni/META-SHARE,MiltosD/CEF-ELRC,MiltosD/CEF-ELRC,MiltosD/CEFELRC" 2b18bc0e0f3b9e0ca14935e2648fb9e6d637c8d0,backend/rest.py,backend/rest.py,"#!/usr/bin/env python from mcapi.mcapp import app from mcapi import tservices, public, utils, private, access, process, machine, template, tservices from mcapi.user import account, datadirs, datafiles, reviews, ud, usergroups, projects, conditions from mcapi.stater import stater import sys if __name__ == '__main__': if len(sys.argv) >= 2: debug = True else: debug = False if len(sys.argv) == 3: app.run(debug=debug, host='0.0.0.0') else: app.run(debug=debug) ","#!/usr/bin/env python from mcapi.mcapp import app from mcapi import tservices, public, utils, private, access, process, machine, template, tservices from mcapi.user import account, datadirs, datafiles, reviews, ud, usergroups, projects, conditions from mcapi.stater import stater import sys from os import environ _HOST = environ.get('MC_SERVICE_HOST') or 'localhost' _PORT = environ.get('MC_SERVICE_PORT') or '5000' if __name__ == '__main__': if len(sys.argv) >= 2: debug = True else: debug = False app.run(debug=debug, host=_HOST, port=int(_PORT)) ",Allow host and port that the service listens on to be set from environment variables.,"Allow host and port that the service listens on to be set from environment variables. ",Python,mit,"materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org" 2b99781e67e1e2e0bb3863c08e81b3cf57a5e296,tests/test_bouncer.py,tests/test_bouncer.py,,"from rest_framework import status from rest_framework.test import APITestCase from django.contrib.auth import get_user_model from api_bouncer.models import Api User = get_user_model() class BouncerTests(APITestCase): def setUp(self): self.superuser = User.objects.create_superuser( 'john', 'john@localhost.local', 'john123john' ) self.example_api = Api.objects.create( name='httpbin', hosts=['httpbin.org'], upstream_url='https://httpbin.org' ) def test_bounce_api_request(self): """""" Ensure we can bouncer a request to an api and get the same response. """""" url = '/status/418' # teapot self.client.credentials(HTTP_HOST='httpbin.org') response = self.client.get(url) self.assertEqual(response.status_code, 418) self.assertIn('teapot', response.content.decode('utf-8')) def test_bounce_api_request_unknown_host(self): """""" Ensure we send a response when the hosts making the request is not trying to call an api. """""" url = '/test' self.client.credentials(HTTP_HOST='the-unknown.com') response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.json(), {}) ",Add request bouncer test cases,"Add request bouncer test cases ",Python,apache-2.0,menecio/django-api-bouncer ec28eadeab215533cec1b14b627e2793aa7f4f31,tt_dailyemailblast/send_backends/sync.py,tt_dailyemailblast/send_backends/sync.py,"from . import email def sync_daily_email_blasts(blast): for l in blast.recipients_lists.all(): l.send(blast) def sync_recipients_list(recipients_list, blast): for r in recipients_list.recipientss.all(): r.send(recipients_list, blast) def sync_recipient(recipient, recipients_list, blast): email.send_email(blast.render(recipient, recipients_list)) ","from .. import email def sync_daily_email_blasts(blast): for l in blast.recipients_lists.all(): l.send(blast) def sync_recipients_list(recipients_list, blast): for r in recipients_list.recipientss.all(): r.send(recipients_list, blast) def sync_recipient(recipient, recipients_list, blast): email.send_email(blast.render(recipient, recipients_list)) ",Fix email module could not be imported,"Fix email module could not be imported This helpful message alerted me to this problem: ImproperlyConfigured: ",Python,apache-2.0,"texastribune/tt_dailyemailblast,texastribune/tt_dailyemailblast" 2b5a3f0209d4a5fc5e821ca4f749931d8f6a18be,app/wmmetrics.py,app/wmmetrics.py,"from flask import Flask, render_template app = Flask(__name__) @app.route(""/"") def index(): return render_template('index.html') @app.route(""/fdc"") def fdc_report_page(): return render_template('fdc-report.html') if __name__ == ""__main__"": app.run(debug=True) ","import os import sys from flask import Flask, render_template, request current_dir = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(current_dir, '..')) from wm_metrics import fdc from wm_metrics import wmfr_photography from wm_metrics import commons_cat_metrics app = Flask(__name__) @app.route(""/"") def index(): return render_template('index.html') @app.route(""/fdc"") def fdc_report_page(): return render_template('fdc-report.html') if __name__ == ""__main__"": app.run(debug=True) ",Add imports for Wm_metrics module,"Webapp: Add imports for Wm_metrics module We have to manually add wm_metrics to the Python Path ",Python,mit,"danmichaelo/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics" 17d1a9f41f91c03b640a112313c9afb068a4ead4,auth_mac/tools.py,auth_mac/tools.py,," import datetime import hmac, hashlib, base64 def _build_authheader(method, data): datastr = "", "".join(['{0}=""{1}""'.format(x, y) for x, y in data.iteritems()]) return ""{0} {1}"".format(method, datastr) class Signature(object): ""A class to ease the creation of MAC signatures"" MAC = None def __init__(self, credentials, host=""example.com"", port=80): self.MAC = credentials self.host = host self.port = port self.ext = """" def get_timestamp(self): timestamp = datetime.datetime.utcnow() - datetime.datetime(1970,1,1) return timestamp.days * 24 * 3600 + timestamp.seconds def get_nonce(self): return User.objects.make_random_password(8) def sign_request(self, uri, method=""GET"", timestamp=None, nonce=None): """"""Signs a request to a specified URI and returns the signature"""""" if not timestamp: self.timestamp = self.get_timestamp() timestamp = self.timestamp if not nonce: self.nonce = self.get_nonce() nonce = self.nonce self.nonce = nonce self.timestamp = timestamp method = method.upper() if not method in (""GET"", ""POST""): raise RuntimeError(""HTTP Method {0} not supported!"".format(method)) data = [timestamp, nonce, method, uri, self.host, self.port, self.ext] data = [str(x) for x in data] self.base_string = ""\n"".join(data) + ""\n"" # print repr(basestr) # print ""Signing with key '{0}'"".format(self.MAC.key) hm = hmac.new(self.MAC.key, self.base_string, hashlib.sha1) self.signature = base64.b64encode(hm.digest()) # print self.signature return self.signature def get_header(self): # {""id"": ""h480djs93hd8"",""ts"": ""1336363200"",""nonce"":""dj83hs9s"",""mac"":""bhCQXTVyfj5cmA9uKkPFx1zeOXM=""} data = {""id"": self.MAC.identifier, ""ts"": self.timestamp, ""nonce"": self.nonce, ""mac"": self.signature } return _build_authheader(""MAC"", data) ",Move the signature class into it's own tool .py,"Move the signature class into it's own tool .py ",Python,mit,ndevenish/auth_mac fda08d81e3b6a4aae5610973053890bf8b283bf0,buffer/tests/test_profile.py,buffer/tests/test_profile.py,"import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') ","import json from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profile_schedules_getter(): ''' Test schedules gettering from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) eq_(profile.schedules, '123') mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1) def test_profile_schedules_setter(): ''' Test schedules setter from buffer api ''' mocked_api = MagicMock() mocked_api.get.return_value = '123' profile = Profile(mocked_api, mocked_response) profile.schedules = { 'times': ['mo'] } mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') def test_profile_updates(): ''' Test updates relationship with a profile ''' mocked_api = MagicMock() with patch('buffer.models.profile.Updates') as mocked_updates: profile = Profile(api=mocked_api, raw_response={'id': 1}) updates = profile.updates mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1) ",Test profile's relationship with updates,"Test profile's relationship with updates ",Python,mit,"vtemian/buffpy,bufferapp/buffer-python" 94bbfda63c7734c43e5771a92a69e6ce15d29c24,src/hades/common/exc.py,src/hades/common/exc.py,,"import functools import logging import os import sys import typing as t from contextlib import contextmanager from logging import Logger RESTART_PREVENTING_EXCEPTIONS = frozenset( (os.EX_CONFIG, os.EX_USAGE, os.EX_UNAVAILABLE) ) class HadesSetupError(Exception): preferred_exit_code = os.EX_UNAVAILABLE def __init__(self, *args, logger: t.Optional[Logger] = None): super().__init__(*args) self.logger = logger def __init_subclass__(cls, **kwargs: dict[str, t.Any]) -> None: super().__init_subclass__(**kwargs) if ""preferred_exit_code"" not in cls.__dict__: return if cls.__dict__[""preferred_exit_code""] not in RESTART_PREVENTING_EXCEPTIONS: raise ValueError( ""Subclasses of HadesSetupException can only provide exit codes"" "" known to prevent a restart (see `RestartPreventExitStatus=` in systemd.service(5))"" ) def report_error(self, fallback_logger: Logger) -> None: """"""Emit helpful log messages about this error."""""" logger = self.logger or fallback_logger logger.critical(""Error in setup: %s"", str(self), exc_info=self) class HadesUsageError(HadesSetupError): preferred_exit_code = os.EX_USAGE def __init__(self, *a, **kw): super().__init__(*a, **kw) @contextmanager def handle_setup_errors(logger: logging.Logger) -> t.Generator[None, None, None]: """"""If a :class:`HadesSetupError` occurs, report it and call :func:`sys.exit` accordingly."""""" try: yield except HadesSetupError as e: e.report_error(fallback_logger=logger) sys.exit(e.preferred_exit_code) F = t.TypeVar(""F"", bound=t.Callable[..., t.Any]) def handles_setup_errors(logger: logging.Logger) -> t.Callable[[F], F]: def decorator(f: F) -> F: @functools.wraps(f) def wrapped(*a, **kw): with handle_setup_errors(logger): f(*a, **kw) return t.cast(F, wrapped) return decorator ",Introduce HadesSetupError and HadesUsageError for restart prevention,"Introduce HadesSetupError and HadesUsageError for restart prevention ",Python,mit,"agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades" da5db320bd96ff881be23c91f8f5d69505d67946,src/project_name/urls.py,src/project_name/urls.py,"from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import TemplateView urlpatterns = [ url(r'^admin_tools/', include('admin_tools.urls')), url(r'^admin/', include(admin.site.urls)), # Simply show the master template. url(r'^$', TemplateView.as_view(template_name='demo.html')), ] # NOTE: The staticfiles_urlpatterns also discovers static files (ie. no need to run collectstatic). Both the static # folder and the media folder are only served via Django if DEBUG = True. urlpatterns += staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ","from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.base import TemplateView urlpatterns = [ url(r'^admin_tools/', include('admin_tools.urls')), url(r'^admin/', include(admin.site.urls)), # Simply show the master template. url(r'^$', TemplateView.as_view(template_name='demo.html')), ] # NOTE: The staticfiles_urlpatterns also discovers static files (ie. no need to run collectstatic). Both the static # folder and the media folder are only served via Django if DEBUG = True. urlpatterns += staticfiles_urlpatterns() + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] ",Add missing configuration for DjDT,"Add missing configuration for DjDT ",Python,mit,"Clarity-89/clarityv2,Clarity-89/clarityv2,Clarity-89/clarityv2,Clarity-89/clarityv2" 9c42a7925d4e872a6245301ef68b2b9aa1f0aa7b,tests/__init__.py,tests/__init__.py,"#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly # Copyright 2012 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ","#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly # Copyright 2012 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the ""License""); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an ""AS IS"" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from sys import version_info from os import name as OS_NAME __all__= ['unittest', 'skipIfNtMove'] if version_info < (2, 7): import unittest2 as unittest else: import unittest skipIfNtMove = unittest.skipIf(OS_NAME == 'nt', ""windows can not detect moves"") ",Declare unittest lib used within python version,"Declare unittest lib used within python version ",Python,apache-2.0,"glorizen/watchdog,ymero/watchdog,javrasya/watchdog,mconstantin/watchdog,teleyinex/watchdog,gorakhargosh/watchdog,javrasya/watchdog,ymero/watchdog,javrasya/watchdog,mconstantin/watchdog,teleyinex/watchdog,teleyinex/watchdog,glorizen/watchdog,glorizen/watchdog,gorakhargosh/watchdog,mconstantin/watchdog,ymero/watchdog" b36d2b6760b9905638ad2202d2b7e0461eb9d7fc,scanner/ToolbarProxy.py,scanner/ToolbarProxy.py,"from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty class ToolbarProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._state = 0 self._use_wizard = False stateChanged = pyqtSignal() wizardStateChanged = pyqtSignal() @pyqtProperty(bool,notify = wizardStateChanged) def wizardActive(self): return self._use_wizard @pyqtSlot(bool) def setWizardState(self, state): self._use_wizard = state self.wizardStateChanged.emit() @pyqtProperty(int,notify = stateChanged) def state(self): return self._state @pyqtSlot(int) def setState(self, state): self._state = state self.stateChanged.emit()","from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot,pyqtSignal, pyqtProperty class ToolbarProxy(QObject): def __init__(self, parent = None): super().__init__(parent) self._state = 1 self._use_wizard = False stateChanged = pyqtSignal() wizardStateChanged = pyqtSignal() @pyqtProperty(bool,notify = wizardStateChanged) def wizardActive(self): return self._use_wizard @pyqtSlot(bool) def setWizardState(self, state): self._use_wizard = state self.wizardStateChanged.emit() @pyqtProperty(int,notify = stateChanged) def state(self): return self._state @pyqtSlot(int) def setState(self, state): self._state = state self.stateChanged.emit()",Set standard state of wizard to one (so first step automatically starts),"Set standard state of wizard to one (so first step automatically starts) ",Python,agpl-3.0,"onitake/Uranium,onitake/Uranium" 6ac16fc33a6f887535a143cc7155c7ff910ca835,control/utils.py,control/utils.py,,"import csv from datetime import datetime import itertools from django.http import StreamingHttpResponse from django_object_actions import DjangoObjectActions class Echo(object): '''An object that implements just the write method of the file-like interface.''' def write(self, value): '''Write the value by returning it, instead of storing it in a buffer.''' return value class CsvExportAdminMixin(DjangoObjectActions): '''A mix-in class for adding a CSV export button to a Django Admin page.''' csv_header = None def clean_csv_line(self, obj): '''Subclass to override. Gets a model object, and returns a list representing a line in the CSV file.''' def get_csv_header(self): '''Subclass can override. Returns a list representing the header of the CSV. Can also set the `csv_header` class variable.''' return self.csv_header def export_csv(self, request, queryset): rows = itertools.chain( (self.get_csv_header(), ), (self.clean_csv_line(obj) for obj in queryset) ) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse( (writer.writerow(row) for row in rows), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=%s-%s.csv' % ( self.model.__name__, datetime.now().strftime('%Y-%m-%d')) return response export_csv.label = ""Download"" export_csv.short_description = ""Download an export of the data as CSV"" changelist_actions = ('export_csv', ) ",Add django admin mixin for exporting csvs,"Add django admin mixin for exporting csvs ",Python,bsd-3-clause,"praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control" 71de95f9a2ea9e48d30d04897e79b025b8520775,bfg9000/shell/__init__.py,bfg9000/shell/__init__.py,"import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """"""A special subclass of list used to mark that this command line uses special shell characters."""""" pass def execute(args, shell=False, env=None, quiet=False): stderr = None if quiet: stderr = open(os.devnull, 'wb') try: result = subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) finally: if quiet: stderr.close() return result ","import os import subprocess from ..platform_name import platform_name if platform_name() == 'windows': from .windows import * else: from .posix import * class shell_list(list): """"""A special subclass of list used to mark that this command line uses special shell characters."""""" pass def execute(args, shell=False, env=None, quiet=False): stderr = open(os.devnull, 'wb') if quiet else None try: return subprocess.check_output( args, universal_newlines=True, shell=shell, env=env, stderr=stderr ) finally: if stderr: stderr.close() ",Clean up the shell execute() function,"Clean up the shell execute() function ",Python,bsd-3-clause,"jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000" e59a870a1e039e12da2097401f925146ecc1a5fb,tests/modules/test_memory.py,tests/modules/test_memory.py,,"# pylint: disable=C0103,C0111 import mock import unittest import tests.mocks as mocks from bumblebee.input import LEFT_MOUSE from bumblebee.modules.memory import Module class VirtualMemory(object): def __init__(self, percent): self.percent = percent class TestMemoryModule(unittest.TestCase): def setUp(self): mocks.setup_test(self, Module) self._psutil = mock.patch(""bumblebee.modules.memory.psutil"") self.psutil = self._psutil.start() def tearDown(self): self._psutil.stop() mocks.teardown_test(self) def test_leftclick(self): mocks.mouseEvent(stdin=self.stdin, button=LEFT_MOUSE, inp=self.input, module=self.module) self.popen.assert_call(""gnome-system-monitor"") def test_warning(self): self.config.set(""memory.critical"", ""80"") self.config.set(""memory.warning"", ""70"") self.psutil.virtual_memory.return_value = VirtualMemory(75) self.module.update_all() self.assertTrue(""warning"" in self.module.state(self.anyWidget)) def test_critical(self): self.config.set(""memory.critical"", ""80"") self.config.set(""memory.warning"", ""70"") self.psutil.virtual_memory.return_value = VirtualMemory(81) self.module.update_all() self.assertTrue(""critical"" in self.module.state(self.anyWidget)) def test_usage(self): rv = VirtualMemory(50) rv.total = 1000 rv.available = 500 self.psutil.virtual_memory.return_value = rv self.module.update_all() self.assertEquals(""500.00B/1000.00B (50.00%)"", self.module.memory_usage(self.anyWidget)) self.assertEquals(None, self.module.state(self.anyWidget)) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 ",Add unit tests for memory module,"[tests] Add unit tests for memory module ",Python,mit,"tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status" c062ae638a4c864e978a4adfcd7d8d830b99abc2,opentreemap/treemap/lib/dates.py,opentreemap/treemap/lib/dates.py,"from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """""" If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """""" if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2 ","from datetime import datetime from django.utils import timezone import calendar import pytz DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' DATE_FORMAT = '%Y-%m-%d' def parse_date_string_with_or_without_time(date_string): try: return datetime.strptime(date_string.strip(), '%Y-%m-%d %H:%M:%S') except ValueError: # If the time is not included, try again with date only return datetime.strptime(date_string.strip(), '%Y-%m-%d') def unix_timestamp(d=None): if d is None: d = timezone.now() return calendar.timegm(d.utctimetuple()) else: return calendar.timegm(d.timetuple()) def datesafe_eq(obj1, obj2): """""" If two objects are dates, but don't both have the same timezone awareness status, compare them in a timezone-safe way. Otherwise, compare them with regular equality. """""" if isinstance(obj1, datetime) and not timezone.is_aware(obj1): obj1 = timezone.make_aware(obj1, pytz.UTC) if isinstance(obj2, datetime) and not timezone.is_aware(obj2): obj2 = timezone.make_aware(obj2, pytz.UTC) return obj1 == obj2 def make_aware(value): if value is None or timezone.is_aware(value): return value else: return timezone.make_aware(value, timezone.utc) ","Add function for nullsafe, tzsafe comparison","Add function for nullsafe, tzsafe comparison ",Python,agpl-3.0,"clever-crow-consulting/otm-core,recklessromeo/otm-core,maurizi/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/otm-core,RickMohr/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,RickMohr/otm-core,maurizi/otm-core" 6d04f0f924df11968b85aa2c885bde30cf6af597,stack/vpc.py,stack/vpc.py,"from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( ""Vpc"", template=template, CidrBlock=""10.0.0.0/16"", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( ""InternetGateway"", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( ""GatewayAttachement"", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) ","from troposphere import ( Ref, ) from troposphere.ec2 import ( InternetGateway, Route, RouteTable, VPC, VPCGatewayAttachment, ) from .template import template vpc = VPC( ""Vpc"", template=template, CidrBlock=""10.0.0.0/16"", ) # Allow outgoing to outside VPC internet_gateway = InternetGateway( ""InternetGateway"", template=template, ) # Attach Gateway to VPC VPCGatewayAttachment( ""GatewayAttachement"", template=template, VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) # Public route table public_route_table = RouteTable( ""PublicRouteTable"", template=template, VpcId=Ref(vpc), ) public_route = Route( ""PublicRoute"", template=template, GatewayId=Ref(internet_gateway), DestinationCidrBlock=""0.0.0.0/0"", RouteTableId=Ref(public_route_table), ) ",Add a public route table,"Add a public route table ",Python,mit,"caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics" 8141d6cafb4a1c8986ec7065f27d536d98cc9916,Modules/Biophotonics/python/iMC/script_plot_one_spectrum.py,Modules/Biophotonics/python/iMC/script_plot_one_spectrum.py,,"''' Created on Oct 12, 2015 @author: wirkert ''' import pickle import logging import numpy as np import matplotlib.pyplot as plt import luigi import tasks_regression as rt from msi.plot import plot from msi.msi import Msi import msi.normalize as norm import scriptpaths as sp sp.ROOT_FOLDER = ""/media/wirkert/data/Data/2015_xxxx_plot_one_spectrum"" # the wavelengths recorded by our camera RECORDED_WAVELENGTHS = \ np.array([580, 470, 660, 560, 480, 511, 600, 700]) * 10 ** -9 PARAMS = np.array([0.05, # bvf 0.0, # SaO2 0.0, # billirubin 500., # a_mie 0.0, # a_ray 1.091, # b (for scattering 500. * 10 ** -6]) # d_muc class PlotOneSpectrum(luigi.Task): batch_prefix = luigi.Parameter() def requires(self): return rt.TrainForestForwardModel(self.batch_prefix) def run(self): f = file(self.input().path, ""r"") rf = pickle.load(f) f.close() refl = rf.predict(PARAMS) msi = Msi(refl) msi.set_wavelengths(RECORDED_WAVELENGTHS) norm.standard_normalizer.normalize(msi) plot(msi) plt.gca().set_xlabel(""wavelength"") plt.gca().set_ylabel(""normalized reflectance"") plt.grid() plt.ylim([0.0, 0.4]) plt.title(""bvf: "" + str(PARAMS[0]) + ""; saO2: "" + str(PARAMS[1]) + ""; bili: "" + str(PARAMS[2]) + ""; a_mie: "" + str(PARAMS[3]) + ""; a_ray: "" + str(PARAMS[4]) + ""; d_muc: "" + str(PARAMS[6])) plt.show() if __name__ == '__main__': logging.basicConfig(level=logging.INFO) luigi.interface.setup_interface_logging() sch = luigi.scheduler.CentralPlannerScheduler() w = luigi.worker.Worker(scheduler=sch) main_task = PlotOneSpectrum(batch_prefix= ""jacques_no_billi_generic_scattering_"") w.add(main_task) w.run() ",Add little script calculate sample spectra.,"Add little script calculate sample spectra. ",Python,bsd-3-clause,"RabadanLab/MITKats,MITK/MITK,MITK/MITK,RabadanLab/MITKats,MITK/MITK,MITK/MITK,fmilano/mitk,fmilano/mitk,fmilano/mitk,iwegner/MITK,RabadanLab/MITKats,iwegner/MITK,RabadanLab/MITKats,iwegner/MITK,RabadanLab/MITKats,MITK/MITK,fmilano/mitk,iwegner/MITK,fmilano/mitk,iwegner/MITK,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,MITK/MITK,iwegner/MITK" cb149a64cf969edef79528f052f96bc4a847a11c,bin/run_benchmark.py,bin/run_benchmark.py,,"import datetime import itertools import os import subprocess # Modify parameters here out_directory = datetime.datetime.now().strftime('benchmark_%Y-%m-%d_%H-%M-%S') dimension = 3 size = 50 ppc = 1 temperature = 0.0 iterations = 1 representations = [""SoA"", ""AoS""] storages = [""unordered"", ""ordered""] # add other combinations here combination_keys = [""-r"", ""-e""] combination_values = list(itertools.product(representations, storages)) # End of parameters # Enumerate all combinations of parameters and run if not os.path.exists(out_directory): os.makedirs(out_directory) args_base = (""benchmark"", ""-d"", str(dimension), ""-g"", str(size), ""-p"", str(ppc), ""-t"", str(temperature), ""-i"", str(iterations)) for i in range(0, len(combination_values)): file_name = """" args_combination = () for j in range(0, len(combination_values[i])): args_combination += (combination_keys[j], combination_values[i][j]) file_name += combination_values[i][j] + ""_"" args = args_base + args_combination popen = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines=True) popen.wait() file_name = file_name[:-1] + "".txt"" f = open(os.path.join(out_directory, file_name), ""w"") f.write(str(popen.stdout.read())) ",Add a script to enumerate configurations for benchmarking.,"Add a script to enumerate configurations for benchmarking. ",Python,mit,"pictools/pica,pictools/pica,pictools/pica" 6487ca4227f75d11d9f3ee985056c3292d4df5e4,dmoj/tests/test_control.py,dmoj/tests/test_control.py,"import threading import unittest import requests from dmoj.control import JudgeControlRequestHandler try: from unittest import mock except ImportError: import mock try: from http.server import HTTPServer except ImportError: from BaseHTTPServer import HTTPServer class ControlServerTest(unittest.TestCase): @classmethod def setUpClass(cls): class FakeJudge(object): pass class Handler(JudgeControlRequestHandler): judge = FakeJudge() cls.judge = Handler.judge cls.server = HTTPServer(('127.0.0.1', 0), Handler) thread = threading.Thread(target=cls.server.serve_forever) thread.daemon = True thread.start() cls.connect = 'http://%s:%s/' % cls.server.server_address def setUp(self): self.update_mock = self.judge.update_problems = mock.Mock() def test_get_404(self): self.assertEqual(requests.get(self.connect).status_code, 404) self.assertEqual(requests.get(self.connect + 'update/problems').status_code, 404) self.update_mock.assert_not_called() def test_post_404(self): self.assertEqual(requests.post(self.connect).status_code, 404) self.update_mock.assert_not_called() def test_update_problem(self): requests.post(self.connect + 'update/problems') self.update_mock.assert_called_with() @classmethod def tearDownClass(cls): cls.server.shutdown() ","import mock import threading import unittest import requests from dmoj.control import JudgeControlRequestHandler try: from http.server import HTTPServer except ImportError: from BaseHTTPServer import HTTPServer class ControlServerTest(unittest.TestCase): @classmethod def setUpClass(cls): class FakeJudge(object): pass class Handler(JudgeControlRequestHandler): judge = FakeJudge() cls.judge = Handler.judge cls.server = HTTPServer(('127.0.0.1', 0), Handler) thread = threading.Thread(target=cls.server.serve_forever) thread.daemon = True thread.start() cls.connect = 'http://%s:%s/' % cls.server.server_address def setUp(self): self.update_mock = self.judge.update_problems = mock.Mock() def test_get_404(self): self.assertEqual(requests.get(self.connect).status_code, 404) self.assertEqual(requests.get(self.connect + 'update/problems').status_code, 404) self.update_mock.assert_not_called() def test_post_404(self): self.assertEqual(requests.post(self.connect).status_code, 404) self.update_mock.assert_not_called() def test_update_problem(self): requests.post(self.connect + 'update/problems') self.update_mock.assert_called_with() @classmethod def tearDownClass(cls): cls.server.shutdown() ",Make it work in PY3.5 *properly*,Make it work in PY3.5 *properly*,Python,agpl-3.0,"DMOJ/judge,DMOJ/judge,DMOJ/judge" 91736e7a7cc2510bb2c9a7a6c7930ea30d9be388,py/intersection-of-two-arrays.py,py/intersection-of-two-arrays.py,,"class Solution(object): def intersection(self, nums1, nums2): """""" :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """""" return list(set(nums1) & set(nums2)) ",Add py solution for 349. Intersection of Two Arrays,"Add py solution for 349. Intersection of Two Arrays 349. Intersection of Two Arrays: https://leetcode.com/problems/intersection-of-two-arrays/ ",Python,apache-2.0,"ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode" 6d928da6c3848c2fd9f34772033fb645767ae4c3,dbaas/workflow/steps/util/resize/check_database_status.py,dbaas/workflow/steps/util/resize/check_database_status.py,"# -*- coding: utf-8 -*- import logging from ...util.base import BaseStep LOG = logging.getLogger(__name__) class CheckDatabaseStatus(BaseStep): def __unicode__(self): return ""Checking database status..."" def do(self, workflow_dict): try: if not 'database' in workflow_dict: return False if not 'databaseinfra' in workflow_dict: workflow_dict['databaseinfra'] = workflow_dict[ 'database'].databaseinfra LOG.info(""Getting driver class"") driver = workflow_dict['databaseinfra'].get_driver() from time import sleep sleep(60) if driver.check_status(): LOG.info(""Database is ok..."") workflow_dict['database'].status = 1 workflow_dict['database'].save() return True return False except Exception, e: LOG.info(""Error: {}"".format(e)) pass def undo(self, workflow_dict): LOG.info(""Nothing to do here..."") return True ","# -*- coding: utf-8 -*- import logging from ...util.base import BaseStep LOG = logging.getLogger(__name__) class CheckDatabaseStatus(BaseStep): def __unicode__(self): return ""Checking database status..."" def do(self, workflow_dict): try: if 'database' not in workflow_dict: return False if 'databaseinfra' not in workflow_dict: workflow_dict['databaseinfra'] = workflow_dict[ 'database'].databaseinfra LOG.info(""Getting driver class"") driver = workflow_dict['databaseinfra'].get_driver() from time import sleep sleep(60) if driver.check_status(): LOG.info(""Database is ok..."") workflow_dict['database'].status = 1 workflow_dict['database'].save() return True except Exception as e: LOG.info(""Error: {}"".format(e)) pass def undo(self, workflow_dict): LOG.info(""Nothing to do here..."") return True ",Change check database status to return even when it is false,"Change check database status to return even when it is false ",Python,bsd-3-clause,"globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service" 49b13a33d37daa513345f629f5466f9807e24b49,setup.py,setup.py,"from setuptools import setup def read(f): try: with open(f) as file: return file.read() except: return """" setup(name='shellvars-py', version='0.1.2', description='Read environment variables defined in a shell script into Python.', author_email='aneil.mallavar@gmail.com', license='Apache2', py_modules=['shellvars'], long_description = read('README.md'), url=""http://github.com/aneilbaboo/shellvars-py"", author=""Aneil Mallavarapu"", include_package_data = True, classifiers = [ 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) ","from setuptools import setup def read(f): try: with open(f) as file: return file.read() except: return """" setup(name='shellvars-py', version='0.1.2', description='Read environment variables defined in a shell script into Python.', author_email='aneil.mallavar@gmail.com', license='Apache2', py_modules=['shellvars'], long_description = read('README.md'), url=""http://github.com/aneilbaboo/shellvars-py"", author=""Aneil Mallavarapu"", include_package_data = True, classifiers = [ 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) ",Add POSIX as supported OS type,"Add POSIX as supported OS type ",Python,apache-2.0,aneilbaboo/shellvars-py b49f733d675d537779bed931d0a079888a83a735,mpfmonitor/_version.py,mpfmonitor/_version.py,"# mpf-monitor __version__ = '0.3.0-dev.1' __short_version__ = '0.3' __bcp_version__ = '1.1' __config_version__ = '4' __mpf_version_required__ = '0.33.0' version = ""MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})"".format( __version__, __config_version__, __bcp_version__, __mpf_version_required__) ","# mpf-monitor __version__ = '0.2.0-dev.3' __short_version__ = '0.2' __bcp_version__ = '1.1' __config_version__ = '4' __mpf_version_required__ = '0.33.0.dev15' version = ""MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})"".format( __version__, __config_version__, __bcp_version__, __mpf_version_required__) ","Revert ""Bump dev version to 0.3.0-dev.1""","Revert ""Bump dev version to 0.3.0-dev.1"" This reverts commit facc1caaca87e680321be0654882d6c5570bc2ad. ",Python,mit,missionpinball/mpf-monitor e895795c6461da12f4824994168893ff131c0dd9,runtests.py,runtests.py,"import sys import django from django.conf import settings APP_NAME = 'impersonate' settings.configure( DEBUG=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, USE_TZ=True, ROOT_URLCONF='{0}.tests'.format(APP_NAME), MIDDLEWARE_CLASSES=( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'impersonate.middleware.ImpersonateMiddleware', ), INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', APP_NAME, ), # turn off for testing, override in logging-specific tests IMPERSONATE_SESSION_LOGGING=False, ) from django.test.utils import get_runner try: django.setup() except AttributeError: pass TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests([APP_NAME]) if failures: sys.exit(failures) ","import sys import django from django.conf import settings APP_NAME = 'impersonate' settings.configure( DEBUG=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, USE_TZ=True, ROOT_URLCONF='{0}.tests'.format(APP_NAME), MIDDLEWARE_CLASSES=( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'impersonate.middleware.ImpersonateMiddleware', ), INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', APP_NAME, ), # turn off for testing, override in logging-specific tests IMPERSONATE_DISABLE_LOGGING=True, ) from django.test.utils import get_runner try: django.setup() except AttributeError: pass TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests([APP_NAME]) if failures: sys.exit(failures) ",Disable impersonation logging during testing,"Disable impersonation logging during testing ",Python,bsd-3-clause,"Top20Talent/django-impersonate,Top20Talent/django-impersonate" 43bc1f2670b722d5fb1b0e34a0b098fd2f41bd77,icekit/plugins/image/admin.py,icekit/plugins/image/admin.py,"from django.contrib import admin from icekit.utils.admin.mixins import ThumbnailAdminMixin from . import models class ImageAdmin(ThumbnailAdminMixin, admin.ModelAdmin): list_display = ['description', 'title', 'thumbnail'] list_display_links = ['description', 'thumbnail'] filter_horizontal = ['categories', ] list_filter = ['categories', 'is_active', ] # ThumbnailAdminMixin attributes thumbnail_field = 'image' thumbnail_options = { 'size': (150, 150), } def title(self, image): return image.title def description(self, image): return str(image) admin.site.register(models.Image, ImageAdmin) ","from django.contrib import admin from icekit.utils.admin.mixins import ThumbnailAdminMixin from . import models class ImageAdmin(ThumbnailAdminMixin, admin.ModelAdmin): list_display = ['thumbnail', 'alt_text', 'title', ] list_display_links = ['alt_text', 'thumbnail'] filter_horizontal = ['categories', ] list_filter = ['categories', 'is_active', ] search_fields = ['title', 'alt_text', 'caption', 'admin_notes', ] # ThumbnailAdminMixin attributes thumbnail_field = 'image' thumbnail_options = { 'size': (150, 150), } admin.site.register(models.Image, ImageAdmin) ","Add search options for images, reorder field listing, use field names in list display rather than properties.","Add search options for images, reorder field listing, use field names in list display rather than properties. ",Python,mit,"ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit" 76f0f55670e80dff24001e9c9e99209e8a045c31,modules/engine.py,modules/engine.py,"import importlib import glob from modules.exception import * from os.path import basename, splitext PLUGINS_DIR = ""./plugins"" def get_plugins(plugins_dir = PLUGINS_DIR): plugins = {} plugin_files = glob.glob(""{}/*.py"".format(plugins_dir)) for plugin_file in plugin_files: if plugin_file.endswith(""__init__.py""): continue name, ext = splitext(basename(plugin_file)) module_name = ""plugins.{}"".format(name) module = importlib.import_module(module_name) plugin = module.__plugin__() plugins[module.__cname__] = plugin return plugins def dispatch(plugin, fields): if not plugin.VerifyCredentials(): try: plugin.Authorize() except (AuthorizarionError, Failed), e: return e.message req_fields_list = plugin.__fields__ req_fields = {} for field in fields: if field in req_fields_list: req_fields[field] = fields[field] try: return plugin.SendMsg(req_fields) except Exception, e: raise UnhandledException(e.message) if __name__ == '__main__': main() ","import importlib import glob from modules.exception import * from os.path import basename, splitext PLUGINS_DIR = ""./plugins"" def get_plugins(plugins_dir = PLUGINS_DIR): plugins = {} plugin_files = glob.glob(""{}/*.py"".format(plugins_dir)) for plugin_file in plugin_files: if plugin_file.endswith(""__init__.py""): continue name, ext = splitext(basename(plugin_file)) module_name = ""plugins.{}"".format(name) module = importlib.import_module(module_name) plugin = module.__plugin__() plugins[module.__cname__] = plugin return plugins def dispatch(plugin, fields): if not plugin.VerifyCredentials(): try: plugin.Authorize() except (AuthorizationError, Failed), e: return e.message req_fields_list = plugin.__fields__ req_fields = {} for field in fields: if field in req_fields_list: req_fields[field] = fields[field] try: return plugin.SendMsg(req_fields) except Exception, e: raise UnhandledException(e.message) if __name__ == '__main__': main() ",Fix bug due to typo,"Fix bug due to typo ",Python,mit,alfie-max/Publish d626fd1e9f808c42df5a9147bcbeb5050b923c93,tests/conftest.py,tests/conftest.py,"import os import sys from pathlib import Path import pytest if sys.version_info < (3, 4): print(""Requires Python 3.4+"") sys.exit(1) TESTS_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(TESTS_ROOT) @pytest.fixture(scope=""session"") def resources(): return Path(TESTS_ROOT) / 'resources' @pytest.fixture(scope=""function"") def outdir(tmp_path): return tmp_path @pytest.fixture(scope=""function"") def outpdf(tmp_path): return tmp_path / 'out.pdf' ","import os import sys from pathlib import Path import pytest if sys.version_info < (3, 6): print(""Requires Python 3.6+"") sys.exit(1) TESTS_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(TESTS_ROOT) @pytest.fixture(scope=""session"") def resources(): return Path(TESTS_ROOT) / 'resources' @pytest.fixture(scope=""function"") def outdir(tmp_path): return tmp_path @pytest.fixture(scope=""function"") def outpdf(tmp_path): return tmp_path / 'out.pdf' ",Test suite: don't try to run on Python < 3.6 anymore,"Test suite: don't try to run on Python < 3.6 anymore ",Python,mpl-2.0,"pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf" 83cfb4d135b5eb3eaa4efb3f74ce13d44afb4c5a,tests/test_main.py,tests/test_main.py,,"import pytest from cutadapt.__main__ import main def test_help(): with pytest.raises(SystemExit) as e: main([""--help""]) assert e.value.args[0] == 0 ",Add a test for __main__,"Add a test for __main__ ",Python,mit,marcelm/cutadapt 05b2848849553172873600ffd6344fc2b1f12d8e,example/__init__.py,example/__init__.py,"from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ex' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] ","from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example', 'legislature_name': 'Example Legislature', 'legislature_url': 'http://example.com', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013'] ",Substitute a more realistic jurisdiction_id,"Substitute a more realistic jurisdiction_id ",Python,bsd-3-clause,"datamade/pupa,mileswwatkins/pupa,rshorey/pupa,opencivicdata/pupa,mileswwatkins/pupa,influence-usa/pupa,datamade/pupa,influence-usa/pupa,rshorey/pupa,opencivicdata/pupa" 226e8c322670a310fcfb9eb95d9d59838bbac3d3,refcollections/admin_custom.py,refcollections/admin_custom.py,"from django.contrib.admin.sites import AdminSite from django.conf.urls.defaults import patterns, url from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet class ShellsAdmin(AdminSite): def get_urls(self): urls = super(ShellsAdmin, self).get_urls() my_urls = patterns('', url('upload_images/', self.admin_view(ShellsImagesUploader.as_view()), name=""upload-images""), url(r'^upload/', self.admin_view(upload_species_spreadsheet), name='upload_species_spreadsheet'), ) return my_urls + urls shells_admin = ShellsAdmin() from shells.admin import SpeciesAdmin, SpecimenAdmin, SpeciesRepresentationAdmin from shells.models import Species, Specimen, SpeciesRepresentation shells_admin.register(Species, SpeciesAdmin) shells_admin.register(Specimen, SpecimenAdmin) shells_admin.register(SpeciesRepresentation, SpeciesRepresentationAdmin) ","from django.contrib.admin.sites import AdminSite from django.conf.urls.defaults import patterns, url from shells.admin_views import ShellsImagesUploader, upload_species_spreadsheet class ShellsAdmin(AdminSite): def get_urls(self): urls = super(ShellsAdmin, self).get_urls() my_urls = patterns('', url('upload_images/', self.admin_view(ShellsImagesUploader.as_view()), name=""upload-images""), url(r'^upload/', self.admin_view(upload_species_spreadsheet), name='upload_species_spreadsheet'), ) return my_urls + urls shells_admin = ShellsAdmin() from shells.admin import SpeciesAdmin, SpecimenAdmin, SpeciesRepresentationAdmin from shells.models import Species, Specimen, SpeciesRepresentation shells_admin.register(Species, SpeciesAdmin) shells_admin.register(Specimen, SpecimenAdmin) shells_admin.register(SpeciesRepresentation, SpeciesRepresentationAdmin) from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User shells_admin.register(User, UserAdmin)",Add User back into admin,"Add User back into admin ",Python,bsd-3-clause,"uq-eresearch/archaeology-reference-collections,uq-eresearch/archaeology-reference-collections,uq-eresearch/archaeology-reference-collections,uq-eresearch/archaeology-reference-collections" ba8939167379633b5b572cd7b70c477f101b95dd,application.py,application.py,"#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app(os.getenv('FLASH_CONFIG') or 'default') manager = Manager(application) manager.add_command(""runserver"", Server(port=5003)) if __name__ == '__main__': manager.run() ","#!/usr/bin/env python import os from app import create_app from flask.ext.script import Manager, Server application = create_app( os.getenv('DM_SUPPLIER_FRONTEND_ENVIRONMENT') or 'default' ) manager = Manager(application) manager.add_command(""runserver"", Server(port=5003)) if __name__ == '__main__': manager.run() ",Rename FLASH_CONFIG to match common convention,"Rename FLASH_CONFIG to match common convention ",Python,mit,"mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,mtekel/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend" bd78770c589ff2919ce96d0b04127bfceda0583f,setup.py,setup.py,"from setuptools import setup version = '0.5.dev0' long_description = '\n\n'.join([ open('README.rst').read(), open('CREDITS.rst').read(), open('CHANGES.rst').read(), ]) install_requires = [ 'Django', 'ddsc-logging', 'ddsc-opendap', 'ddsc-site', 'dikedata-api', 'django-cors-headers', 'django-extensions', 'django-nose', 'gunicorn', 'lizard-auth-client', 'lizard-ui >= 4.0b5', 'lxml >= 3.0', 'pyproj', 'python-magic', 'python-memcached', 'raven', 'tslib', 'werkzeug', ], setup(name='ddsc-api', version=version, description=""TODO"", long_description=long_description, # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=['Programming Language :: Python', 'Framework :: Django', ], keywords=[], author='Reinout van Rees', author_email='reinout.vanrees@nelen-schuurmans.nl', url='', license='MIT', packages=['ddsc_api'], include_package_data=True, zip_safe=False, install_requires=install_requires, entry_points={ 'console_scripts': [ ]}, ) ","from setuptools import setup version = '0.5.dev0' long_description = '\n\n'.join([ open('README.rst').read(), open('CREDITS.rst').read(), open('CHANGES.rst').read(), ]) install_requires = [ 'Django', 'ddsc-logging', 'ddsc-core', 'ddsc-opendap', 'ddsc-site', 'dikedata-api', 'django-cors-headers', 'django-extensions', 'django-haystack >= 2.0', 'django-nose', 'gunicorn', 'lizard-security', 'lizard-auth-client', 'lizard-ui >= 4.0b5', 'lxml >= 3.0', 'pyproj', 'python-magic', 'python-memcached', 'raven', 'tslib', 'werkzeug', ], setup(name='ddsc-api', version=version, description=""TODO"", long_description=long_description, # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers classifiers=['Programming Language :: Python', 'Framework :: Django', ], keywords=[], author='Reinout van Rees', author_email='reinout.vanrees@nelen-schuurmans.nl', url='', license='MIT', packages=['ddsc_api'], include_package_data=True, zip_safe=False, install_requires=install_requires, entry_points={ 'console_scripts': [ ]}, ) ","Add missing libraries to the install_requires list (we import from them, so they really should be declared.","Add missing libraries to the install_requires list (we import from them, so they really should be declared. ",Python,mit,"ddsc/ddsc-api,ddsc/ddsc-api" 60f666a7d3aac09b5fa8e3df29d0ff08b67eac3c,tools/gyp/find_mac_gcc_version.py,tools/gyp/find_mac_gcc_version.py,"#!/usr/bin/env python # Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import re import subprocess import sys def main(): job = subprocess.Popen(['xcodebuild', '-version'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = job.communicate() if job.returncode != 0: print >>sys.stderr, stdout print >>sys.stderr, stderr raise Exception('Error %d running xcodebuild!' % job.returncode) matches = re.findall('^Xcode (\d+)\.(\d+)(\.(\d+))?$', stdout, re.MULTILINE) if len(matches) > 0: major = int(matches[0][0]) minor = int(matches[0][1]) if major >= 4: return 'com.apple.compilers.llvmgcc42' elif major == 3 and minor >= 1: return '4.2' else: raise Exception('Unknown XCode Version ""%s""' % version_match) else: raise Exception('Could not parse output of xcodebuild ""%s""' % stdout) if __name__ == '__main__': if sys.platform != 'darwin': raise Exception(""This script only runs on Mac"") print main() ","#!/usr/bin/env python # Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import re import subprocess import sys def main(): job = subprocess.Popen(['xcodebuild', '-version'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = job.communicate() if job.returncode != 0: print >>sys.stderr, stdout print >>sys.stderr, stderr raise Exception('Error %d running xcodebuild!' % job.returncode) matches = re.findall('^Xcode (\d+)\.(\d+)(\.(\d+))?$', stdout, re.MULTILINE) if len(matches) > 0: major = int(matches[0][0]) minor = int(matches[0][1]) if major == 3 and minor >= 1: return '4.2' elif major == 4 and minor < 5: return 'com.apple.compilers.llvmgcc42' elif major == 4 and minor >= 5: # XCode seems to select the specific clang version automatically return 'com.apple.compilers.llvm.clang.1_0' else: raise Exception('Unknown XCode Version ""%s""' % version_match) else: raise Exception('Could not parse output of xcodebuild ""%s""' % stdout) if __name__ == '__main__': if sys.platform != 'darwin': raise Exception(""This script only runs on Mac"") print main() ","Revert ""Revert ""Use clang on mac if XCode >= 4.5""""","Revert ""Revert ""Use clang on mac if XCode >= 4.5"""" The V8 dependency has been removed, so we should be able to enable clang on mac again. R=ricow@google.com Review URL: https://codereview.chromium.org//14751012 git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@22304 260f80e4-7a28-3924-810f-c04153c831b5 ",Python,bsd-3-clause,"dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk" 67b86cb3ddfb7c9e95ebed071ba167472276cc29,utils/decorators/require.py,utils/decorators/require.py,"import requests from functools import wraps from flask import request, current_app from utils.decorators.signature import sign def require(resource_namespace, permissions, resource_id=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if request.method == 'GET': payload = request.args client_key = current_app.config['CLIENTS']['plutonium']['client_key'] client_id = current_app.config['CLIENTS']['plutonium']['client_id'] data = [] for permission in permissions: data.append({ 'client_namespace' : 'app', 'client_id' : payload['client_id'], 'resource_namespace' : resource_namespace, 'permission' : permission, 'resource_id' : resource_id or '*' }) result = f(*args, **kwargs) return result return decorated_function return decorator ","import json import requests from functools import wraps from flask import request, current_app from utils.decorators.signature import sign from utils.exceptions import HttpUnauthorized def require(resource_namespace, permissions, resource_id=None): def decorator(f): @wraps(f) def decorated_function(*args, **kwargs): if request.method == 'GET': payload = request.args client_key = current_app.config['CLIENTS']['plutonium']['client_key'] client_id = current_app.config['CLIENTS']['plutonium']['client_id'] apq = current_app.config['CLIENTS']['apq'] data = [] for permission in permissions: data.append({ 'client_namespace' : 'app', 'client_id' : payload['client_id'], 'resource_namespace' : resource_namespace, 'permission' : permission, 'resource_id' : resource_id or '*' }) signature = sign(client_key, json.dumps(data)) payload = { 'data' : json.dumps(data), 'client_id': client_id, 'signature': signature } apq = requests.get(""http://%s/has_perm"" % apq['host'], params=payload) permission = json.loads(apq.content) granted = [granted for granted in permission if granted == 'True'] if len(permission) != len(granted): raise HttpUnauthorized(""You don't have enough permission to access this resource"") result = f(*args, **kwargs) return result return decorated_function return decorator ",Check for permission in apq,"Check for permission in apq ",Python,apache-2.0,PressLabs/lithium 97f0326bc5ab5ce5601b72eb3e2196dd85588705,19/Solution.py,19/Solution.py,,"class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head, n): """""" :type head: ListNode :type n: int :rtype: ListNode """""" count = 0 node = head while node is not None: count += 1 node = node.next if count - n == 0: return head.next prev = count - n - 1 node = head while prev > 0: node = node.next prev -= 1 node.next = node.next.next return head ",Add my two pass solution,"Add my two pass solution ",Python,mit,"xliiauo/leetcode,xiao0720/leetcode,xliiauo/leetcode,xiao0720/leetcode,xliiauo/leetcode" 617819e7aff47f2764d13bd183080dea54f689f9,test_equil_solver.py,test_equil_solver.py,,"# -*- coding: utf-8 -*- """""" Created on Thu Nov 5 09:44:38 2015 @author: jensv """""" import numpy as np import numpy.testing as test import scipy.integrate as integrate import equil_solver as es from scipy.interpolate import splev from nose.tools import with_setup test_equil = None def setup_func(): r"""""" Generate test equilibrium. """""" global test_equil test_equil = es.UnitlessSmoothedCoreSkin(core_radius_norm=0.9, transition_width_norm=0.033, skin_width_norm=0.034, epsilon=0.9, lambda_bar=.5) def teardown_func(): pass @with_setup(setup_func, teardown_func) def test_epsilon(): r"""""" Test that ratio of b_theta gives epsilon. """""" r_core = test_equil.core_radius a = (test_equil.core_radius + 2.*test_equil.transition_width + test_equil.skin_width) b_theta_tck = test_equil.get_tck_splines()['b_theta'] epsilon_from_b_theta_ratio = (splev(r_core, b_theta_tck) / splev(a, b_theta_tck)) test.assert_approx_equal(epsilon_from_b_theta_ratio, test_equil.epsilon, significant=3) @with_setup(setup_func, teardown_func) def test_lambda_bar(): r"""""" Test that lambda bar is given by ratio of total current to magnetic flux. """""" a = (test_equil.core_radius + 2.*test_equil.transition_width + test_equil.skin_width) b_theta_tck = test_equil.get_tck_splines()['b_theta'] b_z_tck = test_equil.get_tck_splines()['b_z'] calculated_lambda = (2.*splev(a, b_theta_tck) / (splev(a, b_z_tck))) test.assert_approx_equal(calculated_lambda, test_equil.lambda_bar, significant=3) ",Add tests for equilibrium profiles.,"Add tests for equilibrium profiles. ",Python,mit,"jensv/fluxtubestability,jensv/fluxtubestability" 7f2700ee4b6aafed259d78affef462197194d2fc,usecase/spider_limit.py,usecase/spider_limit.py,,"# coding: utf-8 import setup_script from grab.spider import Spider, Task import logging class TestSpider(Spider): def task_generator(self): yield Task('initial', url='http://google.com:89/', network_try_count=9) def task_initial(self): print 'done' logging.basicConfig(level=logging.DEBUG) bot = TestSpider(network_try_limit=10) bot.setup_grab(timeout=1) bot.run() ",Add use case of spider with limits,"Add use case of spider with limits ",Python,mit,"kevinlondon/grab,SpaceAppsXploration/grab,liorvh/grab,subeax/grab,alihalabyah/grab,pombredanne/grab-1,SpaceAppsXploration/grab,subeax/grab,codevlabs/grab,giserh/grab,istinspring/grab,istinspring/grab,DDShadoww/grab,shaunstanislaus/grab,huiyi1990/grab,huiyi1990/grab,giserh/grab,maurobaraldi/grab,lorien/grab,pombredanne/grab-1,raybuhr/grab,codevlabs/grab,lorien/grab,shaunstanislaus/grab,alihalabyah/grab,subeax/grab,raybuhr/grab,DDShadoww/grab,maurobaraldi/grab,liorvh/grab,kevinlondon/grab" 15efe5ecd3f17ec05f3dc9054cd823812c4b3743,utils/http.py,utils/http.py,"import requests def retrieve_json(url): r = requests.get(url) r.raise_for_status() return r.json() ","import requests DEFAULT_TIMEOUT = 10 def retrieve_json(url, timeout=DEFAULT_TIMEOUT): r = requests.get(url, timeout=timeout) r.raise_for_status() return r.json() ",Add a default timeout parameter to retrieve_json,"Add a default timeout parameter to retrieve_json ",Python,bsd-3-clause,"tebriel/dd-agent,jyogi/purvar-agent,pmav99/praktoras,gphat/dd-agent,manolama/dd-agent,pmav99/praktoras,gphat/dd-agent,Wattpad/dd-agent,brettlangdon/dd-agent,cberry777/dd-agent,pmav99/praktoras,brettlangdon/dd-agent,tebriel/dd-agent,tebriel/dd-agent,Wattpad/dd-agent,jyogi/purvar-agent,cberry777/dd-agent,manolama/dd-agent,gphat/dd-agent,takus/dd-agent,tebriel/dd-agent,gphat/dd-agent,takus/dd-agent,cberry777/dd-agent,Wattpad/dd-agent,c960657/dd-agent,c960657/dd-agent,Wattpad/dd-agent,indeedops/dd-agent,takus/dd-agent,indeedops/dd-agent,tebriel/dd-agent,jyogi/purvar-agent,Wattpad/dd-agent,takus/dd-agent,gphat/dd-agent,cberry777/dd-agent,takus/dd-agent,brettlangdon/dd-agent,pmav99/praktoras,jyogi/purvar-agent,c960657/dd-agent,c960657/dd-agent,brettlangdon/dd-agent,indeedops/dd-agent,manolama/dd-agent,brettlangdon/dd-agent,c960657/dd-agent,manolama/dd-agent,indeedops/dd-agent,pmav99/praktoras,jyogi/purvar-agent,cberry777/dd-agent,manolama/dd-agent,indeedops/dd-agent" 1c216c833d42b648e4d38298eac1616d8748c76d,tests/test_pathutils.py,tests/test_pathutils.py,"from os.path import join import sublime import sys from unittest import TestCase from unittest.mock import patch version = sublime.version() if version < '3000': from libsass import pathutils else: from sublime_libsass.libsass import pathutils class TestPathutils(TestCase): @classmethod def setUpClass(cls): super(TestPathutils, cls).setUpClass() import time time.sleep(3) # Fix for Python3 async importing? Some race condition. def test_subpaths(self): path = join('/foo','bar','baz') exprmt = pathutils.subpaths(path) expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ] self.assertEqual(exprmt, expect) @patch('pathutils.os') def test_grep_r(self, mock_os): mock_os.walk = lambda x: [('/tmp','',['file.scss'])] self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), []) self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), []) ","from os.path import join import sublime import sys from unittest import TestCase from unittest.mock import patch version = sublime.version() class TestPathutils(TestCase): @classmethod def setUpClass(cls): super(TestPathutils, cls).setUpClass() if version < '3000': from libsass import pathutils else: from sublime_libsass.libsass import pathutils def test_subpaths(self): path = join('/foo','bar','baz') exprmt = pathutils.subpaths(path) expect = [ join('/foo','bar','baz'), join('/foo','bar'), join('/foo'), join('/') ] self.assertEqual(exprmt, expect) @patch('pathutils.os') def test_grep_r(self, mock_os): mock_os.walk = lambda x: [('/tmp','',['file.scss'])] self.assertEqual(pathutils.find_type_dirs('anything', '.scss'), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', ['.scss', '.sass']), ['/tmp']) self.assertEqual(pathutils.find_type_dirs('anything', '.sass'), []) self.assertEqual(pathutils.find_type_dirs('anything', ['.txt', '.csv']), []) ",Move importing of source to class setup,"Move importing of source to class setup ",Python,mit,"blitzrk/sublime_libsass,blitzrk/sublime_libsass" f7f20c50b82e3b8f8f2be4687e661348979fe6a6,script_helpers.py,script_helpers.py,"""""""A set of functions to standardize some options for python scripts."""""" def setup_parser_help(parser, additional_docs=None): """""" Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """""" from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """""" Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """""" verbose_help = ""provide more information during processing"" parser.add_argument(""-v"", ""--verbose"", help=verbose_help, action=""store_true"") def add_directories(parser): """""" Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """""" parser.add_argument(""dir"", metavar='dir', nargs='+', help=""Directory to process"") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser ","""""""A set of functions to standardize some options for python scripts."""""" def setup_parser_help(parser, additional_docs=None): """""" Set formatting for parser to raw and add docstring to help output Parameters ---------- parser : `ArgumentParser` The parser to be modified. additional_docs: str Any documentation to be added to the documentation produced by `argparse` """""" from argparse import RawDescriptionHelpFormatter parser.formatter_class = RawDescriptionHelpFormatter if additional_docs is not None: parser.epilog = additional_docs def add_verbose(parser): """""" Add a verbose option (--verbose or -v) to parser. Parameters: ----------- parser : `ArgumentParser` """""" verbose_help = ""provide more information during processing"" parser.add_argument(""-v"", ""--verbose"", help=verbose_help, action=""store_true"") def add_directories(parser, nargs_in='+'): """""" Add a positional argument that is one or more directories. Parameters ---------- parser : `ArgumentParser` """""" parser.add_argument(""dir"", metavar='dir', nargs=nargs_in, help=""Directory to process"") def construct_default_parser(docstring=None): #import script_helpers import argparse parser = argparse.ArgumentParser() if docstring is not None: setup_parser_help(parser, docstring) add_verbose(parser) add_directories(parser) return parser ",Allow for directories argument to be optional,"Allow for directories argument to be optional ",Python,bsd-3-clause,mwcraig/msumastro ac3447251395a0f6ee445d76e1c32910505a5bd4,scripts/remove_after_use/reindex_quickfiles.py,scripts/remove_after_use/reindex_quickfiles.py,,"import sys import progressbar from django.core.paginator import Paginator from website.app import setup_django setup_django() from website.search.search import update_file from osf.models import QuickFilesNode PAGE_SIZE = 50 def reindex_quickfiles(dry): qs = QuickFilesNode.objects.all().order_by('id') count = qs.count() paginator = Paginator(qs, PAGE_SIZE) progress_bar = progressbar.ProgressBar(maxval=count).start() n_processed = 0 for page_num in paginator.page_range: page = paginator.page(page_num) for quickfiles in page.object_list: for file_ in quickfiles.files.all(): if not dry: update_file(file_) n_processed += len(page.object_list) progress_bar.update(n_processed) if __name__ == '__main__': dry = '--dry' in sys.argv reindex_quickfiles(dry=dry) ",Add script to re-index users' files in quickfiles nodes,"Add script to re-index users' files in quickfiles nodes ",Python,apache-2.0,"caseyrollins/osf.io,sloria/osf.io,erinspace/osf.io,aaxelb/osf.io,pattisdr/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,pattisdr/osf.io,HalcyonChimera/osf.io,icereval/osf.io,adlius/osf.io,brianjgeiger/osf.io,mattclark/osf.io,Johnetordoff/osf.io,adlius/osf.io,aaxelb/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,erinspace/osf.io,brianjgeiger/osf.io,felliott/osf.io,mfraezz/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,saradbowman/osf.io,aaxelb/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,mattclark/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,mfraezz/osf.io,adlius/osf.io,erinspace/osf.io,aaxelb/osf.io,icereval/osf.io,mfraezz/osf.io,baylee-d/osf.io,felliott/osf.io,HalcyonChimera/osf.io,felliott/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,baylee-d/osf.io,baylee-d/osf.io,adlius/osf.io,Johnetordoff/osf.io,felliott/osf.io,HalcyonChimera/osf.io,icereval/osf.io,caseyrollins/osf.io,mattclark/osf.io,mfraezz/osf.io" be779b6b7f47750b70afa6f0aeb67b99873e1c98,indico/modules/events/tracks/forms.py,indico/modules/events/tracks/forms.py,"# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see . from __future__ import unicode_literals from wtforms.fields import StringField, TextAreaField from wtforms.validators import DataRequired from indico.util.i18n import _ from indico.web.forms.base import IndicoForm class TrackForm(IndicoForm): title = StringField(_('Title'), [DataRequired()], description=_('Title of the track')) code = StringField(_('Code'), description=_('Code for the track')) description = TextAreaField(_('Description'), description=_('Text describing the track')) ","# This file is part of Indico. # Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN). # # Indico is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # Indico is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Indico; if not, see . from __future__ import unicode_literals from wtforms.fields import StringField, TextAreaField from wtforms.validators import DataRequired from indico.util.i18n import _ from indico.web.forms.base import IndicoForm class TrackForm(IndicoForm): title = StringField(_('Title'), [DataRequired()]) code = StringField(_('Code')) description = TextAreaField(_('Description'), render_kw={'rows': 10}) ","Remove useless field descs, increase rows","Tracks: Remove useless field descs, increase rows ",Python,mit,"DirkHoffmann/indico,pferreir/indico,OmeGak/indico,indico/indico,mvidalgarcia/indico,mvidalgarcia/indico,indico/indico,OmeGak/indico,DirkHoffmann/indico,mic4ael/indico,mvidalgarcia/indico,OmeGak/indico,indico/indico,OmeGak/indico,indico/indico,ThiefMaster/indico,pferreir/indico,ThiefMaster/indico,ThiefMaster/indico,pferreir/indico,mic4ael/indico,DirkHoffmann/indico,ThiefMaster/indico,mic4ael/indico,mvidalgarcia/indico,mic4ael/indico,DirkHoffmann/indico,pferreir/indico" bdc0466c63347280fbd8bc8c30fb07f294200194,client/third_party/idna/__init__.py,client/third_party/idna/__init__.py,"# Emulate the bare minimum for idna for the Swarming bot. # In practice, we do not need it, and it's very large. def encode(host, uts46): return unicode(host) ","# Emulate the bare minimum for idna for the Swarming bot. # In practice, we do not need it, and it's very large. # See https://pypi.org/project/idna/ from encodings import idna def encode(host, uts46=False): # pylint: disable=unused-argument # Used by urllib3 return idna.ToASCII(host) def decode(host): # Used by cryptography/hazmat/backends/openssl/x509.py return idna.ToUnicode(host) ",Change idna stub to use python's default,"[client] Change idna stub to use python's default Fix a regression from 690b8ae29be2ca3b4782fa6ad0e7f2454443c38d which broke select bots running inside docker. The new stub is still simpler than https://pypi.org/project/idna/ and lighter weight but much better than ignoring the ""xn-"" encoding as this was done previously. As per the project home page: This acts as a suitable replacement for the “encodings.idna” module that comes with the Python standard library, but only supports the old, deprecated IDNA specification (RFC 3490). In practice, we don't expect to use non-ASCII hostnames, so it's not a big deal for us. decode() is required by openssl/x509.py. TBR=jchinlee@chromium.org Bug: 916644 Change-Id: Ia999a56b981d943e2f3d942f83e40d40e1bb805b Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1573244 Reviewed-by: Marc-Antoine Ruel Commit-Queue: Marc-Antoine Ruel ",Python,apache-2.0,"luci/luci-py,luci/luci-py,luci/luci-py,luci/luci-py" f7f25876d3398cacc822faf2b16cc156e88c7fd3,misc/jp2_kakadu_pillow.py,misc/jp2_kakadu_pillow.py,,"# This the basic flow for getting from a JP2 to a jpg w/ kdu_expand and Pillow # Useful for debugging the scenario independent of the server. from PIL import Image from PIL.ImageFile import Parser from os import makedirs, path, unlink import subprocess import sys KDU_EXPAND='/usr/local/bin/kdu_expand' LIB_KDU='/usr/local/lib/libkdu_v72R.so' TMP='/tmp' INPUT_JP2='/home/jstroop/Desktop/nanteuil.jp2' OUT_JPG='/tmp/test.jpg' REDUCE=0 ### cmds, etc. pipe_fp = '%s/mypipe.bmp' % (TMP,) kdu_cmd = '%s -i %s -o %s -num_threads 4 -reduce %d' % (KDU_EXPAND, INPUT_JP2, pipe_fp, REDUCE) mkfifo_cmd = '/usr/bin/mkfifo %s' % (pipe_fp,) rmfifo_cmd = '/bin/rm %s' % (pipe_fp,) # make a named pipe mkfifo_resp = subprocess.check_call(mkfifo_cmd, shell=True) if mkfifo_resp == 0: print 'mkfifo OK' # write kdu_expand's output to the named pipe kdu_expand_proc = subprocess.Popen(kdu_cmd, shell=True, bufsize=-1, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env={ 'LD_LIBRARY_PATH' : KDU_EXPAND }) # open the named pipe and parse the stream with open(pipe_fp, 'rb') as f: p = Parser() while True: s = f.read(1024) if not s: break p.feed(s) im = p.close() # finish kdu kdu_exit = kdu_expand_proc.wait() if kdu_exit != 0: map(sys.stderr.write, kdu_expand_proc.stderr) else: # if kdu was successful, save to a jpg map(sys.stdout.write, kdu_expand_proc.stdout) im = im.resize((719,900), resample=Image.ANTIALIAS) im.save(OUT_JPG, quality=95) # remove the named pipe rmfifo_resp = subprocess.check_call(rmfifo_cmd, shell=True) if rmfifo_resp == 0: print 'rm fifo OK' ","Use this enough, might as well add it.","Use this enough, might as well add it. ",Python,bsd-2-clause,"ehenneken/loris,medusa-project/loris,rlskoeser/loris,medusa-project/loris,rlskoeser/loris,ehenneken/loris" 1867707bd33bb4908e63f82f3d975fcf5d9e829a,plc-upo-alarm.py,plc-upo-alarm.py,,"import shlex import sys import re from subprocess import Popen, PIPE def extractMacAddress(ampStatLine): macAddr = None items = ampStatLine.split( "" "" ) for index in range(len(items)): if (items[index] == ""MAC"") and ((index+1) < len(items)): if re.match(""[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$"", items[index+1].lower()): return items[index+1] return macAddr device = ""eth0"" if len(sys.argv) > 1: device = sys.argv[1] cmd = ""ampstat -m -i {}"".format(device) process = Popen(shlex.split(cmd), stdout=PIPE) (output, err) = process.communicate() exit_code = process.wait() allowedMacAddrMap = dict() outputArray = output.splitlines() for entries in outputArray: macAddr = extractMacAddress(entries) if macAddr is not None: # Check if mac address is allowed on the network print macAddr ",Read ampstat -m -i and print out the mac addresses on the powerline network,"Read ampstat -m -i and print out the mac addresses on the powerline network ",Python,mit,alanbertadev/plc_upo_alarm 1e006b5df70303b743cb2fd7d6c2a5ef4234f70b,zazo/__init__.py,zazo/__init__.py,"""""""An Extensible Dependency Resolver written in Python """""" __version__ = ""0.1.0.dev0"" ","""""""An Extensible Dependency Resolver written in Python """""" __version__ = ""0.0.0a2"" ",Switch to an alpha version,"Switch to an alpha version ",Python,mit,"pradyunsg/zazo,pradyunsg/zazo" 2b7bdf39497809749c504d10399dffabe52e97ca,testutils/base_server.py,testutils/base_server.py,"from testrunner import testhelp class BaseServer(object): ""Base server class. Responsible with setting up the ports etc."" # We only want standalone repositories to have SSL support added via # useSSL sslEnabled = False def start(self, resetDir = True): raise NotImplementedError def cleanup(self): pass def stop(self): raise NotImplementedError def reset(self): raise NotImplementedError def initPort(self): ports = testhelp.findPorts(num = 1, closeSockets=False)[0] self.port = ports[0] self.socket = ports[1] ","from testrunner import testhelp class BaseServer(object): ""Base server class. Responsible with setting up the ports etc."" # We only want standalone repositories to have SSL support added via # useSSL sslEnabled = False def start(self, resetDir = True): raise NotImplementedError def cleanup(self): pass def stop(self): raise NotImplementedError def reset(self): raise NotImplementedError def isStarted(self): raise NotImplementedError def initPort(self): ports = testhelp.findPorts(num = 1, closeSockets=False)[0] self.port = ports[0] self.socket = ports[1] def __del__(self): if self.isStarted(): print 'warning: %r was not stopped before freeing' % self try: self.stop() except: print 'warning: could not stop %r in __del__' % self ",Implement a noisy __del__ in BaseServer.,"Implement a noisy __del__ in BaseServer. It will complain if the server is still running, and attempt to stop it. ",Python,apache-2.0,"sassoftware/testutils,sassoftware/testutils,sassoftware/testutils" aed959a0593558b6063e70c3b594feb6caa4bdda,tests/runner/compose/init_test.py,tests/runner/compose/init_test.py,"import os import tempfile import shutil from unittest import TestCase import yaml from dusty import constants from dusty.runner.compose import _write_composefile class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() self.temp_compose_path = os.path.join(self.temp_compose_dir, 'docker-compose.yml') self.old_compose_dir = constants.COMPOSE_DIR constants.COMPOSE_DIR = self.temp_compose_dir self.test_spec = {'app-a': {'image': 'app/a'}} def tearDown(self): constants.COMPOSE_DIR = self.old_compose_dir shutil.rmtree(self.temp_compose_dir) def test_write_composefile(self): _write_composefile(self.test_spec) written = open(self.temp_compose_path, 'r').read() self.assertItemsEqual(yaml.load(written), self.test_spec) ","import os import tempfile import shutil from unittest import TestCase from mock import patch import yaml from dusty import constants from dusty.runner.compose import _write_composefile, _get_docker_env class TestComposeRunner(TestCase): def setUp(self): self.temp_compose_dir = tempfile.mkdtemp() self.temp_compose_path = os.path.join(self.temp_compose_dir, 'docker-compose.yml') self.old_compose_dir = constants.COMPOSE_DIR constants.COMPOSE_DIR = self.temp_compose_dir self.test_spec = {'app-a': {'image': 'app/a'}} def tearDown(self): constants.COMPOSE_DIR = self.old_compose_dir shutil.rmtree(self.temp_compose_dir) def test_write_composefile(self): _write_composefile(self.test_spec) written = open(self.temp_compose_path, 'r').read() self.assertItemsEqual(yaml.load(written), self.test_spec) @patch('dusty.runner.compose._check_output_demoted') def test_get_docker_env(self, fake_check_output): fake_check_output.return_value = """""" export DOCKER_TLS_VERIFY=1 export DOCKER_HOST=tcp://192.168.59.103:2376 export DOCKER_CERT_PATH=/Users/root/.boot2docker/certs/boot2docker-vm"""""" expected = {'DOCKER_TLS_VERIFY': '1', 'DOCKER_HOST': 'tcp://192.168.59.103:2376', 'DOCKER_CERT_PATH': '/Users/root/.boot2docker/certs/boot2docker-vm'} result = _get_docker_env() self.assertItemsEqual(result, expected) ",Add a test for _get_docker_env,"Add a test for _get_docker_env ",Python,mit,"gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty,gamechanger/dusty" ee5b38c649b1a5b46ce5b53c179bde57b3a6e6f2,examples/customserverexample.py,examples/customserverexample.py,,"#!/usr/bin/env python3 from pythinclient.server import ThinServer class CustomThinServer(BasicThinServer): def __init__(self, port=65000, is_daemon=False): super(BasicThinServer, self).__init__(port, is_daemon=is_daemon) # add custom server hooks self.add_hook('help', self.__server_help) self.add_hook('echo', self.__server_echo) self.add_hook('log', self.__server_log) def on_accept(self, conn, addr): """""" This is basically a copy of the on_accept from the BasicThinServer """""" # receive the message message = conn.recv(self.recv_size) # handle the message self.on_receive(message, conn, addr) # close the connection conn.close() def __server_help(self, msg, conn, addr): conn.send( """""" Available commands: help : shows this help echo : send a message back to the client log : log a message to the server.log file """""".encode('ascii')) def __server_echo(self, msg, conn, addr): conn.send((msg + '\n').encode('ascii')) def __server_log(self, msg, conn, addr): # write the given message to the logfile with open(""server.log"", ""a+"") as fp: fp.write(msg + '\n') if __name__ == ""__main__"": from sys import argv daemon = True if ""-d"" in argv or ""--daemon"" in argv else False server = CustomThinServer(is_daemon=daemon) # start it up server.start()",Add a custom server example implementation. This is fully compatible with the client example.,"Add a custom server example implementation. This is fully compatible with the client example. ",Python,bsd-3-clause,alekratz/pythinclient 44da0c97ac662375dd45d201cce88c32896ca361,scripts/list-checkins.py,scripts/list-checkins.py,,"#!/usr/bin/env python # This script retrieves a detailed list of the currently running checkins import argparse import concurrent.futures import datetime import json import sys import boto3 SFN = boto3.client('stepfunctions') def format_date_fields(obj): for key in obj: if isinstance(obj[key], datetime.datetime): obj[key] = obj[key].isoformat() return obj def get_execution_details(execution_arn): e = SFN.describe_execution(executionArn=execution_arn) e = format_date_fields(e) del e['ResponseMetadata'] return e def main(args): results = [] state_machine_arn = args.state_machine_arn # TODO(dw): pagination for > 100 executions executions = SFN.list_executions( stateMachineArn=state_machine_arn, statusFilter='RUNNING' ) with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: futures = [] for e in executions['executions']: future = executor.submit(get_execution_details, e['executionArn']) futures.append(future) for future in concurrent.futures.as_completed(futures): results.append(future.result()) print(json.dumps(results)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--state-machine-arn', required=True) args = parser.parse_args() main(args) ",Add script to list scheduled checkins,"Add script to list scheduled checkins ",Python,mit,DavidWittman/serverless-southwest-check-in 91d7e27882c4317199f2de99964da4ef3a2e3950,edx_data_research/web_app/__init__.py,edx_data_research/web_app/__init__.py,"from flask import Flask from flask.ext.mail import Mail from flask.ext.mongoengine import MongoEngine from flask.ext.security import MongoEngineUserDatastore, Security # Create app app = Flask(__name__) app.config.from_object('config') # Create mail object mail = Mail(app) ","from flask import Flask from flask.ext.mail import Mail from flask.ext.mongoengine import MongoEngine from flask.ext.security import MongoEngineUserDatastore, Security # Create app app = Flask(__name__) app.config.from_object('config') # Create mail object mail = Mail(app) # Create database connection object db = MongoEngine(app) from edx_data_research.web_app.models import User, Role # Setup Flask-Security user_datastore = MongoEngineUserDatastore(db, User, Role) security = Security(app, user_datastore) ",Define flask security object for login stuff,Define flask security object for login stuff,Python,mit,"McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research" b3bfd60643a670ca1ab590f539d1c96e95e3623b,setup.py,setup.py,"# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup import os setup( name='openhim-report-tasks', version='0.1.0', author='Jembi Health Systems NPC', packages=['openhimtasks'], description='OpenHIM Report and Alerting Tasks', long_description=open('README.md').read(), install_requires=[ ""mysql-python"", ], data_files=[('/etc/cron.daily', ['openhim_reports.sh']), ('/etc/cron.hourly', ['openhim_alerts.sh']), ('/etc', ['openhim-report-tasks.conf']), ], ) # Setup /etc source conf files with open('/etc/openhim-report-tasks.source', 'w') as src: src.write(os.getcwd()) ","# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup import os setup( name='openhim-report-tasks', version='0.1.0', author='Jembi Health Systems NPC', packages=['openhimtasks'], description='OpenHIM Report and Alerting Tasks', long_description=open('README.md').read(), install_requires=[ ""mysql-python"", ], data_files=[('/etc/cron.daily', ['openhim_reports.sh']), ('/etc/cron.hourly', ['openhim_alerts.sh']), ('/etc', ['openhim-report-tasks.conf']), ], ) # Setup /etc source conf files with open('/etc/openhim-report-tasks.source', 'w') as src: src.write(os.getcwd()) # Cron script permissions os.chmod('/etc/cron.daily/openhim_reports.sh', 0755) os.chmod('/etc/cron.hourly/openhim_alerts.sh', 0755) ",Set script permissions during install,"Set script permissions during install ",Python,mpl-2.0,jembi/openhim-report-tasks