commit stringlengths 40 40 | old_file stringlengths 4 118 | new_file stringlengths 4 118 | old_contents stringlengths 10 3.52k | new_contents stringlengths 21 3.18k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 43k | ndiff stringlengths 52 3.32k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | fuzzy_diff stringlengths 17 3.24k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6af918668cddf30c12a10fe46bc174e110bf04c3 | red_api.py | red_api.py | import os
from pymongo import MongoClient
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_john_tweets = mo... | import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo on... | Use bson's JSON util to handle ObjectIds in a JSON context | Use bson's JSON util to handle ObjectIds in a JSON context
| Python | mit | AnSavvides/redjohn,AnSavvides/redjohn | import os
+ from pymongo import DESCENDING
from pymongo import MongoClient
+ from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a co... | Use bson's JSON util to handle ObjectIds in a JSON context | ## Code Before:
import os
from pymongo import MongoClient
MONGO_USER = os.getenv('MONGO_USER')
MONGO_PASSWORD = os.getenv('MONGO_PASSWORD')
MONGO_URI = 'mongodb://{0}:{1}@paulo.mongohq.com:10039/redjohn'.format(MONGO_USER, MONGO_PASSWORD)
# Open a connection to Mongo once
#
mongo_client = MongoClient(MONGO_URI)
red_... | // ... existing code ...
import os
from pymongo import DESCENDING
from pymongo import MongoClient
from bson.json_util import dumps
MONGO_USER = os.getenv('MONGO_USER')
// ... modified code ...
tweets = red_john_tweets.find({
'suspect': suspect
}).sort('entry_time', DESCENDING)[:limit]
retu... |
8eb0b7fcd6ffb81d6b0fc69cb31c7625550583d7 | targetrupypy.py | targetrupypy.py | from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
driver.exe_name = "rupypy-c"
return entry_point, None
def jitpolicy(driver):
return JitPolicy() | from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
driver.exe_name = "./bin/topaz"
return entry_point, None
def jitpolicy(driver):
return JitPolicy()
| Move towards a normal bin directory. | Move towards a normal bin directory.
| Python | bsd-3-clause | babelsberg/babelsberg-r,topazproject/topaz,babelsberg/babelsberg-r,kachick/topaz,kachick/topaz,babelsberg/babelsberg-r,babelsberg/babelsberg-r,babelsberg/babelsberg-r,kachick/topaz,topazproject/topaz,topazproject/topaz,topazproject/topaz | from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
- driver.exe_name = "rupypy-c"
+ driver.exe_name = "./bin/topaz"
return entry_point, None
+
def jitpolicy(driver):
return JitPolicy()
+ | Move towards a normal bin directory. | ## Code Before:
from pypy.jit.codewriter.policy import JitPolicy
from rupypy.main import entry_point
def target(driver, args):
driver.exe_name = "rupypy-c"
return entry_point, None
def jitpolicy(driver):
return JitPolicy()
## Instruction:
Move towards a normal bin directory.
## Code After:
from pypy.jit... | // ... existing code ...
def target(driver, args):
driver.exe_name = "./bin/topaz"
return entry_point, None
def jitpolicy(driver):
// ... rest of the code ... |
2cc8a541814cc353e7b60767afd2128dce38918a | tests/test_plugins/test_plugin/server.py | tests/test_plugins/test_plugin/server.py |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
... |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Other(Resource):
... | Fix failing python style test | Fix failing python style test
| Python | apache-2.0 | jbeezley/girder,jcfr/girder,RafaelPalomar/girder,opadron/girder,Kitware/girder,essamjoubori/girder,RafaelPalomar/girder,adsorensen/girder,Xarthisius/girder,adsorensen/girder,data-exp-lab/girder,jcfr/girder,girder/girder,opadron/girder,Xarthisius/girder,data-exp-lab/girder,jcfr/girder,kotfic/girder,manthey/girder,msmole... |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
... | Fix failing python style test | ## Code Before:
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
class CustomAppRoot(object):
"""
The webroot endpoint simply serves the main index HTML file.
"""
exposed = True
def GET(self):
return "hello world"
class Othe... | ...
def load(info):
info['serverRoot'], info['serverRoot'].girder = (
CustomAppRoot(), info['serverRoot'])
info['serverRoot'].api = info['serverRoot'].girder.api
del info['serverRoot'].girder.api
... |
5cca245f84a87f503c8e16577b7dba635d689a26 | opencc/__main__.py | opencc/__main__.py | from __future__ import print_function
import argparse
import sys
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original text from... | from __future__ import print_function
import argparse
import sys
import io
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read original... | Add support for Python 2.6 and 2.7 | Add support for Python 2.6 and 2.7
Remove the following error when using Python 2.6 and 2.7.
TypeError: 'encoding' is an invalid keyword argument for this function
Python 3 operation is unchanged
| Python | apache-2.0 | yichen0831/opencc-python | from __future__ import print_function
import argparse
import sys
+ import io
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
... | Add support for Python 2.6 and 2.7 | ## Code Before:
from __future__ import print_function
import argparse
import sys
from opencc import OpenCC
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-i', '--input', metavar='<file>',
help='Read or... | // ... existing code ...
import argparse
import sys
import io
from opencc import OpenCC
// ... modified code ...
parser.add_argument('-o', '--output', metavar='<file>',
help='Write converted text to <file>.')
parser.add_argument('-c', '--config', metavar='<conversion>',
... |
6f0a35372d625f923b9093194540cf0b0e9f054d | platformio_api/__init__.py | platformio_api/__init__.py |
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__email__ = "me@ikr... |
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__email__ = "me@ikr... | Increase repo size to 20Mb | Increase repo size to 20Mb
| Python | apache-2.0 | orgkhnargh/platformio-api,platformio/platformio-api |
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Iva... | Increase repo size to 20Mb | ## Code Before:
import json
import logging.config
import os
from time import tzset
VERSION = (0, 3, 0)
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio-api"
__description__ = ("An API for PlatformIO")
__url__ = "https://github.com/ivankravets/platformio-api"
__author__ = "Ivan Kravets"
__e... | # ... existing code ...
DL_PIO_DIR=None,
DL_PIO_URL=None,
MAX_DLFILE_SIZE=1024*1024*20, # 20 Mb
LOGGING=dict(version=1)
)
# ... rest of the code ... |
7a057ba74a5914f8d7f8db3646feb5cb06a74cef | ml/pytorch/image_classification/image_classifier.py | ml/pytorch/image_classification/image_classifier.py | import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
net: A p... | import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
net: A p... | Add set_optimizer method to pytorch ImageClassifier class | FEAT: Add set_optimizer method to pytorch ImageClassifier class
| Python | apache-2.0 | ronrest/convenience_py,ronrest/convenience_py | import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
... | Add set_optimizer method to pytorch ImageClassifier class | ## Code Before:
import torch
from torch import nn
from torch.autograd import Variable
def accuracy(preds, labels):
return (preds==labels).mean()
def n_correct(preds, labels):
return (preds==labels).sum()
class ImageClassifier(object):
def __init__(self, net, n_classes):
"""
Args:
... | # ... existing code ...
self.optimizer = None
def set_optimizer(self, opt_func=torch.optim.Adam, **kwargs):
"""
Args:
opt_func: (function class) the optimization function creator to use
**kwargs: The keyword arguments to pass to opt_func
... |
6d72a1d3b4bd2e1a11e2fb9744353e5d2d9c8863 | setup.py | setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("lulu_base", ["lulu_base.pyx"]),
Extension("ccomp", ["ccomp.pyx"])])
| from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
def cext(name):
return Extension(name, [name + ".pyx"],
include_dirs=[numpy.get_include()])
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [cext('lulu... | Add NumPy includes dir for Cython builds. | Add NumPy includes dir for Cython builds.
| Python | bsd-3-clause | stefanv/lulu | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
+ import numpy
+
+ def cext(name):
+ return Extension(name, [name + ".pyx"],
+ include_dirs=[numpy.get_include()])
setup(cmdclass = {'build_ext': build_ext},
+ ext... | Add NumPy includes dir for Cython builds. | ## Code Before:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("lulu_base", ["lulu_base.pyx"]),
Extension("ccomp", ["ccomp.pyx"])])
## Instruction:
Add NumP... | // ... existing code ...
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
def cext(name):
return Extension(name, [name + ".pyx"],
include_dirs=[numpy.get_include()])
setup(cmdclass = {'build_ext': build_ext},
ext_modules = [cext('lulu_base... |
bf41f23d71491050dc79a2975b26ffe210b45505 | examples/test_contains_selector.py | examples/test_contains_selector.py | from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_text("Math Work", "#ctitle")
self.click('a:contains("Next")')
self.assert_text("Drone Fishing", "#ctitle")
| from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_element('div.box div:contains("Math Work")')
self.click('a:contains("Next")')
self.assert_element('div div:contains("Dr... | Update an example that uses the ":contains()" selector | Update an example that uses the ":contains()" selector
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
- self.assert_text("Math Work", "#ctitle")
+ self.assert_element('div.box div:contains("Math Work")')
self.click('a:c... | Update an example that uses the ":contains()" selector | ## Code Before:
from seleniumbase import BaseCase
class ContainsSelectorTests(BaseCase):
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_text("Math Work", "#ctitle")
self.click('a:contains("Next")')
self.assert_text("Drone Fishing", "#ctitle")
## ... | // ... existing code ...
def test_contains_selector(self):
self.open("https://xkcd.com/2207/")
self.assert_element('div.box div:contains("Math Work")')
self.click('a:contains("Next")')
self.assert_element('div div:contains("Drone Fishing")')
// ... rest of the code ... |
047483d9897e75f8284c39e8477a285763da7b37 | heufybot/modules/util/commandhandler.py | heufybot/modules/util/commandhandler.py | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.handleChannelMessag... | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.handleChannelMessag... | Make the bot respond to its name | Make the bot respond to its name
Implements GH-7
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, ... | Make the bot respond to its name | ## Code Before:
from twisted.plugin import IPlugin
from heufybot.moduleinterface import BotModule, IBotModule
from zope.interface import implements
class CommandHandler(BotModule):
implements(IPlugin, IBotModule)
name = "CommandHandler"
def actions(self):
return [ ("message-channel", 1, self.han... | ...
def _handleCommand(self, message):
commandPrefix = self.bot.config.serverItemWithDefault(message["server"], "command_prefix", "!")
botNick = self.bot.servers[message["server"]].nick.lower()
params = message["body"].split()
if message["body"].startswith(commandPrefix):
... |
262a8fe3651a4ad368fd6594cba0669267c2d225 | run_deploy_job_wr.py | run_deploy_job_wr.py | import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{}/{}/build-{}'.f... | import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{}/{}/build-{}'.f... | Add *.json to the list of artifacts backed up by Workspace Runner. | Add *.json to the list of artifacts backed up by Workspace Runner. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju | import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products... | Add *.json to the list of artifacts backed up by Workspace Runner. | ## Code Before:
import json
import os
from os.path import join
import subprocess
import sys
from tempfile import NamedTemporaryFile
def main():
revision_build = os.environ['revision_build']
job_name = os.environ['JOB_NAME']
build_number = os.environ['BUILD_NUMBER']
prefix = 'juju-ci/products/version-{... | // ... existing code ...
'artifacts/machine*/*log*',
'artifacts/*.jenv',
'artifacts/*.json',
]},
'bucket': 'juju-qa-data',
// ... rest of the code ... |
9c2951d794bb27952606cae77da1ebcd0d651e72 | aiodownload/api.py | aiodownload/api.py |
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
url_map = url... |
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
url_map = url... | Fix - needed to provide create_task a function, not a class | Fix - needed to provide create_task a function, not a class
| Python | mit | jelloslinger/aiodownload |
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, do... | Fix - needed to provide create_task a function, not a class | ## Code Before:
from aiodownload import AioDownloadBundle, AioDownload
import asyncio
def one(url, download=None):
return [s for s in swarm([url], download=download)][0]
def swarm(urls, download=None):
return [e for e in each(urls, download=download)]
def each(iterable, url_map=None, download=None):
... | # ... existing code ...
tasks.append(
download._loop.create_task(
download.main(AioDownloadBundle(url, info=info))
)
)
# ... rest of the code ... |
b3b67fe0e68423fc2f85bccf1f20acdb779a38ba | pylxd/deprecated/tests/utils.py | pylxd/deprecated/tests/utils.py |
from pylxd import api
from pylxd import exceptions as lxd_exceptions
def upload_image(image):
alias = "{}/{}/{}/{}".format(
image["os"], image["release"], image["arch"], image["variant"]
)
lxd = api.API()
imgs = api.API(host="images.linuxcontainers.org")
d = imgs.alias_show(alias)
me... |
from pylxd import api
def delete_image(image):
lxd = api.API()
lxd.image_delete(image)
| Remove unused testing utility function | Remove unused testing utility function
Signed-off-by: Dougal Matthews <8f24f2c0fd825cfb6716a36822888c4a01678c88@dougalmatthews.com>
| Python | apache-2.0 | lxc/pylxd,lxc/pylxd |
from pylxd import api
- from pylxd import exceptions as lxd_exceptions
-
-
- def upload_image(image):
- alias = "{}/{}/{}/{}".format(
- image["os"], image["release"], image["arch"], image["variant"]
- )
- lxd = api.API()
- imgs = api.API(host="images.linuxcontainers.org")
- d = imgs.a... | Remove unused testing utility function | ## Code Before:
from pylxd import api
from pylxd import exceptions as lxd_exceptions
def upload_image(image):
alias = "{}/{}/{}/{}".format(
image["os"], image["release"], image["arch"], image["variant"]
)
lxd = api.API()
imgs = api.API(host="images.linuxcontainers.org")
d = imgs.alias_sho... | # ... existing code ...
from pylxd import api
# ... rest of the code ... |
c24dc7db961b03c947a98454fc3e8655c5f938ff | functional_tests/test_all_users.py | functional_tests/test_all_users.py | from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Fire... | from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Fire... | Fix css and heading test also removed localization test as no longer required | Fix css and heading test also removed localization test as no longer required
| Python | mit | iAmMrinal0/django_moviealert,iAmMrinal0/django_moviealert,iAmMrinal0/django_moviealert | from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.br... | Fix css and heading test also removed localization test as no longer required | ## Code Before:
from datetime import date
from django.core.urlresolvers import reverse
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils import formats
from selenium import webdriver
class HomeNewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
self.browser ... | # ... existing code ...
self.assertIn("Alert", self.browser.title)
def test_h2_css(self):
self.browser.get(self.get_full_url("home"))
h2 = self.browser.find_element_by_tag_name("h2")
self.assertIn(h2.value_of_css_property(
"color"), "rgba(0, 0, 0, 1)")
def test_h... |
5748b1a7dc4a5be3b2b9da9959eabe586347078a | tensorflow_federated/python/program/value_reference.py | tensorflow_federated/python/program/value_reference.py | """Defines the abstract interface for classes that reference values."""
import abc
from typing import Any
from tensorflow_federated.python.core.impl.types import typed_object
class ValueReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface for classes that reference values.
This ... |
import abc
from typing import Union
import numpy as np
from tensorflow_federated.python.core.impl.types import typed_object
class ServerArrayReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface representing references to server placed values."""
@abc.abstractmethod
def get_va... | Update the Value Reference API to be more precise about the types of values being referenced. | Update the Value Reference API to be more precise about the types of values being referenced.
PiperOrigin-RevId: 404647934
| Python | apache-2.0 | tensorflow/federated,tensorflow/federated,tensorflow/federated | - """Defines the abstract interface for classes that reference values."""
import abc
- from typing import Any
+ from typing import Union
+
+ import numpy as np
from tensorflow_federated.python.core.impl.types import typed_object
- class ValueReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
+... | Update the Value Reference API to be more precise about the types of values being referenced. | ## Code Before:
"""Defines the abstract interface for classes that reference values."""
import abc
from typing import Any
from tensorflow_federated.python.core.impl.types import typed_object
class ValueReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface for classes that reference ... | ...
import abc
from typing import Union
import numpy as np
from tensorflow_federated.python.core.impl.types import typed_object
...
class ServerArrayReference(typed_object.TypedObject, metaclass=abc.ABCMeta):
"""An abstract interface representing references to server placed values."""
@abc.abstractm... |
b9b4089fcd7f26ebf339c568ba6454d538a1813e | zk_shell/cli.py | zk_shell/cli.py | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... | Handle IOError in run_once mode so paging works | Handle IOError in run_once mode so paging works
Signed-off-by: Raul Gutierrez S <f25f6873bbbde69f1fe653b3e6bd40d543b8d0e0@itevenworks.net>
| Python | apache-2.0 | harlowja/zk_shell,harlowja/zk_shell,rgs1/zk_shell,rgs1/zk_shell | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)... | Handle IOError in run_once mode so paging works | ## Code Before:
from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = sel... | ...
if params.run_once != "":
try:
sys.exit(0 if s.onecmd(params.run_once) == None else 1)
except IOError:
sys.exit(1)
intro = "Welcome to zk-shell (%s)" % (__version__)
... |
8090fa9c072656497ff383e9b76d49af2955e420 | examples/hopv/hopv_graph_conv.py | examples/hopv/hopv_graph_conv.py | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvTensorGraph
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset... | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# Load HOPV dataset
hopv_... | Fix GraphConvTensorGraph to GraphConvModel in hopv example | Fix GraphConvTensorGraph to GraphConvModel in hopv example
| Python | mit | Agent007/deepchem,lilleswing/deepchem,lilleswing/deepchem,Agent007/deepchem,peastman/deepchem,miaecle/deepchem,peastman/deepchem,ktaneishi/deepchem,miaecle/deepchem,Agent007/deepchem,deepchem/deepchem,ktaneishi/deepchem,deepchem/deepchem,ktaneishi/deepchem,miaecle/deepchem,lilleswing/deepchem | from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
- from models import GraphConvTensorGraph
+ from models import GraphConvModel
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as d... | Fix GraphConvTensorGraph to GraphConvModel in hopv example | ## Code Before:
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
from models import GraphConvTensorGraph
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_hopv
# L... | // ... existing code ...
import numpy as np
from models import GraphConvModel
np.random.seed(123)
// ... modified code ...
# Batch size of models
batch_size = 50
model = GraphConvModel(
len(hopv_tasks), batch_size=batch_size, mode='regression')
// ... rest of the code ... |
c1b97bbc6fc0603c0f2a809175edf88cd1e4a207 | setup.py | setup.py | from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
version='0.... | from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
version='0.... | Add requirement of h5py and phonopy | Add requirement of h5py and phonopy
| Python | mit | yuzie007/ph_unfolder,yuzie007/upho | from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
... | Add requirement of h5py and phonopy | ## Code Before:
from distutils.core import setup
packages = [
'upho',
'upho.phonon',
'upho.harmonic',
'upho.analysis',
'upho.structure',
'upho.irreps',
'upho.qpoints',
'group',
]
scripts = [
'scripts/upho_weights',
'scripts/upho_sf',
'scripts/qpoints',
]
setup(name='upho',
... | // ... existing code ...
packages=packages,
scripts=scripts,
install_requires=['numpy', 'h5py', 'phonopy'])
// ... rest of the code ... |
9217bfc6bab0d152e33d9fda60218c404b61d064 | cmd2/__init__.py | cmd2/__init__.py | from .cmd2 import __version__, Cmd, CmdResult, Statement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
| from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
| Add EmptyStatement exception to default imports | Add EmptyStatement exception to default imports
| Python | mit | python-cmd2/cmd2,python-cmd2/cmd2 | - from .cmd2 import __version__, Cmd, CmdResult, Statement, categorize
+ from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
| Add EmptyStatement exception to default imports | ## Code Before:
from .cmd2 import __version__, Cmd, CmdResult, Statement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
## Instruction:
Add EmptyStatement exception to default imports
## Code After:
from .cmd2 import __version__, Cmd, CmdResult, Stateme... | // ... existing code ...
from .cmd2 import __version__, Cmd, CmdResult, Statement, EmptyStatement, categorize
from .cmd2 import with_argument_list, with_argparser, with_argparser_and_unknown_args, with_category
// ... rest of the code ... |
dd8c85a49a31693f43e6f6877a0657d63cbc1b01 | auth0/v2/device_credentials.py | auth0/v2/device_credentials.py | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in ... | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the token generator in ... | Remove default arguments for user_id, client_id and type | Remove default arguments for user_id, client_id and type
| Python | mit | auth0/auth0-python,auth0/auth0-python | from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using... | Remove default arguments for user_id, client_id and type | ## Code Before:
from .rest import RestClient
class DeviceCredentials(object):
"""Auth0 connection endpoints
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
jwt_token (str): An API token created with your account's global
keys. You can create one by using the tok... | // ... existing code ...
return url
def get(self, user_id, client_id, type, fields=[], include_fields=True):
params = {
'fields': ','.join(fields) or None,
// ... rest of the code ... |
3e98ed8801d380b6ab40156b1f20a1f9fe23a755 | books/views.py | books/views.py | from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.all()
serializer_class = BookPageSeri... | from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.order_by('page_number')
serializer_cl... | Order book pages by page number. | Order book pages by page number.
| Python | mit | Pepedou/Famas | from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
- queryset = BookPage.objects.all()
+ queryse... | Order book pages by page number. | ## Code Before:
from rest_framework import viewsets
from books.models import BookPage
from books.serializers import BookPageSerializer
class BookPageViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.all()
serializer_clas... | // ... existing code ...
API endpoint that allows BookPages to be viewed or edited.
"""
queryset = BookPage.objects.order_by('page_number')
serializer_class = BookPageSerializer
// ... rest of the code ... |
d7ebf5c6db9b73133915aabb3dbd9c5b283f9982 | ooni/tests/test_trueheaders.py | ooni/tests/test_trueheaders.py | from twisted.trial import unittest
from ooni.utils.txagentwithsocks import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3':... | from twisted.trial import unittest
from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
'Header3': ['Va... | Fix unittest for true headers.. | Fix unittest for true headers..
| Python | bsd-2-clause | kdmurray91/ooni-probe,kdmurray91/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-prob... | from twisted.trial import unittest
- from ooni.utils.txagentwithsocks import TrueHeaders
+ from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1',... | Fix unittest for true headers.. | ## Code Before:
from twisted.trial import unittest
from ooni.utils.txagentwithsocks import TrueHeaders
dummy_headers_dict = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB']
}
dummy_headers_dict2 = {
'Header1': ['Value1', 'Value2'],
'Header2': ['ValueA', 'ValueB'],
... | # ... existing code ...
from twisted.trial import unittest
from ooni.utils.trueheaders import TrueHeaders
dummy_headers_dict = {
# ... rest of the code ... |
5b7a1a40ea43834feb5563f566d07bd5b31c589d | tests/test-recipes/metadata/always_include_files_glob/run_test.py | tests/test-recipes/metadata/always_include_files_glob/run_test.py | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set... | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
assert set... | Add error messages to the asserts | Add error messages to the asserts
| Python | bsd-3-clause | ilastik/conda-build,shastings517/conda-build,frol/conda-build,dan-blanchard/conda-build,mwcraig/conda-build,mwcraig/conda-build,dan-blanchard/conda-build,ilastik/conda-build,sandhujasmine/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,shastings517/conda-build,rmcgibbo/conda-build,shastings517/conda-build,da... | import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'd... | Add error messages to the asserts | ## Code Before:
import os
import sys
import json
def main():
prefix = os.environ['PREFIX']
info_file = os.path.join(prefix, 'conda-meta',
'always_include_files_regex-0.1-0.json')
with open(info_file, 'r') as fh:
info = json.load(fh)
if sys.platform == 'darwin':
... | # ... existing code ...
if sys.platform == 'darwin':
assert set(info['files']) == {'lib/libpng.dylib', 'lib/libpng16.16.dylib', 'lib/libpng16.dylib'}, info['files']
elif sys.platform.startswith('linux'):
assert set(info['files']) == {'lib/libpng.so', 'lib/libpng16.so', 'lib/libpng16.so.16', ... |
08812c8507fac2c57bd143dd7aad4c54d5c0aa75 | panoptes_client/user.py | panoptes_client/user.py | from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_email',
)
... | from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_email',
)
... | Allow batched User lookups by login name | Allow batched User lookups by login name
| Python | apache-2.0 | zooniverse/panoptes-python-client | from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'val... | Allow batched User lookups by login name | ## Code Before:
from __future__ import absolute_import, division, print_function
from panoptes_client.panoptes import PanoptesObject, LinkResolver
from panoptes_client.utils import isiterable, split
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = (
'valid_ema... | // ... existing code ...
def where(cls, **kwargs):
email = kwargs.get('email')
login = kwargs.get('login')
if email and login:
raise ValueError(
'Queries are supported on at most ONE of email and login'
)
if email:
if not isite... |
6caca3259f4ec8f298b1d35f15e4492efbcff6b1 | tests/basics/dict1.py | tests/basics/dict1.py |
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
# equality opera... |
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
# equality opera... | Add test to print full KeyError exc from failed dict lookup. | tests: Add test to print full KeyError exc from failed dict lookup.
| Python | mit | jmarcelino/pycom-micropython,alex-march/micropython,hiway/micropython,AriZuu/micropython,chrisdearman/micropython,kerneltask/micropython,jmarcelino/pycom-micropython,selste/micropython,tuc-osg/micropython,blazewicz/micropython,oopy/micropython,ryannathans/micropython,micropython/micropython-esp32,trezor/micropython,inf... |
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different siz... | Add test to print full KeyError exc from failed dict lookup. | ## Code Before:
d = {}
print(d)
d[2] = 123
print(d)
d = {1:2}
d[3] = 3
print(len(d), d[1], d[3])
d[1] = 0
print(len(d), d[1], d[3])
print(str(d) == '{1: 0, 3: 3}' or str(d) == '{3: 3, 1: 0}')
x = 1
while x < 100:
d[x] = x
x += 1
print(d[50])
# equality operator on dicts of different size
print({} == {1:1})
... | ...
try:
{}[0]
except KeyError as er:
print('KeyError', er, repr(er), er.args)
# unsupported unary op
... |
53d5f47c828bec78e7241cb9e3d4f614dd18e6f9 | responder.py | responder.py | import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)... | import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = yaml.load(stream)... | Fix bug with text/plain response | Fix bug with text/plain response
| Python | mit | aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools,aaronbassett/Bad-Tools | import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
... | Fix bug with text/plain response | ## Code Before:
import random
import yaml
from flask import jsonify, Response, render_template
class Which(object):
def __init__(self, mime_type, args):
self.mime_type = mime_type
self.args = args
@property
def _excuse(self):
stream = open("excuses.yaml", 'r')
excuses = y... | ...
elif self.mime_type == "text/plain":
return Response(self._excuse, mimetype='text/plain'), "/text/"
else:
... |
47ddf999dd7ef8cd7600710ad6ad7611dd55a218 | bin/testNetwork.py | bin/testNetwork.py |
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scann... |
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[key] = value
scann... | Change the config dictionary key validation | Change the config dictionary key validation
| Python | apache-2.0 | starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser,starksm64/NativeRaspberryPiBeaconParser |
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("="... | Change the config dictionary key validation | ## Code Before:
import subprocess
import os
from time import sleep
env = {}
HOME = os.environ.get("HOME", "/root")
scannerConf = open(HOME+"/scanner.conf", "rt")
while True:
in_line = scannerConf.readline()
if not in_line:
break
in_line = in_line[:-1]
key, value = in_line.split("=")
env[ke... | ...
GATEWAY = '192.168.1.1'
if 'GATEWAY' in env:
GATEWAY = env['GATEWAY']
IFACE = 'wlan0'
if 'IFACE' in env:
IFACE = env['IFACE']
... |
27d40996f0912a1b9b16afa0884f10b1504acce2 | scoring_engine/web/__init__.py | scoring_engine/web/__init__.py | import os
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(scoreboard.mod)
ap... | import os
import logging
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, ab... | Use error severity for flask output | Use error severity for flask output
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | import os
+ import logging
from flask import Flask
+
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
+
+
+ log = logging.getLogger('werkzeug')
+ log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services,... | Use error severity for flask output | ## Code Before:
import os
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(sc... | ...
import os
import logging
from flask import Flask
app = Flask(__name__)
...
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth... |
56e3f571196bdc0ab8882f56ed66192d54ff8cad | gmt/clib/tests/test_functions.py | gmt/clib/tests/test_functions.py | import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap'
args = '-R... | import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap'
args = '-R... | Remove tmp file created by test | Remove tmp file created by test
| Python | bsd-3-clause | GenericMappingTools/gmt-python,GenericMappingTools/gmt-python | import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module ... | Remove tmp file created by test | ## Code Before:
import os
from .. import create_session, call_module
def test_create_session():
"Test that create_session is called without errors"
session = create_session()
assert session is not None
def test_call_module():
"Run a psbasemap call to see if the module works"
module = 'psbasemap... | ...
call_module(session, module, args)
assert os.path.exists('tmp.ps')
os.remove('tmp.ps')
# Not the most ideal test. Just check if no segfaults or exceptions occur.
... |
b16474b4523e8e804f28188ba74c992896748efe | broctl/Napatech.py | broctl/Napatech.py | import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use this plugin only... | import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use this plugin only... | Fix minor bug in broctl plugin. | Fix minor bug in broctl plugin.
| Python | bsd-3-clause | hosom/bro-napatech,hosom/bro-napatech | import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
... | Fix minor bug in broctl plugin. | ## Code Before:
import BroControl.plugin
import BroControl.config
class Napatech(BroControl.plugin.Plugin):
def __init__(self):
super(Napatech, self).__init__(apiversion=1)
def name(self):
return 'napatech'
def pluginVersion(self):
return 1
def init(self):
# Use ... | # ... existing code ...
def broctl_config(self):
script = ''
script += '# Settings for configuring Napatech interractions'
script += '\nredef Napatech::dedupe_lru_size = {0};'.format(self.getOption('dedupe_lru_size'))
# ... rest of the code ... |
9dafef749aaf2fca9e865cf28b043ea22bafe3a5 | backend/django/apps/accounts/tests.py | backend/django/apps/accounts/tests.py | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = B... | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = B... | Create a test for Account creation | Create a test for Account creation
| Python | mit | slavpetroff/sweetshop,slavpetroff/sweetshop | from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class... | Create a test for Account creation | ## Code Before:
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from rest_framework import status
import factory
import json
from .models import BaseAccount
from .serializers import WholeAccountSerializer
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
... | ...
raw=json.dumps(response.data),
expected_data=WholeAccountSerializer(self.user).data)
class CreateUserTest(APITestCase):
def setUp(self):
self.user = UserFactory()
def test_create_user(self):
self.user.email = 'john@email.com'
data = json.dumps(WholeAcc... |
4d29aa24b39285c491182edd69ecb7c22a9d643d | ceph_medic/tests/test_main.py | ceph_medic/tests/test_main.py | import pytest
import ceph_medic.main
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medic(argv)
... | import pytest
import ceph_medic.main
from mock import patch
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.m... | Fix test breakage when ssh_config missing | tests: Fix test breakage when ssh_config missing
I assumed /etc/ssh/ssh_config would be present, but it turns out in a
mock chroot environment it isn't.
Signed-off-by: Zack Cerza <d7cdf09fc0f0426e98c9978ee42da5d61fa54986@redhat.com>
| Python | mit | alfredodeza/ceph-doctor | import pytest
import ceph_medic.main
+
+ from mock import patch
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit)... | Fix test breakage when ssh_config missing | ## Code Before:
import pytest
import ceph_medic.main
class TestMain(object):
def test_main(self):
assert ceph_medic.main
def test_invalid_ssh_config(self, capsys):
argv = ["ceph-medic", "--ssh-config", "/does/not/exist"]
with pytest.raises(SystemExit):
ceph_medic.main.Medi... | ...
import pytest
import ceph_medic.main
from mock import patch
...
ssh_config = '/etc/ssh/ssh_config'
argv = ["ceph-medic", "--ssh-config", ssh_config]
def fake_exists(path):
if path == ssh_config:
return True
if path.endswith('cephmedic.con... |
959897478bbda18f02aa6e38f2ebdd837581f1f0 | tests/test_sct_verify_signature.py | tests/test_sct_verify_signature.py | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signa... | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signa... | Fix test for changed SctVerificationResult | Fix test for changed SctVerificationResult
| Python | mit | theno/ctutlz,theno/ctutlz | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin')... | Fix test for changed SctVerificationResult | ## Code Before:
from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').... | // ... existing code ...
pubkey = open(flo('{basedir}/pubkey.pem'), 'rb').read()
assert verify_signature(signature_input, signature, pubkey) is True
signature_input = b'some invalid signature input'
assert verify_signature(signature_input, signature, pubkey) is False
// ... rest of the code ... |
2ec5f71d04ae17a1c0a457fba1b82f8c8e8891ab | sc2reader/listeners/utils.py | sc2reader/listeners/utils.py | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass | Add a default ListenerBase.setup implementation. | Add a default ListenerBase.setup implementation.
| Python | mit | StoicLoofah/sc2reader,vlaufer/sc2reader,vlaufer/sc2reader,GraylinKim/sc2reader,ggtracker/sc2reader,ggtracker/sc2reader,GraylinKim/sc2reader,StoicLoofah/sc2reader | from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
+
+ def setup(self, replay):
+ pass | Add a default ListenerBase.setup implementation. | ## Code Before:
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
## Instruction:
Add a default ListenerBase.setup implementation.
## Code After:
from sc2reader import log_uti... | // ... existing code ...
def accepts(self, event):
return true
def setup(self, replay):
pass
// ... rest of the code ... |
2ef0ccfbf337d0ef1870c5a1191b2bcdcffd1f9e | dbaas/backup/admin/log_configuration.py | dbaas/backup/admin/log_configuration.py | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
... | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_days",
... | Add new fields on LogConfiguration model | Add new fields on LogConfiguration model
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "re... | Add new fields on LogConfiguration model | ## Code Before:
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
import logging
LOG = logging.getLogger(__name__)
class LogConfigurationAdmin(admin.ModelAdmin):
list_filter = ("environment", "engine_type")
list_display = ("environment", "engine_type", "retention_da... | # ... existing code ...
list_display = ("environment", "engine_type", "retention_days",
"filer_path", "mount_point_path", "log_path",
"cron_minute", "cron_hour")
# ... rest of the code ... |
End of preview. Expand in Data Studio
Code Apply
Processed EditPackFT with fuzzy diff generated using heuristics for Python language.
Columns
old_contentsthe old codenew_contentsthe new codefuzzy_diffthe code segment extracted from diff betweenold_contentsandnew_contents
Augmentation
Examples with number of diff chunks > 1 were duplicated. Old contents have one of the diff chunks applied.
Example
Diff
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
+ with producers[self.connection].acquire(block=False) as producer:
+ for queue in task_queues:
+ maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
- for queue in task_queues:
- maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
Snippet
# ... existing code ...
self.connection = BrokerConnection(**config)
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
# ... modified code ...
with producers[self.connection].acquire(block=False) as producer:
producer.publish(payload,
exchange=task_exchange,
# ... rest of the code ...
Partial apply
from kombu import BrokerConnection
from kombu.common import maybe_declare
from kombu.pools import producers
from sentry.conf import settings
from sentry.queue.queues import task_queues, task_exchange
class Broker(object):
def __init__(self, config):
self.connection = BrokerConnection(**config)
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
def delay(self, func, *args, **kwargs):
payload = {
"func": func,
"args": args,
"kwargs": kwargs,
}
with producers[self.connection].acquire(block=False) as producer:
for queue in task_queues:
maybe_declare(queue, producer.channel)
producer.publish(payload,
exchange=task_exchange,
serializer="pickle",
compression="bzip2",
queue='default',
routing_key='default',
)
broker = Broker(settings.QUEUE)
- Downloads last month
- 4