diff --git "a/benchmark.csv" "b/benchmark.csv" --- "a/benchmark.csv" +++ "b/benchmark.csv" @@ -1,70 +1,25 @@ -instruction,output -"Here are the two versions of a code. The old version is - - -The new version is - -from abc import * -import os -from SimpleXMLRPCServer import SimpleXMLRPCServer -import xmlrpclib -import sys - -class Forker(object): - ''' Easily fork a job and retrieve the results ''' - __metaclass__ = ABCMeta - - def __init__(self, ip='localhost', port=3370): - self.ip = ip - self.port = port - self.server = SimpleXMLRPCServer((ip, port), allow_none=True) - self.server.register_function(self.return_to_parent, ""return_to_parent"") - self.client_return = None - - @abstractmethod - def fork(self, code_block): - ''' Fork off a child process, and run code_block. Return the json_hash - sent by the client''' - pass - - def _invoke_child(self, code_block): - parent_url = ""http://"" + str(self.ip) + "":"" + str(self.port) + ""/"" - proxy = xmlrpclib.ServerProxy(parent_url, allow_none=True) - client_return = code_block() - proxy.return_to_parent(client_return) - sys.exit(0) - - def return_to_parent(self, client_return): - ''' Invoked by child process to return a value ''' - print ""client_return!:"" % client_return - self.client_return = client_return - return None - -class LocalForker(Forker): - def fork(self, code_block): - # TODO(cs): use subprocess instead to spawn baby snakes - pid = os.fork() - if pid == 0: # Child - self._invoke_child(code_block) - else: # Parent - self.server.handle_request() - return self.client_return - -class RemoteForker(Forker): - def __init__(self, server_info_list): - ''' cycles through server_info_list for each invocation of fork() ''' - pass - - def fork(self, code_block): - # Would need bidirectional communication between parent and child.. - # (Need to send code_block to client) - pass - - - -Write a commit message that summarizes the changes.",Add a forker class: spawn children and return results via XML-RPC -"Here are the two versions of a code. The old version is -import unittest +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 @@ -85,10 +40,7 @@ class QueueTestCase(unittest.TestCase): def tearDown(self): pass - - -The new version is -import unittest +","import unittest from aids.queue.queue import Queue @@ -121,11 +73,9 @@ class QueueTestCase(unittest.TestCase): def tearDown(self): pass - - -Write a commit message that summarizes the changes.","Add unit tests for enqueue, dequeue and length for Queue" -"Here are the two versions of a code. The old version is -import sys +","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 @@ -175,10 +125,7 @@ def print_message(message, tests, query): print print ""Query:"" print ""%s"" % query - - -The new version is -import sys +","import sys import sqlparse from .checks import has_cross_join @@ -224,97 +171,93 @@ def print_message(message, query): 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. +"""""" -Write a commit message that summarizes the changes.",Work with plain SQL files -"Here are the two versions of a code. The old version is -# -*- coding: utf-8; -*- - -import re - -from jenkins_autojobs import main - - -def test_filter_jobs(): - class Job: - def __init__(self, name): - self.name = name - - class jenkins: - pass - - names = ['feature-one', 'feature-two', 'release-one', 'release-two'] - jenkins.jobs = [Job(i) for i in names] - filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)} - - #------------------------------------------------------------------------- - assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'} +import os - res = filter_jobs(by_name_regex=[re.compile('feature-')]) - assert res == {'feature-one', 'feature-two'} +import requests +import six - res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')]) - assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'} +import conda_smithy.ci_register - #------------------------------------------------------------------------- - view_jobs = { - 'v1': [Job('scratch-one'), Job('scratch-two')], - 'v2': [Job('release-one'), Job('maintenance-three')] - } - jenkins.view_jobs = lambda x: view_jobs[x] - res = filter_jobs(by_views=['v1']) - assert res == {'scratch-one', 'scratch-two'} +def rebuild_travis(repo_slug): + headers = conda_smithy.ci_register.travis_headers() - res = filter_jobs(by_views=['v1', 'v2']) - assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'} + # 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() -The new version is -# -*- coding: utf-8; -*- -import re +if __name__ == '__main__': + rebuild_travis('conda-forge/conda-forge.github.io') +",""""""" +Trigger the conda-forge.github.io Travis job to restart. +"""""" -from jenkins_autojobs import main +import os -def test_filter_jobs(): - class Job: - def __init__(self, name): - self.name = name +import requests +import six - class jenkins: - @staticmethod - def view_jobs(x): - return { - 'v1': [Job('scratch-one'), Job('scratch-two')], - 'v2': [Job('release-one'), Job('maintenance-three')] - }[x] +import conda_smithy.ci_register - names = ['feature-one', 'feature-two', 'release-one', 'release-two'] - jenkins.jobs = [Job(i) for i in names] - filter_jobs = lambda **kw: {i.name for i in main.filter_jobs(jenkins, **kw)} - #------------------------------------------------------------------------- - assert filter_jobs() == {'feature-one', 'feature-two', 'release-one', 'release-two'} +def rebuild_travis(repo_slug): + headers = conda_smithy.ci_register.travis_headers() - res = filter_jobs(by_name_regex=[re.compile('feature-')]) - assert res == {'feature-one', 'feature-two'} + # 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"" - res = filter_jobs(by_name_regex=[re.compile('.*one'), re.compile('.*two')]) - assert res == {'feature-one', 'feature-two', 'release-one', 'release-two'} + # 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() - #------------------------------------------------------------------------- - res = filter_jobs(by_views=['v1']) - assert res == {'scratch-one', 'scratch-two'} - res = filter_jobs(by_views=['v1', 'v2']) - assert res == {'scratch-one', 'scratch-two', 'release-one', 'maintenance-three'} +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. -Write a commit message that summarizes the changes.",Fix tests on Python 2 -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +[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 @@ -346,10 +289,7 @@ if __name__ == '__main__': rospy.on_shutdown(rospy.ServiceProxy('/motor_off',Trigger).call) rospy.ServiceProxy('/motor_on',Trigger).call() WallStop().run() - - -The new version is -#!/usr/bin/env python +","#!/usr/bin/env python import rospy,copy from geometry_msgs.msg import Twist from std_srvs.srv import Trigger, TriggerResponse @@ -381,26 +321,104 @@ if __name__ == '__main__': 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', + ) -Write a commit message that summarizes the changes.",Reduce the name of a function -"Here are the two versions of a code. The old version is -from archivebox import util + def test_password_change_done(self): + self.check_url( + views.password_change_done, + '/password/change/done/', + 'password_change_done', + ) -def test_download_url_downloads_content(): - text = util.download_url(""https://example.com"") - assert ""Example Domain"" in text + def test_password_reset(self): + self.check_url( + views.password_reset, + '/password/reset/', + 'password_reset', + ) -The new version is -from archivebox import util + def test_password_reset_done(self): + self.check_url( + views.password_reset_done, + '/password/reset/done/', + 'password_reset_done', + ) -def test_download_url_downloads_content(): - text = util.download_url(""http://localhost:8080/static/example.com.html"") - assert ""Example Domain"" in text + 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. -Write a commit message that summarizes the changes.",Refactor util tests to use local webserver -"Here are the two versions of a code. The old version is -from .compat import decode, encode +* 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): @@ -432,10 +450,7 @@ def is_valid(file_path): from os import path, stat return path.exists(file_path) and stat(file_path).st_size > 0 - - -The new version is -from .compat import decode, encode +","from .compat import decode, encode def read_data(file_path): @@ -481,65 +496,107 @@ def is_valid(file_path): 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. +"""""" -Write a commit message that summarizes the changes.",Create a new file if the path is invalid. -"Here are the two versions of a code. The old version is -# -*- coding: utf-8 -*- -# -# (c) 2016 Björn Ricks -# -# See LICENSE comming with the source of 'phell' for details. -# -import sys +from . import libui -def to_hex(value): - if sys.version_info.major < 3: - return value.encode('hex') - return """".join(""%02x"" % b for b in value) +class App: + def __init__(self): + """""" + Creates a new pylibui app. -def from_hex(value): - if sys.version_info.major < 3: - return value.decode('hex') - return bytes.fromhex(value) + """""" + options = libui.uiInitOptions() + libui.uiInit(options) -# vim: set ts=4 sw=4 tw=80: + def start(self): + """""" + Starts the application main loop. + :return: None + """""" + libui.uiMain() -The new version is -# -*- coding: utf-8 -*- -# -# (c) 2016 Björn Ricks -# -# See LICENSE comming with the source of 'phell' for details. -# -import sys + 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 to_hex(value): - if sys.version_info.major < 3: - return value.encode('hex') - return """".join(""%02x"" % b for b in value) + def __enter__(self): + self.start() + + def start(self): + """""" + Starts the application main loop. + :return: None + """""" + libui.uiMain() -def from_hex(value): - if sys.version_info.major < 3: - return value.decode('hex') - return bytes.fromhex(value) + def __exit__(self, exc_type, exc_val, exc_tb): + self.stop() + self.close() + -def swap_bytes(value): - if sys.version_info.major < 3: - return """".join([bytes(b) for b in reversed(value)]) - return bytes(reversed(value)) + def stop(self): + """""" + Stops the application main loop. -# vim: set ts=4 sw=4 tw=80: + :return: None + """""" + libui.uiQuit() + def close(self): + """""" + Closes the application and frees resources. -Write a commit message that summarizes the changes.",Add function to swap byte order -"Here are the two versions of a code. The old version is -def flatten(lst): + :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)] @@ -554,10 +611,7 @@ def _flatten(lst): yield from _flatten(item) else: yield lst - - -The new version is -def flatten(lst): +","def flatten(lst): """"""Completely flatten an arbitrarily-deep list"""""" return [*_flatten(lst)] @@ -569,11 +623,9 @@ def _flatten(lst): yield from _flatten(item) elif item is not None: yield item - - -Write a commit message that summarizes the changes.",Tidy and simplify generator code -"Here are the two versions of a code. The old version is -from nose.tools import istest, assert_equal +",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 @@ -588,10 +640,7 @@ def output_of_run_is_stored(): def cwd_of_run_can_be_set(): result = shell.run([""pwd""], cwd=""/"") assert_equal(""/\n"", result.output) - - -The new version is -from nose.tools import istest, assert_equal +","from nose.tools import istest, assert_equal from spur import LocalShell @@ -611,11 +660,9 @@ def cwd_of_run_can_be_set(): 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) - - -Write a commit message that summarizes the changes.",Add test for LocalShell.run with update_env -"Here are the two versions of a code. The old version is -from trac.core import Component, implements +",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): @@ -623,10 +670,7 @@ class KKBOXSecretTicketsPolicy(Component): def get_permission_actions(self): return ['SECRET_VIEW'] - - -The new version is -from trac.ticket.model import Ticket +","from trac.ticket.model import Ticket from trac.core import Component, implements, TracError from trac.perm import IPermissionPolicy @@ -665,11 +709,15 @@ class KKBOXSecretTicketsPolicy(Component): 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. -Write a commit message that summarizes the changes.",Mark ticket as sensitive by keyword -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +[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 @@ -688,10 +736,7 @@ setup( url=""https://github.com/timstaley/pysovo"", install_requires=required ) - - -The new version is -#!/usr/bin/env python +","#!/usr/bin/env python from setuptools import setup @@ -710,14 +755,9 @@ setup( url=""https://github.com/timstaley/pysovo"", install_requires=required ) - - -Write a commit message that summarizes the changes.",Add triggers module to install. -"Here are the two versions of a code. The old version is - - -The new version is -#!/usr/bin/env python +",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. @@ -781,14 +821,9 @@ def main(): if __name__ == ""__main__"": main() - - -Write a commit message that summarizes the changes.",Make ticker symbols lower case -"Here are the two versions of a code. The old version is - - -The new version is -import glob +",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]]; @@ -819,11 +854,9 @@ print len( palette ) for pixel in palette: print str(pixel[ 0 ] ) + ""\t"" + str(pixel[ 1 ] ) + ""\t"" + str(pixel[ 2 ] ) - - -Write a commit message that summarizes the changes.",Add utility to extract palette for the DOS version -"Here are the two versions of a code. The old version is -#!/usr/bin/env python2 +",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 # @@ -845,10 +878,7 @@ import giles.server server = giles.server.Server() server.instantiate() server.loop() - - -The new version is -#!/usr/bin/env python2 +","#!/usr/bin/env python2 # Giles: giles.py, the main loop. # Copyright 2012 Phil Bordelon # @@ -876,11 +906,12 @@ else: port = 9435 server.instantiate(port) server.loop() +",Support choosing a port on the command line.,"Support choosing a port on the command line. - -Write a commit message that summarizes the changes.",Support choosing a port on the command line. -"Here are the two versions of a code. The old version is -from flask import render_template +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 @@ -914,10 +945,7 @@ def _render_error_page(status_code): status_code = 500 template_data = main.config['BASE_TEMPLATE_DATA'] return render_template(template_map[status_code], **template_data), status_code - - -The new version is -from flask import render_template +","from flask import render_template from app.main import main @@ -955,11 +983,9 @@ def _render_error_page(status_code): status_code = 500 template_data = main.config['BASE_TEMPLATE_DATA'] return render_template(template_map[status_code], **template_data), status_code - - -Write a commit message that summarizes the changes.",Add print statements for all error types -"Here are the two versions of a code. The old version is -""""""install_ext +",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."""""" @@ -1002,10 +1028,7 @@ class install_ext (Command): outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt - - -The new version is -""""""install_ext +","""""""install_ext Implement the Distutils ""install_ext"" command to install extension modules."""""" @@ -1048,48 +1071,84 @@ class install_ext (Command): 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 -Write a commit message that summarizes the changes.","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." -"Here are the two versions of a code. The old version is +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) -The new version is -# This work was created by participants in the DataONE project, and is -# jointly copyrighted by participating institutions in DataONE. For -# more information on DataONE, see our web site at http://dataone.org. -# -# Copyright 2009-2019 DataONE -# -# 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. -""""""Support for type annotations in d1_common. + def __init__(self, name): + self.name = name + self.created_at = datetime.utcnow() -Types for DataONE objects are provided along with all the contents of Python's standard -``typing`` module. -"""""" + @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 -# noinspection PyUnresolvedReferences -from typing import * +from ..database import db +from ..date_tools import FHIR_datetime -D1Client = NewType(""D1Client"", Any) -AsyncD1Client = NewType(""AsyncD1Client"", Any) -Checksum = NewType(""Checksum"", Any) +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() -Write a commit message that summarizes the changes.",Add placeholder for adding type hinting using the new syntax in Python. -"Here are the two versions of a code. The old version is -from distutils.core import setup + @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', @@ -1099,10 +1158,7 @@ setup(name='q', version='2.3', py_modules=['q'], 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License' ]) - - -The new version is -from distutils.core import setup +","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', @@ -1112,145 +1168,109 @@ setup(name='q', version='2.4', py_modules=['q'], '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 = ...; -Write a commit message that summarizes the changes.",Advance PyPI version to 2.4. -"Here are the two versions of a code. The old version is -from rest_framework import serializers - -from grandchallenge.cases.models import Image, ImageFile - - -class ImageFileSerializer(serializers.ModelSerializer): - class Meta: - model = ImageFile - fields = (""pk"", ""image"", ""file"") - - -class ImageSerializer(serializers.ModelSerializer): - files = ImageFileSerializer(many=True, read_only=True) - - class Meta: - model = Image - fields = ( - ""pk"", - ""name"", - ""study"", - ""files"", - ""width"", - ""height"", - ""depth"", - ""color_space"", - ""modality"", - ""eye_choice"", - ""stereoscopic_choice"", - ""field_of_view"", - ""shape_without_color"", - ""shape"", - ) - - -The new version is -from rest_framework import serializers - -from grandchallenge.cases.models import Image, ImageFile - - -class ImageFileSerializer(serializers.ModelSerializer): - class Meta: - model = ImageFile - fields = (""pk"", ""image"", ""file"", ""image_type"") - - -class ImageSerializer(serializers.ModelSerializer): - files = ImageFileSerializer(many=True, read_only=True) - - class Meta: - model = Image - fields = ( - ""pk"", - ""name"", - ""study"", - ""files"", - ""width"", - ""height"", - ""depth"", - ""color_space"", - ""modality"", - ""eye_choice"", - ""stereoscopic_choice"", - ""field_of_view"", - ""shape_without_color"", - ""shape"", - ) - - -Write a commit message that summarizes the changes.",Return image type of file in api -"Here are the two versions of a code. The old version is -"""""" -MacroecoDesktop script for making standalone executable -"""""" - -from macroeco import desktop -desktop() +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. -The new version is +Status: progress has been made replacing these cases, but there is an +infinite number of such cases. """""" -MacroecoDesktop script for making standalone executable -"""""" - -import sys as _sys -from macroeco import desktop - -if len(_sys.argv) > 1: - desktop(_sys.argv[1]) -else: - desktop() - - -Write a commit message that summarizes the changes.",Allow compiled OS X app to take parameter file as input on command line -"Here are the two versions of a code. The old version is -from django.shortcuts import Http404 -from django.utils import translation - - -def handle_cms_response(response): - if response.status_code == 404: - raise Http404() - response.raise_for_status() - return response.json() - - -def get_language_from_querystring(request): - language_code = request.GET.get('lang') - language_codes = translation.trans_real.get_languages() - if language_code and language_code in language_codes: - return language_code - - -The new version is -from django.shortcuts import Http404 -from django.utils import translation +import _json, weakref -def handle_cms_response(response): - if response.status_code == 404: - raise Http404() - response.raise_for_status() - return response.json() +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 get_language_from_querystring(request): - language_code = request.GET.get('language') - language_codes = translation.trans_real.get_languages() - if language_code and language_code in language_codes: - return language_code - +def delete_me(*args): + print scanner.encoding.__dict__ -Write a commit message that summarizes the changes.",Use 'language' for query string instead of 'lang' -"Here are the two versions of a code. The old version is -# +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 # @@ -1285,10 +1305,7 @@ class GJSLint(Linter): selectors = { 'html': 'source.js.embedded.html' } - - -The new version is -# +","# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # @@ -1323,14 +1340,9 @@ class GJSLint(Linter): selectors = { 'html': 'source.js.embedded.html' } - - -Write a commit message that summarizes the changes.","Change 'language' to 'syntax', that is more precise terminology." -"Here are the two versions of a code. The old version is - - -The new version is -from nose.tools import * # noqa +","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 @@ -1366,107 +1378,62 @@ class TestUser(PMGTestCase): 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 -Write a commit message that summarizes the changes.",Add unit test for Soundcloud get_unstarted_query function -"Here are the two versions of a code. The old version is -import base64 -import cStringIO +application = create_app(os.getenv('FLASH_CONFIG') or 'development') +manager = Manager(application) -import requests +if __name__ == '__main__': + manager.run() +","#!/usr/bin/env python +import os +from app import create_app +from flask.ext.script import Manager, Server -class Camera(object): - def __init__(self, host): - self.host = host +application = create_app(os.getenv('FLASH_CONFIG') or 'development') +manager = Manager(application) +manager.add_command(""runserver"", Server(port=5001)) - def get_image(self): - """""" - Get an image from the camera. +if __name__ == '__main__': + manager.run() +",Update to run on port 5001,"Update to run on port 5001 - Returns image data as a StringIO object. - """""" - url = ""http://{}/image.jpg"".format(self.host) +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 - encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') +from setuptools import setup, find_packages - headers = { - 'Authorization': 'Basic ' + encoded - } +setup( + name='django-sensible-caching', - result = requests.get(url, headers=headers) - if result.ok: - return cStringIO.StringIO(result.content) + url=""https://chris-lamb.co.uk/projects/django-sensible-caching"", + version='2.0.1', + description=""Non-magical object caching for Django."", - else: - return None + author=""Chris Lamb"", + author_email=""chris@chris-lamb.co.uk"", + license=""BSD"", + packages=find_packages(), +) +","#!/usr/bin/env python -The new version is -import base64 +from setuptools import setup, find_packages -import requests -import six +setup( + name='django-sensible-caching', - -class Camera(object): - def __init__(self, host): - self.host = host - - def get_image(self): - """""" - Get an image from the camera. - - Returns image data as a BytesIO/StringIO object. - """""" - url = ""http://{}/image.jpg"".format(self.host) - - encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii') - - headers = { - 'Authorization': 'Basic ' + encoded - } - - result = requests.get(url, headers=headers) - if result.ok: - return six.BytesIO(result.content) - - else: - return None - - -Write a commit message that summarizes the changes.",Use six.BytesIO for Python3 compatibility -"Here are the two versions of a code. The old version is -#!/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(), -) - - -The new version is -#!/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."", + 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"", @@ -1478,11 +1445,9 @@ setup( 'Django>=1.8', ), ) - - -Write a commit message that summarizes the changes.",Update Django requirement to latest LTS -"Here are the two versions of a code. The old version is -import pytest +",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 @@ -1532,10 +1497,7 @@ def test_open(simbad): simbad.open(radius=10) url, = mock_open.call_args[0] assert 'file://' in url and 'html' in url - - -The new version is -import pytest +","import pytest import vcr try: from unittest import mock @@ -1585,11 +1547,9 @@ def test_open(simbad): simbad.open(radius=10) url, = mock_open.call_args[0] assert 'file://' in url and 'html' in url - - -Write a commit message that summarizes the changes.",Remove real database during testing -"Here are the two versions of a code. The old version is -from setuptools import setup, find_packages +",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', @@ -1620,10 +1580,7 @@ setup( ] }, ) - - -The new version is -from setuptools import setup, find_packages +","from setuptools import setup, find_packages setup( name='gdcdatamodel', @@ -1654,11 +1611,9 @@ setup( ] }, ) - - -Write a commit message that summarizes the changes.",Update pins for marvin release -"Here are the two versions of a code. The old version is -from django import forms +",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): @@ -1673,10 +1628,7 @@ class IndexForm(forms.Form): 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'})) - - -The new version is -from django import forms +","from django import forms class IndexForm(forms.Form): @@ -1695,11 +1647,9 @@ class IndexForm(forms.Form): 'database), then the line is left as is.', initial=r'\b\d{7,}\b', widget=forms.TextInput(attrs={'placeholder': r'\b\d{7,}\b'})) - - -Write a commit message that summarizes the changes.",Add help_text and required=False to the PIN field -"Here are the two versions of a code. The old version is -import os +",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 @@ -1726,10 +1676,7 @@ def docs(clean=False, browse=False): run(""sphinx-build %s %s"" % (docs_dir, build), pty=True) if browse: browse_docs.body() - - -The new version is -import os +","import os from invoke.tasks import task from invoke.runner import run @@ -1756,11 +1703,9 @@ def docs(clean=False, browse=False): run(""sphinx-build %s %s"" % (docs_dir, build), pty=True) if browse: browse_docs() - - -Write a commit message that summarizes the changes.",Leverage __call__ on task downstream -"Here are the two versions of a code. The old version is -from __future__ import absolute_import +",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 @@ -1782,10 +1727,7 @@ 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"") - - -The new version is -from __future__ import absolute_import +","from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals @@ -1807,11 +1749,9 @@ 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"") - - -Write a commit message that summarizes the changes.",Update example for architecture upload -"Here are the two versions of a code. The old version is -import tensorflow as tf +",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 @@ -1829,10 +1769,7 @@ def Exponential(lambda_, name=None): Distribution.integral = lambda lower, upper: cdf(upper) - cdf(lower) return X - - -The new version is -import tensorflow as tf +","import tensorflow as tf from .. import config from ..distribution import Distribution @@ -1850,70 +1787,69 @@ def Exponential(lambda_, name=None): 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') -Write a commit message that summarizes the changes.",Correct integral used for Exponential distributon -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', + default={'attrs': {'cols': 100, 'rows': 15}}) -# -# test a streaming app by dumping files from one directory -# into another, at a specified rate -# -# srcPath targetPath waitTime -# -# example: -# data/streaming_test.py /groups/ahrens/ahrenslab/Misha/forJeremy_SparkStreamingSample/ /nobackup/freeman/buffer/ 1 -# -import sys, os, time, glob; +class PageForm(FlatpageForm): + + class Meta: + model = FlatPage + widgets = { + 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), + } + -srcPath = str(sys.argv[1]) -targetPath = str(sys.argv[2]) -waitTime = float(sys.argv[3]) -files = glob.glob(srcPath+""*"") -count = 1 -for f in files: - cmd = ""scp "" + f + "" "" + targetPath - os.system(cmd) - print('writing file ' +str(count)) - count = count + 1 - time.sleep(waitTime) +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') -The new version is -#!/usr/bin/env python +FLATPAGE_WIDGET_KWARGS = getattr(settings, 'FLATPAGE_WIDGET_KWARGS', + {'attrs': {'cols': 100, 'rows': 15}}) -# -# test a streaming app by dumping files from one directory -# into another, at a specified rate -# -# srcPath targetPath waitTime -# -# example: -# data/streaming_test.py /groups/ahrens/ahrenslab/Misha/forJeremy_SparkStreamingSample/ /nobackup/freeman/buffer/ 1 -# -import sys, os, time, glob; +class PageForm(FlatpageForm): -srcPath = str(sys.argv[1]) -targetPath = str(sys.argv[2]) -waitTime = float(sys.argv[3]) -files = sorted(glob.glob(srcPath+""*""),key=os.path.getmtime) -count = 1 -for f in files: - cmd = ""scp "" + f + "" "" + targetPath - os.system(cmd) - print('writing file ' +str(count)) - count = count + 1 - time.sleep(waitTime) + class Meta: + model = FlatPage + widgets = { + 'content': import_string(FLATPAGE_WIDGET)(**FLATPAGE_WIDGET_KWARGS), + } +class PageAdmin(FlatPageAdmin): + """""" + Page Admin + """""" + form = PageForm -Write a commit message that summarizes the changes.",Sort files by modification date when testing streaming to preserve order -"Here are the two versions of a code. The old version is -from __future__ import unicode_literals +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 @@ -1950,10 +1886,7 @@ class ModelPublisher(Publisher): except ValueError as e: return http.BadRequest(str(e)) return self.render_single_object(obj, serialiser) - - -The new version is -from __future__ import unicode_literals +","from __future__ import unicode_literals from .. import http from ..shortcuts import get_object_or_404 @@ -1990,11 +1923,9 @@ class ModelPublisher(Publisher): except ValueError as e: return http.BadRequest(str(e)) return self.render_single_object(obj, serialiser) - - -Write a commit message that summarizes the changes.",Use our own get_object_or_404 for ModelPublisher.get_object -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +",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 @@ -2019,10 +1950,7 @@ def input_files(parsed_args): parsed = parsed_command_line() input_files(parsed) - - -The new version is -#!/usr/bin/env python +","#!/usr/bin/env python import argparse @@ -2062,32 +1990,22 @@ converters = {('plink_assoc','networkx'):plink_assoc_to_networkx} parsed = parsed_command_line() print "","".join([str(i) for i in input_files(parsed)]) - - -Write a commit message that summarizes the changes.",Add input file and converter abstraction -"Here are the two versions of a code. The old version is -from ckan.lib.base import BaseController +",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) - -The new version is -from ckan.lib.base import BaseController + super(QAController, self).__init(*args, **kwargs)","from ckan.lib.base import BaseController from pylons import config class QAController(BaseController): pass - - -Write a commit message that summarizes the changes.",Fix typo in constructor. Seems unnecessary anyway. -"Here are the two versions of a code. The old version is - - -The new version is -#!/usr/bin/env python +",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""); @@ -2175,14 +2093,17 @@ def main(): 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 -Write a commit message that summarizes the changes.",Add adhoc script to detect jobs with stuck ActiveInvocations list. -"Here are the two versions of a code. The old version is - - -The new version is -import thread_pool +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 @@ -2208,11 +2129,9 @@ class TestThreadPool(unittest.TestCase): pool.add(self._producer_thread, results) pool.add(self._consumer_thread, results) pool.join() - - -Write a commit message that summarizes the changes.",Add a unit-test for thread_pool.py. -"Here are the two versions of a code. The old version is -from django.core.management.base import BaseCommand, CommandError +",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 * @@ -2231,10 +2150,7 @@ class Command(BaseCommand): self.stdout.write(""Hit to quit."") wait = raw_input() - - -The new version is -from django.core.management.base import BaseCommand, CommandError +","from django.core.management.base import BaseCommand, CommandError from mqtt_logger.models import * import time @@ -2264,47 +2180,39 @@ class Command(BaseCommand): 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) -Write a commit message that summarizes the changes.",Make the listener automatically update the subscriptions. -"Here are the two versions of a code. The old version is -# -*- coding: utf-8 -*- -# Copyright (c) 2013-2014 Simon Jagoe -# All rights reserved. -# -# This software may be modified and distributed under the terms -# of the 3-clause BSD license. See the LICENSE.txt file for details. -import sys # pragma: no cover - -from .main import main # pragma: no cover - - -if __name__ == '__main__': - sys.exit(main()) - - -The new version is -# -*- coding: utf-8 -*- -# Copyright (c) 2013-2014 Simon Jagoe -# All rights reserved. -# -# This software may be modified and distributed under the terms -# of the 3-clause BSD license. See the LICENSE.txt file for details. -import sys # pragma: no cover - -from haas.main import main # pragma: no cover - - -if __name__ == '__main__': - sys.exit(main()) +@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 -Write a commit message that summarizes the changes.",Use absolute import for main entry point. -"Here are the two versions of a code. The old version is +app = Flask (__name__) +ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg']) +mail = Mail(app) +@app.route(""/"") +def index(): + return render_template('index.html.j2') -The new version is -#!/usr/bin/python +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 @@ -2375,14 +2283,11 @@ def main(argv): if __name__ == ""__main__"": main(sys.argv[1:]) +",Add selcet_gamma.py (authored by Amnon),"Add selcet_gamma.py (authored by Amnon) - -Write a commit message that summarizes the changes.",Add selcet_gamma.py (authored by Amnon) -"Here are the two versions of a code. The old version is - - -The new version is -"""""" +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. @@ -2422,11 +2327,9 @@ def GetPluginInfoW(info): def OpenW(info): print(""[open] "" + __file__) - - -Write a commit message that summarizes the changes.",Add 01autoguid/ plugin with own GUIDs autogenerated -"Here are the two versions of a code. The old version is -'''Virtual datasets: The 'Eiger' use case +",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 ''' @@ -2449,10 +2352,7 @@ for i, filename in enumerate(files): with h5py.File(""eiger_vds.h5"", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) - - -The new version is -'''Virtual datasets: The 'Eiger' use case +","'''Virtual datasets: The 'Eiger' use case https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf ''' @@ -2475,11 +2375,9 @@ for i, filename in enumerate(files): with h5py.File(""eiger_vds.h5"", 'w', libver='latest') as f: f.create_virtual_dataset('data', layout, fillvalue=0) - - -Write a commit message that summarizes the changes.",Fix layout for Eiger example -"Here are the two versions of a code. The old version is -import sys +",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) @@ -2540,10 +2438,7 @@ class ClustoTestBase(unittest.TestCase): return self._testresult - - -The new version is -import sys +","import sys import os sys.path.insert(0, os.curdir) @@ -2605,11 +2500,9 @@ class ClustoTestBase(unittest.TestCase): return self._testresult - - -Write a commit message that summarizes the changes.",Enable versioning during unit tests -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +",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 @@ -2637,10 +2530,7 @@ def opacity_test(tol=1.e-10): if __name__ == '__main__': opacity_test() - - -The new version is -#!/usr/bin/env python +","#!/usr/bin/env python """""" Created on Thu 6 March 2014 @@ -2669,11 +2559,9 @@ def opacity_test(tol=1.e-10): if __name__ == '__main__': opacity_test() - - -Write a commit message that summarizes the changes.",Fix test to take care of units. -"Here are the two versions of a code. The old version is -# Copyright Hybrid Logic Ltd. See LICENSE file for details. +",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 -*- """""" @@ -2694,10 +2582,7 @@ class Deployment(object): """""" Stop and disable the application. """""" - - -The new version is -# Copyright Hybrid Logic Ltd. See LICENSE file for details. +","# Copyright Hybrid Logic Ltd. See LICENSE file for details. # -*- test-case-name: flocker.node.test.test_deploy -*- """""" @@ -2727,51 +2612,75 @@ class Deployment(object): """""" 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."""""" -Write a commit message that summarizes the changes.",Allow a fake gear client to be supplied -"Here are the two versions of a code. The old version is -from flask import Flask -from config import config - -def create_app(config_name): - app = Flask(__name__) - app.config.from_object(config[config_name]) - - from .aflafrettir import aflafrettir as afla_blueprint - app.register_blueprint(afla_blueprint) - - return app - - -The new version is -from flask import Flask -from flask.ext.bootstrap import Bootstrap - -from config import config - -bootstrap = Bootstrap() - -def create_app(config_name): - app = Flask(__name__) - app.config.from_object(config[config_name]) +import argparse +import pathlib - bootstrap.init_app(app) +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) - from .aflafrettir import aflafrettir as afla_blueprint - app.register_blueprint(afla_blueprint) +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. - return app +""""""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) -Write a commit message that summarizes the changes.",Add flask-bootstrap to the mix -"Here are the two versions of a code. The old version is -class FeedForwardNet: +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 - - -The new version is -from layers import InputLayer, Layer, OutputLayer +","from layers import InputLayer, Layer, OutputLayer import math import random @@ -2857,11 +2766,11 @@ 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 - -Write a commit message that summarizes the changes.",Add main code and feed forward net class -"Here are the two versions of a code. The old version is -from django.conf.urls.defaults import patterns +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', @@ -2891,10 +2800,7 @@ urlpatterns += patterns('django.contrib.auth.views', (r'^profile/change_password/done/$', 'password_change_done', {'template_name': 'accounts/change_password_done.html'}), ) - - -The new version is -from django.conf.urls.defaults import patterns +","from django.conf.urls.defaults import patterns from metashare.settings import DJANGO_BASE urlpatterns = patterns('metashare.accounts.views', @@ -2922,11 +2828,9 @@ urlpatterns += patterns('django.contrib.auth.views', (r'^profile/change_password/done/$', 'password_change_done', {'template_name': 'accounts/change_password_done.html'}), ) - - -Write a commit message that summarizes the changes.",Manage default editor group on a single page -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +",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 @@ -2944,10 +2848,7 @@ if __name__ == '__main__': app.run(debug=debug, host='0.0.0.0') else: app.run(debug=debug) - - -The new version is -#!/usr/bin/env python +","#!/usr/bin/env python from mcapi.mcapp import app from mcapi import tservices, public, utils, private, access, process, machine, template, tservices @@ -2966,14 +2867,9 @@ if __name__ == '__main__': debug = False app.run(debug=debug, host=_HOST, port=int(_PORT)) - - -Write a commit message that summarizes the changes.",Allow host and port that the service listens on to be set from environment variables. -"Here are the two versions of a code. The old version is - - -The new version is -from rest_framework import status +",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 @@ -3015,38 +2911,46 @@ class BouncerTests(APITestCase): 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 -Write a commit message that summarizes the changes.",Add request bouncer test cases -"Here are the two versions of a code. The old version is -from django.core.management.base import BaseCommand +def sync_daily_email_blasts(blast): + for l in blast.recipients_lists.all(): + l.send(blast) -from boilerroomtv.tasks import scrape_genres, scrape_all_recordings, scrape_channels +def sync_recipients_list(recipients_list, blast): + for r in recipients_list.recipientss.all(): + r.send(recipients_list, blast) -class Command(BaseCommand): - def handle(self, *args, **options): - scrape_genres() - scrape_all_recordings() - scrape_channels() +def sync_recipient(recipient, recipients_list, blast): + email.send_email(blast.render(recipient, recipients_list)) +","from .. import email -The new version is -from django.core.management.base import BaseCommand -from ...tasks import scrape_genres, scrape_all_recordings, scrape_channels +def sync_daily_email_blasts(blast): + for l in blast.recipients_lists.all(): + l.send(blast) -class Command(BaseCommand): - def handle(self, *args, **options): - scrape_genres() - scrape_all_recordings() - scrape_channels() +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 -Write a commit message that summarizes the changes.",Use relative import in command. -"Here are the two versions of a code. The old version is -from flask import Flask, render_template +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(""/"") @@ -3059,10 +2963,7 @@ def fdc_report_page(): if __name__ == ""__main__"": app.run(debug=True) - - -The new version is -import os +","import os import sys from flask import Flask, render_template, request @@ -3085,28 +2986,69 @@ def fdc_report_page(): 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 -Write a commit message that summarizes the changes.",Add imports for Wm_metrics module -"Here are the two versions of a code. The old version is - - -The new version is -#!/usr/bin/env python - -fh = open('/home/ben/dump.txt', 'w') -import sys -for ln in sys.stdin: - print >> fh, ""here"" - print >> fh, ln -print >> fh, ""input closed"" -fh.close() - +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 -Write a commit message that summarizes the changes.",Test for lisp external-program functionality -"Here are the two versions of a code. The old version is -import json + 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 @@ -3148,10 +3090,7 @@ def test_profile_schedules_setter(): mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1, data='schedules[0][times][]=mo&') - - -The new version is -import json +","import json from nose.tools import eq_, raises from mock import MagicMock, patch @@ -3206,140 +3145,102 @@ def test_profile_updates(): 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 -Write a commit message that summarizes the changes.",Test profile's relationship with updates -"Here are the two versions of a code. The old version is -from __future__ import absolute_import, division, print_function - -from ..utils import identity, alias -from .scale import scale_discrete, scale_continuous +RESTART_PREVENTING_EXCEPTIONS = frozenset( + (os.EX_CONFIG, os.EX_USAGE, os.EX_UNAVAILABLE) +) -class scale_color_identity(scale_discrete): - aesthetics = ['color'] - palette = staticmethod(identity) +class HadesSetupError(Exception): + preferred_exit_code = os.EX_UNAVAILABLE + def __init__(self, *args, logger: t.Optional[Logger] = None): + super().__init__(*args) + self.logger = logger -class scale_fill_identity(scale_color_identity): - aesthetics = ['fill'] + 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 scale_shape_identity(scale_discrete): - aesthetics = ['shape'] - palette = staticmethod(identity) +class HadesUsageError(HadesSetupError): + preferred_exit_code = os.EX_USAGE -class scale_linetype_identity(scale_discrete): - aesthetics = ['linetype'] - palette = staticmethod(identity) + def __init__(self, *a, **kw): + super().__init__(*a, **kw) -class scale_alpha_identity(scale_continuous): - aesthetics = ['alpha'] - palette = staticmethod(identity) +@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) -class scale_size_identity(scale_continuous): - aesthetics = ['size'] - palette = staticmethod(identity) +F = t.TypeVar(""F"", bound=t.Callable[..., t.Any]) -# American to British spelling -alias('scale_colour_identity', scale_color_identity) +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) -The new version is -from __future__ import absolute_import, division, print_function + 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 -from ..utils import identity, alias -from .scale import scale_discrete, scale_continuous +urlpatterns = [ + url(r'^admin_tools/', include('admin_tools.urls')), + url(r'^admin/', include(admin.site.urls)), -class MapTrainMixin(object): - """""" - Override map and train methods - """""" - def map(self, x): - return x + # Simply show the master template. + url(r'^$', TemplateView.as_view(template_name='demo.html')), +] - def train(self, x): - # do nothing if no guide, - # otherwise train so we know what breaks to use - if self.guide is None: - return - - return super(MapTrainMixin, self).train(x) - - -class scale_color_identity(MapTrainMixin, scale_discrete): - aesthetics = ['color'] - palette = staticmethod(identity) - guide = None - - -class scale_fill_identity(scale_color_identity): - aesthetics = ['fill'] - - -class scale_shape_identity(MapTrainMixin, scale_discrete): - aesthetics = ['shape'] - palette = staticmethod(identity) - guide = None - - -class scale_linetype_identity(MapTrainMixin, scale_discrete): - aesthetics = ['linetype'] - palette = staticmethod(identity) - guide = None - - -class scale_alpha_identity(MapTrainMixin, scale_continuous): - aesthetics = ['alpha'] - palette = staticmethod(identity) - guide = None - - -class scale_size_identity(MapTrainMixin, scale_continuous): - aesthetics = ['size'] - palette = staticmethod(identity) - guide = None - - -# American to British spelling -alias('scale_colour_identity', scale_color_identity) - - -Write a commit message that summarizes the changes.","Fix identity scales, override map & train methods" -"Here are the two versions of a code. The old version is -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) - - -The new version is -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 +# 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 = [ @@ -3359,11 +3260,9 @@ if settings.DEBUG: urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ] - - -Write a commit message that summarizes the changes.",Add missing configuration for DjDT -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +",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 @@ -3380,10 +3279,7 @@ Write a commit message that summarizes the changes.",Add missing configuration f # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - - -The new version is -#!/usr/bin/env python +","#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2011 Yesudeep Mangalapilly @@ -3412,71 +3308,65 @@ else: import unittest skipIfNtMove = unittest.skipIf(OS_NAME == 'nt', ""windows can not detect moves"") - - -Write a commit message that summarizes the changes.",Declare unittest lib used within python version -"Here are the two versions of a code. The old version is -from os.path import dirname, join -TEST_ROOT = dirname(__file__) - -INSTALLED_APPS = ('adminfiles', 'tests', - 'django.contrib.contenttypes', - 'django.contrib.admin', - 'django.contrib.sites', - 'django.contrib.auth', - 'django.contrib.sessions', - 'sorl.thumbnail') -DATABASE_ENGINE = 'sqlite3' - -SITE_ID = 1 - -MEDIA_URL = '/media/' -MEDIA_ROOT = join(TEST_ROOT, 'media') - -STATIC_URL = '/static/' -STATIC_ROOT = MEDIA_ROOT - -ROOT_URLCONF = 'tests.urls' - -TEMPLATE_DIRS = (join(TEST_ROOT, 'templates'),) - - -The new version is -from os.path import dirname, join -TEST_ROOT = dirname(__file__) - -INSTALLED_APPS = ('adminfiles', 'tests', - 'django.contrib.contenttypes', - 'django.contrib.admin', - 'django.contrib.sites', - 'django.contrib.auth', - 'django.contrib.sessions', - 'sorl.thumbnail') -DATABASES = { - ""default"": { - ""ENGINE"": 'django.db.backends.sqlite3', - } -} - -SITE_ID = 1 - -MEDIA_URL = '/media/' -MEDIA_ROOT = join(TEST_ROOT, 'media') - -STATIC_URL = '/static/' -STATIC_ROOT = MEDIA_ROOT - -ROOT_URLCONF = 'tests.urls' - -TEMPLATE_DIRS = (join(TEST_ROOT, 'templates'),) - - -Write a commit message that summarizes the changes.",Fix deprecation warning: DATABASE_* -> DATABASES -"Here are the two versions of a code. The old version is - - -The new version is -import csv +",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 @@ -3524,100 +3414,66 @@ class CsvExportAdminMixin(DjangoObjectActions): 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 -Write a commit message that summarizes the changes.",Add django admin mixin for exporting csvs -"Here are the two versions of a code. The old version is - - -The new version is -import unittest -from steam import vdf - -class SyntaxTestCase(unittest.TestCase): - UNQUOTED_VDF = """""" - node - { - key value - } - """""" - - QUOTED_VDF = """""" - ""node"" - { - ""key"" ""value"" - } - """""" - - MACRO_UNQUOTED_VDF = """""" - node - { - key value [$MACRO] - } - """""" - - MACRO_QUOTED_VDF = """""" - ""node"" - { - ""key"" ""value"" [$MACRO] - } - """""" - - MIXED_VDF = """""" - node - { - ""key"" value - key2 ""value"" - ""key3"" ""value"" [$MACRO] - - // Comment - ""subnode"" [$MACRO] - { - key value - } - } - """""" - - EXPECTED_DICT = { - u""node"": { - u""key"": u""value"" - } - } +if platform_name() == 'windows': + from .windows import * +else: + from .posix import * - EXPECTED_MIXED_DICT = { - u""node"": { - u""key"": u""value"", - u""key2"": u""value"", - u""key3"": u""value"", - u""subnode"": { - u""key"": u""value"" - } - } - } -class DeserializeTestCase(SyntaxTestCase): - def test_unquoted(self): - self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.UNQUOTED_VDF)) +class shell_list(list): + """"""A special subclass of list used to mark that this command line uses + special shell characters."""""" + pass - def test_quoted(self): - self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.QUOTED_VDF)) - def test_macro_unquoted(self): - self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.MACRO_UNQUOTED_VDF)) +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 - def test_macro_quoted(self): - self.assertEqual(self.EXPECTED_DICT, vdf.loads(self.MACRO_QUOTED_VDF)) +from ..platform_name import platform_name - def test_mixed(self): - self.assertEqual(self.EXPECTED_MIXED_DICT, vdf.loads(self.MIXED_VDF)) +if platform_name() == 'windows': + from .windows import * +else: + from .posix import * -Write a commit message that summarizes the changes.",Add initial vdf test fixture -"Here are the two versions of a code. The old version is +class shell_list(list): + """"""A special subclass of list used to mark that this command line uses + special shell characters."""""" + pass -The new version is -# pylint: disable=C0103,C0111 +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 @@ -3669,109 +3525,94 @@ class TestMemoryModule(unittest.TestCase): 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' -Write a commit message that summarizes the changes.",Add unit tests for memory module -"Here are the two versions of a code. The old version is -# Copyright (c) 2013 Mirantis Inc. -# -# Licensed under the Apache License, Version 2.0 (the ""License""); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an ""AS IS"" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -import eventlet -eventlet.monkey_patch() -import gettext -import sys - -from oslo_config import cfg -from oslo_service import service - -gettext.install('blazar') - -from blazar.db import api as db_api -from blazar.manager import service as manager_service -from blazar.notification import notifier -from blazar.utils import service as service_utils +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 main(): - cfg.CONF(project='blazar', prog='blazar-manager') - service_utils.prepare_service(sys.argv) - db_api.setup_db() - notifier.init() - service.launch( - cfg.CONF, - manager_service.ManagerService() - ).wait() +def unix_timestamp(d=None): + if d is None: + d = timezone.now() + return calendar.timegm(d.utctimetuple()) + else: + return calendar.timegm(d.timetuple()) -if __name__ == '__main__': - main() +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) -The new version is -# Copyright (c) 2013 Mirantis Inc. -# -# Licensed under the Apache License, Version 2.0 (the ""License""); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an ""AS IS"" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or -# implied. -# See the License for the specific language governing permissions and -# limitations under the License. + return obj1 == obj2 +","from datetime import datetime +from django.utils import timezone +import calendar +import pytz -import eventlet -eventlet.monkey_patch() +DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S' +DATE_FORMAT = '%Y-%m-%d' -import gettext -import sys -from oslo_config import cfg -from oslo_service import service +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') -gettext.install('blazar') -from blazar.db import api as db_api -from blazar.manager import service as manager_service -from blazar.notification import notifier -from blazar.utils import service as service_utils +def unix_timestamp(d=None): + if d is None: + d = timezone.now() + return calendar.timegm(d.utctimetuple()) + else: + return calendar.timegm(d.timetuple()) -def main(): - cfg.CONF(project='blazar', prog='blazar-manager') - service_utils.prepare_service(sys.argv) - db_api.setup_db() - notifier.init() - service.launch( - cfg.CONF, - manager_service.ManagerService(), - restart_method='mutate' - ).wait() +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) -if __name__ == '__main__': - main() + return obj1 == obj2 -Write a commit message that summarizes the changes.",Enable mutable config in blazar -"Here are the two versions of a code. The old version is -from troposphere import ( +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, ) @@ -3805,10 +3646,7 @@ VPCGatewayAttachment( VpcId=Ref(vpc), InternetGatewayId=Ref(internet_gateway), ) - - -The new version is -from troposphere import ( +","from troposphere import ( Ref, ) @@ -3861,14 +3699,9 @@ public_route = Route( DestinationCidrBlock=""0.0.0.0/0"", RouteTableId=Ref(public_route_table), ) - - -Write a commit message that summarizes the changes.",Add a public route table -"Here are the two versions of a code. The old version is - - -The new version is -''' +",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 @@ -3938,61 +3771,46 @@ if __name__ == '__main__': ""jacques_no_billi_generic_scattering_"") w.add(main_task) w.run() - - -Write a commit message that summarizes the changes.",Add little script calculate sample spectra. -"Here are the two versions of a code. The old version is -from django.db import models - - -class AdminProfile(models.Model): - - user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') - - desk_token = models.CharField(max_length=45, blank=True) - desk_token_secret = models.CharField(max_length=45, blank=True) - - class Meta: - # custom permissions for use in the OSF Admin App - permissions = ( - ('mark_spam', 'Can mark comments, projects and registrations as spam'), - ('view_spam', 'Can view nodes, comments, and projects marked as spam'), - ('view_metrics', 'Can view metrics on the OSF Admin app'), - ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), - ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), - ('view_desk', 'Can view details about Desk users'), - ) - - -The new version is -from django.db import models - - -class AdminProfile(models.Model): - - user = models.OneToOneField('osf.OSFUser', related_name='admin_profile') - - desk_token = models.CharField(max_length=45, blank=True) - desk_token_secret = models.CharField(max_length=45, blank=True) - - def __unicode__(self): - return self.user.username - - class Meta: - # custom permissions for use in the OSF Admin App - permissions = ( - ('mark_spam', 'Can mark comments, projects and registrations as spam'), - ('view_spam', 'Can view nodes, comments, and projects marked as spam'), - ('view_metrics', 'Can view metrics on the OSF Admin app'), - ('view_prereg', 'Can view entries for the preregistration chellenge on the admin'), - ('administer_prereg', 'Can update, comment on, and approve entries to the prereg challenge'), - ('view_desk', 'Can view details about Desk users'), - ) - - -Write a commit message that summarizes the changes.",Fix the display name of admin profile in the admin admin -"Here are the two versions of a code. The old version is -import threading +",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 @@ -4047,10 +3865,7 @@ class ControlServerTest(unittest.TestCase): @classmethod def tearDownClass(cls): cls.server.shutdown() - - -The new version is -import mock +","import mock import threading import unittest @@ -4100,135 +3915,103 @@ class ControlServerTest(unittest.TestCase): @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 -Write a commit message that summarizes the changes.",Make it work in PY3.5 *properly* -"Here are the two versions of a code. The old version is -from models.basemodel import BaseModel -from peewee import CharField, DateTimeField - -ALLOWED_VERDICTS = ( - 'NOT_AN_EXPL', - 'VIOLATION', - 'NOT_IMPRESSED', - 'GOOD', - 'EXACT', -) - - -class ScoreFeedback(BaseModel): - verdict = CharField(10, choices=ALLOWED_VERDICTS) - timestamp = DateTimeField() - expl_key = CharField(50) - - -The new version is -from models.basemodel import BaseModel -from peewee import CharField, DateTimeField - -ALLOWED_VERDICTS = ( - 'NOT_AN_EXPL', - 'VIOLATION', - 'NOT_IMPRESSED', - 'GOOD', - 'EXACT', -) - - -class ScoreFeedback(BaseModel): - verdict = CharField(20, choices=ALLOWED_VERDICTS) - timestamp = DateTimeField() - expl_key = CharField(50) - +LOG = logging.getLogger(__name__) -Write a commit message that summarizes the changes.",Fix verdict field max length -"Here are the two versions of a code. The old version is -#!/usr/bin/env python -import os -import sys -import requests -import re -from bot import RandomBot +class CheckDatabaseStatus(BaseStep): -SERVER_HOST = 'http://localhost:9000' - -trainingState = requests.post(SERVER_HOST + '/api/training/alone').json() -state = trainingState + def __unicode__(self): + return ""Checking database status..."" -bot = RandomBot() + def do(self, workflow_dict): + try: + if not 'database' in workflow_dict: + return False -def move(url, direction): - r = requests.post(url, {'dir': direction}) - return r.json() + if not 'databaseinfra' in workflow_dict: + workflow_dict['databaseinfra'] = workflow_dict[ + 'database'].databaseinfra -def start(server_url): - def play(state): - if (state['game']['finished']): - print('game finished') - else: - url = state['playUrl'] - direction = bot.move(state) - newState = move(state['playUrl'], direction) - play(newState) + LOG.info(""Getting driver class"") + driver = workflow_dict['databaseinfra'].get_driver() + from time import sleep - print(""Start: "" + state['viewUrl']) - play(state) + sleep(60) -if __name__ == ""__main__"": - if (len(sys.argv) > 1): - SERVER_HOST = sys.argv[1] - start(sys.argv[1]) - else: - print('Specify the server, ex: ""http://localhost:9000""') + 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 -The new version is -#!/usr/bin/env python + def undo(self, workflow_dict): + LOG.info(""Nothing to do here..."") + return True +","# -*- coding: utf-8 -*- +import logging +from ...util.base import BaseStep -import os -import sys -import requests -import re -from bot import RandomBot +LOG = logging.getLogger(__name__) -SERVER_HOST = 'http://localhost:9000' -trainingState = requests.post(SERVER_HOST + '/api/training/alone').json() -state = trainingState +class CheckDatabaseStatus(BaseStep): -bot = RandomBot() + def __unicode__(self): + return ""Checking database status..."" -def move(url, direction): - r = requests.post(url, {'dir': direction}) - return r.json() + def do(self, workflow_dict): + try: + if 'database' not in workflow_dict: + return False -def start(server_url): - def play(state): - if (state['game']['finished']): - print('game finished') - else: - url = state['playUrl'] - direction = bot.move(state) - newState = move(state['playUrl'], direction) + if 'databaseinfra' not in workflow_dict: + workflow_dict['databaseinfra'] = workflow_dict[ + 'database'].databaseinfra - print(""Playing turn %d with direction %s"" % (state['game']['turn'], direction)) - play(newState) + LOG.info(""Getting driver class"") + driver = workflow_dict['databaseinfra'].get_driver() + from time import sleep - print(""Start: "" + state['viewUrl']) - play(state) + sleep(60) -if __name__ == ""__main__"": - if (len(sys.argv) > 1): - SERVER_HOST = sys.argv[1] - start(sys.argv[1]) - else: - print('Specify the server, ex: ""http://localhost:9000""') + 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 -Write a commit message that summarizes the changes.",Add some debug when playing -"Here are the two versions of a code. The old version is -from setuptools import setup + 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: @@ -4259,10 +4042,7 @@ setup(name='shellvars-py', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) - - -The new version is -from setuptools import setup +","from setuptools import setup def read(f): try: @@ -4294,82 +4074,31 @@ setup(name='shellvars-py', 'Topic :: Software Development :: Libraries :: Python Modules' ] ) - - -Write a commit message that summarizes the changes.",Add POSIX as supported OS type -"Here are the two versions of a code. The old version is -#!/usr/bin/env python -# -*- coding: utf-8 -*- - - -"""""" - Alignak REST backend client library - - This module is a Python library used the REST API of the Alignak backend -"""""" -# Application version and manifest -VERSION = (0, 5, 1) - -__application__ = u""Alignak Backend client"" -__short_version__ = '.'.join((str(each) for each in VERSION[:2])) -__version__ = '.'.join((str(each) for each in VERSION[:4])) -__author__ = u""Alignak team"" -__copyright__ = u""(c) 2015-2016 - %s"" % __author__ -__license__ = u""GNU Affero General Public License, version 3"" -__description__ = u""Alignak backend client library"" -__releasenotes__ = u""""""Alignak backend client library"""""" -__doc_url__ = ""https://github.com/Alignak-monitoring-contrib/alignak-backend-client"" -# Application manifest -manifest = { - 'name': __application__, - 'version': __version__, - 'author': __author__, - 'description': __description__, - 'copyright': __copyright__, - 'license': __license__, - 'release': __releasenotes__, - 'doc': __doc_url__ -} - - -The new version is -#!/usr/bin/env python -# -*- coding: utf-8 -*- - - -"""""" - Alignak REST backend client library - - This module is a Python library used the REST API of the Alignak backend -"""""" -# Application version and manifest -VERSION = (0, 5, 2) - -__application__ = u""Alignak Backend client"" -__short_version__ = '.'.join((str(each) for each in VERSION[:2])) -__version__ = '.'.join((str(each) for each in VERSION[:4])) -__author__ = u""Alignak team"" -__copyright__ = u""(c) 2015-2016 - %s"" % __author__ -__license__ = u""GNU Affero General Public License, version 3"" -__description__ = u""Alignak backend client library"" -__releasenotes__ = u""""""Alignak backend client library"""""" -__doc_url__ = ""https://github.com/Alignak-monitoring-contrib/alignak-backend-client"" -# Application manifest -manifest = { - 'name': __application__, - 'version': __version__, - 'author': __author__, - 'description': __description__, - 'copyright': __copyright__, - 'license': __license__, - 'release': __releasenotes__, - 'doc': __doc_url__ -} - - -Write a commit message that summarizes the changes.",Set version to 0.5.2 to publish on Pypi -"Here are the two versions of a code. The old version is -import sys +",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 @@ -4413,10 +4142,7 @@ test_runner = TestRunner() failures = test_runner.run_tests([APP_NAME]) if failures: sys.exit(failures) - - -The new version is -import sys +","import sys import django from django.conf import settings @@ -4460,203 +4186,196 @@ 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 -Write a commit message that summarizes the changes.",Disable impersonation logging during testing -"Here are the two versions of a code. The old version is -import scipy as sp -import matplotlib.pyplot as plt -from mpl_toolkits.mplot3d import Axes3D - - -The new version is -from __future__ import division -from __future__ import absolute_import - -import scipy as sp -import itertools as it -import functools as ft -import operator as op -import sys -import sympy - - -# Plotting -import matplotlib.pyplot as plt -from mpl_toolkits.mplot3d import Axes3D -from matplotlib.pyplot import subplots -from matplotlib.pyplot import show as pltshow - +from . import models -# and import some common functions into the global namespace -from scipy.linalg import norm -from scipy import sin, cos, tan, log, pi, sqrt, exp, mean -from math import atan2, acos -from sympy import Rational as sRat -from sympy import pretty as spretty - - -Write a commit message that summarizes the changes.",Add lots of useful default imports to ipython -"Here are the two versions of a code. The old version is - - -class ENotifer(object): - def notify(self, notification): - notification.notifier = notification.notifier or self - for listener in self._eternal_listener + self.listeners: - listener.notifyChanged(notification) - - -def enum(enumName, *listValueNames): - """"""Clever implementation of an enum like in python - - Shameless copy from: http://sametmax.com/faire-des-enums-en-python/ - """""" - listValueNumbers = range(len(listValueNames)) - dictAttrib = dict(zip(listValueNames, listValueNumbers)) - dictReverse = dict(zip(listValueNumbers, listValueNames)) - dictAttrib[""dictReverse""] = dictReverse - mainType = type(enumName, (), dictAttrib) - return mainType - - -Kind = enum('Kind', - 'ADD', - 'ADD_MANY', - 'MOVE', - 'REMOVE', - 'REMOVE_MANY', - 'SET', - 'UNSET') - - -class Notification(object): - def __init__(self, notifier=None, kind=None, old=None, new=None, - feature=None): - self.notifier = notifier - self.kind = kind - self.old = old - self.new = new - self.feature = feature - - def __repr__(self): - return ('[{0}] old={1} new={2} obj={3} #{4}' - .format(Kind.dictReverse[self.kind], - self.old, - self.new, - self.notifier, - self.feature)) +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), + } -class EObserver(object): - def __init__(self, notifier=None, notifyChanged=None): - if notifier: - notifier.listeners.append(self) - if notifyChanged: - self.notifyChanged = notifyChanged + def title(self, image): + return image.title - def observe(self, notifier): - notifier.listeners.append(self) + def description(self, image): + return str(image) - def notifyChanged(self, notification): - pass +admin.site.register(models.Image, ImageAdmin) +","from django.contrib import admin +from icekit.utils.admin.mixins import ThumbnailAdminMixin -The new version is -from enum import Enum, unique +from . import models -class ENotifer(object): - def notify(self, notification): - notification.notifier = notification.notifier or self - for listener in self._eternal_listener + self.listeners: - listener.notifyChanged(notification) +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) -@unique -class Kind(Enum): - ADD = 0 - ADD_MANY = 1 - MOVE = 2 - REMOVE = 3 - REMOVE_MANY = 4 - SET = 5 - UNSET = 6 +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 -class Notification(object): - def __init__(self, notifier=None, kind=None, old=None, new=None, - feature=None): - self.notifier = notifier - self.kind = kind - self.old = old - self.new = new - self.feature = feature +import pytest - def __repr__(self): - return ('[{0}] old={1} new={2} obj={3} #{4}' - .format(self.kind.name, - self.old, - self.new, - self.notifier, - self.feature)) +if sys.version_info < (3, 4): + print(""Requires Python 3.4+"") + sys.exit(1) -class EObserver(object): - def __init__(self, notifier=None, notifyChanged=None): - if notifier: - notifier.listeners.append(self) - if notifyChanged: - self.notifyChanged = notifyChanged +TESTS_ROOT = os.path.abspath(os.path.dirname(__file__)) +PROJECT_ROOT = os.path.dirname(TESTS_ROOT) - def observe(self, notifier): - notifier.listeners.append(self) - def notifyChanged(self, notification): - pass +@pytest.fixture(scope=""session"") +def resources(): + return Path(TESTS_ROOT) / 'resources' -Write a commit message that summarizes the changes.",Add better enumeration for Notification -"Here are the two versions of a code. The old version is -from django.shortcuts import redirect -from django.contrib.auth import logout as auth_logout -from django.conf import settings +@pytest.fixture(scope=""function"") +def outdir(tmp_path): + return tmp_path -def logout(request): - """"""Logs out user redirects if in request"""""" - r = request.GET.get('r', '') - auth_logout(request) +@pytest.fixture(scope=""function"") +def outpdf(tmp_path): + return tmp_path / 'out.pdf' +","import os +import sys +from pathlib import Path - if r: - return redirect('{}/?r={}'.format(settings.OPENSTAX_ACCOUNTS_LOGOUT_URL, r)) - else: - return redirect(settings.OPENSTAX_ACCOUNTS_LOGOUT_URL) +import pytest +if sys.version_info < (3, 6): + print(""Requires Python 3.6+"") + sys.exit(1) -The new version is -from django.shortcuts import redirect -from django.contrib.auth import logout as auth_logout -from django.conf import settings +TESTS_ROOT = os.path.abspath(os.path.dirname(__file__)) +PROJECT_ROOT = os.path.dirname(TESTS_ROOT) -def logout(request): - """"""Logs out user redirects if in request"""""" - next = request.GET.get('next', '') - auth_logout(request) - if next: - return redirect('{}/?next={}'.format(settings.OPENSTAX_ACCOUNTS_LOGOUT_URL, next)) - else: - return redirect(settings.OPENSTAX_ACCOUNTS_LOGOUT_URL) +@pytest.fixture(scope=""session"") +def resources(): + return Path(TESTS_ROOT) / 'resources' -Write a commit message that summarizes the changes.",Change variable name to next for logout function -"Here are the two versions of a code. The old version is +@pytest.fixture(scope=""function"") +def outdir(tmp_path): + return tmp_path -The new version is -import pytest +@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 @@ -4664,13 +4383,11 @@ from cutadapt.__main__ import main def test_help(): with pytest.raises(SystemExit) as e: main([""--help""]) - assert e.value.args[0] == 0 - - + assert e.value.args[0] == 0 -Write a commit message that summarizes the changes.",Add a test for __main__ -"Here are the two versions of a code. The old version is -from pupa.scrape import Jurisdiction +",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 @@ -4708,10 +4425,7 @@ class Example(Jurisdiction): def scrape_session_list(self): return ['2013'] - - -The new version is -from pupa.scrape import Jurisdiction +","from pupa.scrape import Jurisdiction from .people import PersonScraper @@ -4749,88 +4463,72 @@ class Example(Jurisdiction): 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 -Write a commit message that summarizes the changes.",Substitute a more realistic jurisdiction_id -"Here are the two versions of a code. The old version is -# -# This sets up how models are displayed -# in the web admin interface. -# -from django.contrib import admin -from src.comms.models import ChannelDB - - -class MsgAdmin(admin.ModelAdmin): - list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', - 'db_channels', 'db_message', 'db_lock_storage') - list_display_links = (""id"",) - ordering = [""db_date_sent"", 'db_sender', 'db_receivers', 'db_channels'] - #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] - search_fields = ['id', '^db_date_sent', '^db_message'] - save_as = True - save_on_top = True - list_select_related = True -#admin.site.register(Msg, MsgAdmin) - - -class ChannelAdmin(admin.ModelAdmin): - list_display = ('id', 'db_key', 'db_lock_storage', ""db_subscriptions"") - list_display_links = (""id"", 'db_key') - ordering = [""db_key""] - search_fields = ['id', 'db_key', 'db_aliases'] - save_as = True - save_on_top = True - list_select_related = True - fieldsets = ( - (None, {'fields': (('db_key',), 'db_lock_storage')}), +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 -admin.site.register(ChannelDB, ChannelAdmin) +shells_admin = ShellsAdmin() -The new version is -# -# This sets up how models are displayed -# in the web admin interface. -# +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'), -from django.contrib import admin -from src.comms.models import ChannelDB - - -class MsgAdmin(admin.ModelAdmin): - list_display = ('id', 'db_date_sent', 'db_sender', 'db_receivers', - 'db_channels', 'db_message', 'db_lock_storage') - list_display_links = (""id"",) - ordering = [""db_date_sent"", 'db_sender', 'db_receivers', 'db_channels'] - #readonly_fields = ['db_message', 'db_sender', 'db_receivers', 'db_channels'] - search_fields = ['id', '^db_date_sent', '^db_message'] - save_as = True - save_on_top = True - list_select_related = True -#admin.site.register(Msg, MsgAdmin) - - -class ChannelAdmin(admin.ModelAdmin): - list_display = ('id', 'db_key', 'db_lock_storage') - list_display_links = (""id"", 'db_key') - ordering = [""db_key""] - search_fields = ['id', 'db_key', 'db_aliases'] - save_as = True - save_on_top = True - list_select_related = True - fieldsets = ( - (None, {'fields': (('db_key',), 'db_lock_storage')}), ) + return my_urls + urls + +shells_admin = ShellsAdmin() -admin.site.register(ChannelDB, ChannelAdmin) +from shells.admin import SpeciesAdmin, SpecimenAdmin, SpeciesRepresentationAdmin +from shells.models import Species, Specimen, SpeciesRepresentation -Write a commit message that summarizes the changes.",Remove unsupport M2M field in channelAdmin handler. Removes traceback when DEBUG=True. -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +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 @@ -4842,10 +4540,7 @@ manager.add_command(""runserver"", Server(port=5003)) if __name__ == '__main__': manager.run() - - -The new version is -#!/usr/bin/env python +","#!/usr/bin/env python import os from app import create_app @@ -4859,76 +4554,118 @@ 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', + ], -Write a commit message that summarizes the changes.",Rename FLASH_CONFIG to match common convention -"Here are the two versions of a code. The old version is -from django.core.management.base import NoArgsCommand -from django.core.urlresolvers import reverse - -import requests - -from deflect.models import ShortURL - - -class Command(NoArgsCommand): - help = ""Validate short URL redirect targets"" - - def handle_noargs(self, *args, **options): - for url in ShortURL.objects.all(): - try: - url.check_status() - except requests.exceptions.RequestException as e: - print self.error_text(url, e) - - def error_text(self, url, exception): - """""" - """""" - return """""" - -Bad redirect target: {key} -{target} returns {error} - -Edit this URL: {edit} -"""""".format(key=url.key, target=url.long_url, error=exception, - edit=reverse('admin:deflect_shorturl_change', args=(url.id,))) - - -The new version is -from django.core.management.base import NoArgsCommand -from django.core.urlresolvers import reverse - -import requests - -from deflect.models import ShortURL - - -class Command(NoArgsCommand): - help = ""Validate short URL redirect targets"" - - def handle_noargs(self, *args, **options): - for url in ShortURL.objects.all(): - try: - url.check_status() - except requests.exceptions.RequestException as e: - print self.bad_redirect_text(url, e) - - def bad_redirect_text(self, url, exception): - """""" - Return informational text for a URL that raised an - exception. - """""" - return """""" -Redirect {key} with target {target} returns {error} - -Edit this short URL: {edit} -"""""".format(key=url.key, target=url.long_url, error=exception, - edit=reverse('admin:deflect_shorturl_change', args=(url.id,))) - - -Write a commit message that summarizes the changes.",Modify text for management command message -"Here are the two versions of a code. The old version is -#!/usr/bin/env python +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. @@ -4964,10 +4701,7 @@ if __name__ == '__main__': if sys.platform != 'darwin': raise Exception(""This script only runs on Mac"") print main() - - -The new version is -#!/usr/bin/env python +","#!/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. @@ -5006,11 +4740,18 @@ 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. -Write a commit message that summarizes the changes.","Revert ""Revert ""Use clang on mac if XCode >= 4.5""""" -"Here are the two versions of a code. The old version is -import requests +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 @@ -5042,10 +4783,7 @@ def require(resource_namespace, permissions, resource_id=None): return decorated_function return decorator - - -The new version is -import json +","import json import requests from functools import wraps @@ -5096,14 +4834,9 @@ def require(resource_namespace, permissions, resource_id=None): return decorated_function return decorator - - -Write a commit message that summarizes the changes.",Check for permission in apq -"Here are the two versions of a code. The old version is - - -The new version is -class ListNode: +",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 @@ -5138,73 +4871,70 @@ class Solution: - - -Write a commit message that summarizes the changes.",Add my two pass solution -"Here are the two versions of a code. The old version is -#!/usr/bin/python3 -#Pysarus -#A python wrapper for Big Huge Thesarus -#Jacob Adams - -import urllib.request -import json + ",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 -#where to save reteived defintions -#if None than no files are saved -savepath = ""."" - -#Your API key for Big Huge Thesarus -APIkey = """" - -def thesarus(word): - if(savepath): - try: - return json.load(savepath+word) - except: - print(""No file found in ""+savepath+"" for ""+word) - web = urllib.request.urlopen(""http://words.bighugelabs.com/api/2/""+word+""/json"") - jsonobj = json.loads(web.read()) - if(savepath): - json.dump(jsonobj,savepath+word) - return jsonobj - - -The new version is -#!/usr/bin/python3 -#Pysarus -#A python wrapper for Big Huge Thesarus -#Jacob Adams - -import urllib.request -import json +@author: jensv +"""""" -#where to save reteived defintions -#if None than no files are saved -savepath = ""."" +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 -#Your API key for Big Huge Thesarus -APIkey = """" +test_equil = None -def thesarus(word): - if(savepath): - try: - return json.load(savepath+word) - except: - print(""No file found in ""+savepath+"" for ""+word) - web = urllib.request.urlopen(""http://words.bighugelabs.com/api/2/""+APIkey+""/""+word+""/json"") - jsonobj = json.loads(web.read()) - if(savepath): - json.dump(jsonobj,savepath+word) - return jsonobj +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) -Write a commit message that summarizes the changes.",Use API key in URL -"Here are the two versions of a code. The old version is +def teardown_func(): + pass -The new version is -# coding: utf-8 +@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 @@ -5223,20 +4953,15 @@ bot = TestSpider(network_try_limit=10) bot.setup_grab(timeout=1) bot.run() - - -Write a commit message that summarizes the changes.",Add use case of spider with limits -"Here are the two versions of a code. The old version is -import requests +",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() - - -The new version is -import requests +","import requests DEFAULT_TIMEOUT = 10 @@ -5246,168 +4971,215 @@ 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() -Write a commit message that summarizes the changes.",Add a default timeout parameter to retrieve_json -"Here are the two versions of a code. The old version is -from colander import Length -from deform.widget import Select2Widget, TextAreaWidget -from ekklesia_common.contract import Form, Schema, int_property, json_property, string_property -from ekklesia_common.translation import _ +if version < '3000': + from libsass import pathutils +else: + from sublime_libsass.libsass import pathutils -class BallotSchema(Schema): - name = string_property(title=_('name'), validator=Length(min=2, max=23), missing='') - election = int_property(title=_('election_positions'), missing=0) - result = json_property(title=_('voting_result'), missing={}) - area_id = int_property(title=_('subject_area'), missing=None) - voting_id = int_property(title=('voting_phase'), missing=None) - proposition_type_id = int_property(title=('proposition_type'), missing=None) +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 BallotForm(Form): - def __init__(self, request, action): - super().__init__(BallotSchema(), request, action, buttons=(""submit"", )) - def prepare_for_render(self, items_for_selects): - widgets = { - 'result': TextAreaWidget(rows=4), - 'area_id': Select2Widget(values=items_for_selects['area']), - 'voting_id': Select2Widget(values=items_for_selects['voting']), - 'proposition_type_id': Select2Widget(values=items_for_selects['proposition_type']) - } - self.set_widgets(widgets) +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) -The new version is -from colander import Length -from deform.widget import Select2Widget, TextAreaWidget -from ekklesia_common.contract import Form, Schema, int_property, json_property, string_property -from ekklesia_common.translation import _ + @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."""""" -class BallotSchema(Schema): - name = string_property(title=_('name'), validator=Length(min=2, max=23), missing='') - election = int_property(title=_('election_positions'), missing=0) - result = json_property(title=_('voting_result'), missing={}) - area_id = int_property(title=_('subject_area'), missing=None) - voting_id = int_property(title=_('voting_phase'), missing=None) - proposition_type_id = int_property(title=_('proposition_type'), missing=None) +def setup_parser_help(parser, additional_docs=None): + """""" + Set formatting for parser to raw and add docstring to help output -class BallotForm(Form): + Parameters + ---------- - def __init__(self, request, action): - super().__init__(BallotSchema(), request, action, buttons=(""submit"", )) + parser : `ArgumentParser` + The parser to be modified. - def prepare_for_render(self, items_for_selects): - widgets = { - 'result': TextAreaWidget(rows=4), - 'area_id': Select2Widget(values=items_for_selects['area']), - 'voting_id': Select2Widget(values=items_for_selects['voting']), - 'proposition_type_id': Select2Widget(values=items_for_selects['proposition_type']) - } - self.set_widgets(widgets) + additional_docs: str + Any documentation to be added to the documentation produced by + `argparse` + """""" + from argparse import RawDescriptionHelpFormatter -Write a commit message that summarizes the changes.",Fix missing translations in ballot form -"Here are the two versions of a code. The old version is -""""""Configuration."""""" + parser.formatter_class = RawDescriptionHelpFormatter + if additional_docs is not None: + parser.epilog = additional_docs -import logging -import os -import re -from google.appengine.ext.appstats import recording +def add_verbose(parser): + """""" + Add a verbose option (--verbose or -v) to parser. -logging.info('Loading %s from %s', __name__, __file__) + Parameters: + ----------- -# Custom webapp middleware to add Appstats. -def webapp_add_wsgi_middleware(app): - app = recording.appstats_wsgi_middleware(app) - return app + parser : `ArgumentParser` -# Custom Appstats path normalization. -def appstats_normalize_path(path): - if path.startswith('/user/'): - return '/user/X' - if path.startswith('/user_popup/'): - return '/user_popup/X' - if '/diff/' in path: - return '/X/diff/...' - if '/diff2/' in path: - return '/X/diff2/...' - if '/patch/' in path: - return '/X/patch/...' - if path.startswith('/rss/'): - i = path.find('/', 5) - if i > 0: - return path[:i] + '/X' - return re.sub(r'\d+', 'X', path) + """""" -# Segregate Appstats by runtime (python vs. python27). -appstats_KEY_NAMESPACE = '__appstats_%s__' % os.getenv('APPENGINE_RUNTIME') + verbose_help = ""provide more information during processing"" + parser.add_argument(""-v"", ""--verbose"", help=verbose_help, + action=""store_true"") -# Django 1.2+ requires DJANGO_SETTINGS_MODULE environment variable to be set -# http://code.google.com/appengine/docs/python/tools/libraries.html#Django -os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' -# NOTE: All ""main"" scripts must import webapp.template before django. +def add_directories(parser): + """""" + Add a positional argument that is one or more directories. + Parameters + ---------- -The new version is -""""""Configuration."""""" + parser : `ArgumentParser` -import logging -import os -import re + """""" + + parser.add_argument(""dir"", metavar='dir', nargs='+', + help=""Directory to process"") -from google.appengine.ext.appstats import recording -logging.info('Loading %s from %s', __name__, __file__) +def construct_default_parser(docstring=None): + #import script_helpers + import argparse -# Custom webapp middleware to add Appstats. -def webapp_add_wsgi_middleware(app): - app = recording.appstats_wsgi_middleware(app) - return app + parser = argparse.ArgumentParser() + if docstring is not None: + setup_parser_help(parser, docstring) + add_verbose(parser) + add_directories(parser) -# Custom Appstats path normalization. -def appstats_normalize_path(path): - if path.startswith('/user/'): - return '/user/X' - if path.startswith('/user_popup/'): - return '/user_popup/X' - if '/diff/' in path: - return '/X/diff/...' - if '/diff2/' in path: - return '/X/diff2/...' - if '/patch/' in path: - return '/X/patch/...' - if path.startswith('/rss/'): - i = path.find('/', 5) - if i > 0: - return path[:i] + '/X' - return re.sub(r'\d+', 'X', path) + return parser +","""""""A set of functions to standardize some options for python scripts."""""" -# Segregate Appstats by runtime (python vs. python27). -appstats_KEY_NAMESPACE = '__appstats_%s__' % os.getenv('APPENGINE_RUNTIME') -# Enable Interactive Playground. -appstats_SHELL_OK = True +def setup_parser_help(parser, additional_docs=None): + """""" + Set formatting for parser to raw and add docstring to help output -# Django 1.2+ requires DJANGO_SETTINGS_MODULE environment variable to be set -# http://code.google.com/appengine/docs/python/tools/libraries.html#Django -os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' -# NOTE: All ""main"" scripts must import webapp.template before django. + Parameters + ---------- + parser : `ArgumentParser` + The parser to be modified. -Write a commit message that summarizes the changes.",Enable the Appstats Interactive Playground. -"Here are the two versions of a code. The old version is + additional_docs: str + Any documentation to be added to the documentation produced by + `argparse` + """""" + from argparse import RawDescriptionHelpFormatter -The new version is -import sys + 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 @@ -5439,11 +5211,9 @@ def reindex_quickfiles(dry): if __name__ == '__main__': dry = '--dry' in sys.argv reindex_quickfiles(dry=dry) - - -Write a commit message that summarizes the changes.",Add script to re-index users' files in quickfiles nodes -"Here are the two versions of a code. The old version is -# This file is part of Indico. +",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 @@ -5472,10 +5242,7 @@ 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')) - - -The new version is -# This file is part of Indico. +","# 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 @@ -5504,61 +5271,53 @@ 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 -Write a commit message that summarizes the changes.","Remove useless field descs, increase rows" -"Here are the two versions of a code. The old version is -from django.core.validators import RegexValidator -from django.core.exceptions import ValidationError -from dulwich.repo import check_ref_format - -import re - -sha1_validator = RegexValidator(regex=""^[a-f0-9]{40}$"", - message=""Must be valid sha1 sum"") -tag_regex = re.compile(r'^[A-Za-z][\w\-\.]+[A-Za-z]$') - - -def tag_validator(value): - if not tag_regex.match(value): - msg = ""Must be letters and numbers separated "" - msg += ""by dashes, dots, or underscores"" - raise ValidationError(msg) - if not check_ref_format('refs/tags/' + value): - msg = ""Invalid tag. Tags must adhere to ref formats defined here: "" - msg += ""https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html"" - raise ValidationError(msg) +def encode(host, uts46=False): # pylint: disable=unused-argument + # Used by urllib3 + return idna.ToASCII(host) -The new version is -from django.core.validators import RegexValidator -from django.core.exceptions import ValidationError -from dulwich.repo import check_ref_format - -import re -sha1_validator = RegexValidator(regex=""^[a-f0-9]{40}$"", - message=""Must be valid sha1 sum"") -tag_regex = re.compile(r'^[\w\-\.]+$') +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. -def tag_validator(value): - if not tag_regex.match(value): - msg = ""Must be letters and numbers separated "" - msg += ""by dashes, dots, or underscores"" - raise ValidationError(msg) - if not check_ref_format('refs/tags/' + value): - msg = ""Invalid tag. Tags must adhere to ref formats defined here: "" - msg += ""https://www.kernel.org/pub/software/scm/git/docs/git-check-ref-format.html"" - raise ValidationError(msg) +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). -Write a commit message that summarizes the changes.",Check submission names more leniently -"Here are the two versions of a code. The old version is +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. -The new version is -# This the basic flow for getting from a JP2 to a jpg w/ kdu_expand and Pillow +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 @@ -5614,14 +5373,9 @@ else: rmfifo_resp = subprocess.check_call(rmfifo_cmd, shell=True) if rmfifo_resp == 0: print 'rm fifo OK' - - -Write a commit message that summarizes the changes.","Use this enough, might as well add it." -"Here are the two versions of a code. The old version is - - -The new version is -import shlex +","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 @@ -5655,113 +5409,148 @@ for entries in outputArray: - - -Write a commit message that summarizes the changes.",Read ampstat -m -i and print out the mac addresses on the powerline network -"Here are the two versions of a code. The old version is -""""""An Extensible Dependency Resolver written in Python +",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"" - - -The new version is -""""""An Extensible Dependency Resolver written in Python +","""""""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 -Write a commit message that summarizes the changes.",Switch to an alpha version -"Here are the two versions of a code. The old version is -from base import * # noqa - -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.postgresql_psycopg2', - 'NAME': 'lutris', - 'USER': 'lutris', - 'PASSWORD': 'admin', - 'HOST': 'localhost', - } -} - - -STEAM_API_KEY = os.environ['STEAM_API_KEY'] - - -The new version is -import os -from base import * # noqa - -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.postgresql_psycopg2', - 'NAME': 'lutris', - 'USER': 'lutris', - 'PASSWORD': 'admin', - 'HOST': 'localhost', - } -} - - -STEAM_API_KEY = os.environ.get('STEAM_API_KEY') + def start(self, resetDir = True): + raise NotImplementedError + def cleanup(self): + pass -Write a commit message that summarizes the changes.",Make Steam api key optional -"Here are the two versions of a code. The old version is -# -*- coding: utf-8 -*- + def stop(self): + raise NotImplementedError -import sympy as sy + 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 -def lagrange_basis(points, sym): - """"""Generates a basis of polynomials, :math:`l_i(x)`, such that - .. math:: - l_i(x) = \delta^x_{p_i} - where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. - """""" - n = len(points) - lagrange_poly = sy.interpolating_poly +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 - return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() - for i in xrange(n)] + def start(self, resetDir = True): + raise NotImplementedError + def cleanup(self): + pass -The new version is -# -*- coding: utf-8 -*- + def stop(self): + raise NotImplementedError -import sympy as sy + def reset(self): + raise NotImplementedError + def isStarted(self): + raise NotImplementedError -def lagrange_basis(points, sym): - """"""Generates a basis of polynomials, :math:`l_i(x)`, such that - .. math:: - l_i(x) = \delta^x_{p_i} - where :math:`p_i` is the i'th entry in *points* and :math:`x \in p`. - """""" - n = len(points) - lagrange_poly = sy.interpolating_poly + def initPort(self): + ports = testhelp.findPorts(num = 1, closeSockets=False)[0] + self.port = ports[0] + self.socket = ports[1] - return [lagrange_poly(n, sym, points, [0]*i + [1] + [0]*(n-i-1)).expand() - for i in xrange(n)] + 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 -def norm_jacobi(n, a, b, sym): - G, F = sy.gamma, sy.factorial +from dusty import constants +from dusty.runner.compose import _write_composefile - N2 = sy.S(2)**(a + b + 1)/(2*n + a + b + 1)\ - * (G(n + a + 1)*G(n + b + 1))/(F(n)*G(n + a + b + 1)) +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'}} - return sy.jacobi(n, a, b, sym) / sy.sqrt(N2) + 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 -Write a commit message that summarizes the changes.",Add a function for generating normalised Jacobi polynomials. -"Here are the two versions of a code. The old version is +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'}} -The new version is -#!/usr/bin/env python3 + 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 @@ -5807,14 +5596,9 @@ if __name__ == ""__main__"": server = CustomThinServer(is_daemon=daemon) # start it up - server.start() - -Write a commit message that summarizes the changes.",Add a custom server example implementation. This is fully compatible with the client example. -"Here are the two versions of a code. The old version is - - -The new version is -#!/usr/bin/env python + 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 @@ -5865,184 +5649,93 @@ if __name__ == '__main__': 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 -Write a commit message that summarizes the changes.",Add script to list scheduled checkins -"Here are the two versions of a code. The old version is -from flask.ext.hookserver import Hooks - -from .models import db, User - - -hooks = Hooks() - - -@hooks.hook('ping') -def ping(data, guid): - return 'pong' - - -@hooks.hook('membership') -def membership(data, guid): - if data['scope'] != 'team': - return - member = User.query.filter_by(id=data['member']['id']).first() - if member is None: - return - if data['action'] == 'added': - member.is_member = True - db.session.commit() - elif data['action'] == 'removed': - member.is_member = False - db.session.commit() - - -The new version is -from flask.ext.hookserver import Hooks - -from .models import db, User - - -hooks = Hooks() - - -@hooks.hook('ping') -def ping(data, guid): - return 'pong' - +# Create app +app = Flask(__name__) +app.config.from_object('config') -@hooks.hook('membership') -def membership(data, guid): - if data['scope'] != 'team': - return - member = User.query.filter_by(id=data['member']['id']).first() - if member is None: - return - if data['action'] == 'added': - member.is_member = True - db.session.commit() - elif data['action'] == 'removed': - member.is_member = False - db.session.commit() - return ""Thanks"" +# Create mail object +mail = Mail(app) +# Create database connection object +db = MongoEngine(app) -Write a commit message that summarizes the changes.",Return a response for the membership webhook. -"Here are the two versions of a code. The old version is -from __future__ import unicode_literals +from edx_data_research.web_app.models import User, Role -import io +# 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 -import shutil -import tempfile -import unittest - -import conda_smithy.feedstock_io as fio - - -class TestFeedstockIO(unittest.TestCase): - def setUp(self): - self.old_dir = os.getcwd() - self.tmp_dir = tempfile.mkdtemp() - os.chdir(self.tmp_dir) - - with io.open(os.path.abspath("".keep""), ""w"", encoding=""utf-8"") as fh: - fh.write("""") - - - def tearDown(self): - os.chdir(self.old_dir) - del self.old_dir - - shutil.rmtree(self.tmp_dir) - del self.tmp_dir - - -if __name__ == '__main__': - unittest.main() - - -The new version is -from __future__ import unicode_literals +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']), + ], +) -import io +# 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 -import shutil -import tempfile -import unittest - -import git - -import conda_smithy.feedstock_io as fio - - -def keep_dir(dirname): - keep_filename = os.path.join(dirname, "".keep"") - with io.open(keep_filename, ""w"", encoding = ""utf-8"") as fh: - fh.write("""") - - -def parameterize(): - for pathfunc in [ - lambda pth, tmp_dir: os.path.relpath(pth, tmp_dir), - lambda pth, tmp_dir: pth - ]: - for get_repo in [ - lambda tmp_dir: None, - lambda tmp_dir: git.Repo.init(tmp_dir) - ]: - try: - tmp_dir = tempfile.mkdtemp() - keep_dir(tmp_dir) - - old_dir = os.getcwd() - os.chdir(tmp_dir) - - yield ( - tmp_dir, - get_repo(tmp_dir), - lambda pth: pathfunc(pth, tmp_dir) - ) - finally: - os.chdir(old_dir) - shutil.rmtree(tmp_dir) - - -class TestFeedstockIO(unittest.TestCase): - def setUp(self): - self.old_dir = os.getcwd() - self.tmp_dir = tempfile.mkdtemp() - os.chdir(self.tmp_dir) - - with io.open(os.path.abspath("".keep""), ""w"", encoding=""utf-8"") as fh: - fh.write("""") - - - def test_repo(self): - for tmp_dir, repo, pathfunc in parameterize(): - if repo is None: - self.assertTrue( - fio.get_repo(pathfunc(tmp_dir)) is None - ) - else: - self.assertIsInstance( - fio.get_repo(pathfunc(tmp_dir)), - git.Repo - ) - - - def tearDown(self): - os.chdir(self.old_dir) - del self.old_dir - - shutil.rmtree(self.tmp_dir) - del self.tmp_dir - - -if __name__ == '__main__': - unittest.main() +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()) -Write a commit message that summarizes the changes.",Add some tests for `get_repo`. +# 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