commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 152 6.66k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
89fcf556d6b6086434ea961c19b770ffd3fdc7be | main.py | main.py | #!/usr/bin/env python
"""
This is the main file. The script finds the game window and sets up the
coordinates for each block.
The MIT License (MIT)
(c) 2016
"""
def main():
"""
No inputs
No outputs
Starts up the gameregionfinder
"""
if __name__ == "__main__":
main()
| #!/usr/bin/env python
"""
This is the main file. The script finds the game window and sets up the
coordinates for each block.
The MIT License (MIT)
(c) 2016
"""
import pyautogui, logging, time
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S')
# logging.d... | Add imports, logging configs, and authorship info | Add imports, logging configs, and authorship info
| Python | mit | hydrophilicsun/Automating-Minesweeper- | <REPLACE_OLD> 2016
"""
def <REPLACE_NEW> 2016
"""
import pyautogui, logging, time
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s.%(msecs)03d: %(message)s', datefmt='%H:%M:%S')
# logging.disable(logging.DEBUG) # uncomment to block debug log messages
__author__ = "Alex Flores Escarcega"
__copyright__ =... | Add imports, logging configs, and authorship info
#!/usr/bin/env python
"""
This is the main file. The script finds the game window and sets up the
coordinates for each block.
The MIT License (MIT)
(c) 2016
"""
def main():
"""
No inputs
No outputs
Starts up the gameregionfinder
"""
if __nam... |
f7caec9d0c0058b5d760992172b434b461f70d90 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service... | import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
assert service.is_enabled
def test_docker_service... | Remove test enforcing listening on port 1883 | Remove test enforcing listening on port 1883
| Python | mit | triplepoint/ansible-mosquitto | <DELETE> # listening on localhost, for tcp sockets on port 1883 (MQQT)
('tcp://127.0.0.1:1883'),
<DELETE_END> <|endoftext|> import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
... | Remove test enforcing listening on port 1883
import os
import pytest
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_docker_service_enabled(host):
service = host.service('docker')
asser... |
19ca3135add52010d4d171af79174033b7e7d680 | bluesky/tests/test_legacy_plans.py | bluesky/tests/test_legacy_plans.py | import pytest
import bluesky.plans as bp
def test_legacy_plan_names():
assert bp.outer_product_scan is bp.grid_scan
assert bp.relative_outer_product_scan is bp.rel_grid_scan
assert bp.relative_scan is bp.rel_scan
assert bp.relative_spiral is bp.rel_spiral
assert bp.relative_spiral_fermat is bp.rel_... | Add test to check for legacy plan names | TST: Add test to check for legacy plan names
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky | <INSERT> import pytest
import bluesky.plans as bp
def test_legacy_plan_names():
<INSERT_END> <INSERT> assert bp.outer_product_scan is bp.grid_scan
assert bp.relative_outer_product_scan is bp.rel_grid_scan
assert bp.relative_scan is bp.rel_scan
assert bp.relative_spiral is bp.rel_spiral
assert bp.rel... | TST: Add test to check for legacy plan names
| |
5f3b36bb11858a56bb6154ea5c77eff64e351386 | pombola/south_africa/management/commands/south_africa_export_constituency_offices.py | pombola/south_africa/management/commands/south_africa_export_constituency_offices.py | import csv
import sys
from django.core.management.base import BaseCommand, CommandError
from pombola.core.models import Organisation, OrganisationRelationship
MAPS_URL_TEMPLATE = 'https://www.google.com/maps/place/{lat}+{lon}/@{lat},{lon},17z'
def encode_row_values_to_utf8(row):
return {
k: unicode(v).e... | Add a command to output a CSV file of constituency offices | ZA: Add a command to output a CSV file of constituency offices
| Python | agpl-3.0 | geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola | <REPLACE_OLD> <REPLACE_NEW> import csv
import sys
from django.core.management.base import BaseCommand, CommandError
from pombola.core.models import Organisation, OrganisationRelationship
MAPS_URL_TEMPLATE = 'https://www.google.com/maps/place/{lat}+{lon}/@{lat},{lon},17z'
def encode_row_values_to_utf8(row):
ret... | ZA: Add a command to output a CSV file of constituency offices
| |
306e6939c5b369f4a4ef4bb4d16948dc1f027f53 | tests/test_initial_ismaster.py | tests/test_initial_ismaster.py | # Copyright 2015 MongoDB, 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, so... | # Copyright 2015 MongoDB, 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, so... | Update for PYTHON 985: MongoClient properties now block until connected. | Update for PYTHON 985: MongoClient properties now block until connected.
| Python | apache-2.0 | ajdavis/pymongo-mockup-tests | <REPLACE_OLD> self.assertIsNone(client.address)
server.receives('ismaster').ok()
<REPLACE_NEW> self.assertFalse(client.nodes)
server.receives('ismaster').ok(ismaster=True)
<REPLACE_END> <REPLACE_OLD> client.address is not None,
<REPLACE_NEW> client.nodes,
<REPLACE_END> <REPLACE_OLD> address', <REPLA... | Update for PYTHON 985: MongoClient properties now block until connected.
# Copyright 2015 MongoDB, 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/LIC... |
662101e89943fe62b7036894140272e2f9ea4f78 | ibmcnx/test/test.py | ibmcnx/test/test.py | import ibmcnx.test.loadFunction
loadFilesService()
FilesPolicyService.browse( "title", "true", 1, 25 )
| import ibmcnx.test.loadFunction
ibmcnx.test.loadFunction.loadFilesService()
FilesPolicyService.browse( "title", "true", 1, 25 )
| Customize scripts to work with menu | Customize scripts to work with menu
| Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | <REPLACE_OLD> ibmcnx.test.loadFunction
loadFilesService()
FilesPolicyService.browse( <REPLACE_NEW> ibmcnx.test.loadFunction
ibmcnx.test.loadFunction.loadFilesService()
FilesPolicyService.browse( <REPLACE_END> <|endoftext|> import ibmcnx.test.loadFunction
ibmcnx.test.loadFunction.loadFilesService()
FilesPolicyServ... | Customize scripts to work with menu
import ibmcnx.test.loadFunction
loadFilesService()
FilesPolicyService.browse( "title", "true", 1, 25 )
|
6beccf0c0b4e7788403415c05ae9f31e6c0a89eb | tests/test_gpa.py | tests/test_gpa.py | import unittest
import numpy as np
from sklearn import datasets
from sklearn import decomposition
from sklearn.utils import estimator_checks
import prince
class TestGPA(unittest.TestCase):
# def setUp(self):
def __init__(self):
# Create a list of 2-D circles with different locations and rotations
... | Add tests for Generalized Procrustes Analysis (GPA) | Add tests for Generalized Procrustes Analysis (GPA)
| Python | mit | MaxHalford/Prince | <REPLACE_OLD> <REPLACE_NEW> import unittest
import numpy as np
from sklearn import datasets
from sklearn import decomposition
from sklearn.utils import estimator_checks
import prince
class TestGPA(unittest.TestCase):
# def setUp(self):
def __init__(self):
# Create a list of 2-D circles with differ... | Add tests for Generalized Procrustes Analysis (GPA)
| |
316a6583036ca18cfdf1a95a122aa2367237fa2c | get/views.py | get/views.py | from django.shortcuts import render_to_response
from django.shortcuts import redirect
from models import DownloadLink
def index(request):
links = DownloadLink.objects.all()
context = {'links': list(links)}
return render_to_response('get/listing.tpl', context)
| from django.shortcuts import render_to_response
from django.shortcuts import redirect
from models import DownloadLink
def index(request):
links = DownloadLink.objects.order_by('-pk')
context = {'links': list(links)}
return render_to_response('get/listing.tpl', context)
| Order download links by pk. | get: Order download links by pk.
| Python | bsd-3-clause | ProgVal/Supybot-website | <REPLACE_OLD> DownloadLink.objects.all()
<REPLACE_NEW> DownloadLink.objects.order_by('-pk')
<REPLACE_END> <|endoftext|> from django.shortcuts import render_to_response
from django.shortcuts import redirect
from models import DownloadLink
def index(request):
links = DownloadLink.objects.order_by('-pk')
conte... | get: Order download links by pk.
from django.shortcuts import render_to_response
from django.shortcuts import redirect
from models import DownloadLink
def index(request):
links = DownloadLink.objects.all()
context = {'links': list(links)}
return render_to_response('get/listing.tpl', context)
|
f89d59d89af12473c609948bae518151a9adc64a | accelerator/migrations/0074_update_url_to_community.py | accelerator/migrations/0074_update_url_to_community.py | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRe... | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
community_url = "/community"
SiteRedirectPage = apps.get_model('accelerator', 'SiteRe... | Fix the query for updating the people and mentor urls to community url | [AC-9046] Fix the query for updating the people and mentor urls to community url
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | <REPLACE_OLD> for siteredirectpage in SiteRedirectPage.objects.all():
has_old_url = siteredirectpage.objects.filter(Q(new_url=people_url)| Q(new_url=mentor_url))
if has_old_url.exists():
has_old_url.update(new_url=community_url)
<REPLACE_NEW> SiteRedirectPage.objects.filter(Q(new_url=people_url)| Q(new_u... | [AC-9046] Fix the query for updating the people and mentor urls to community url
# Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = "/people"
mentor_url = "/directory"
commu... |
b1a33b1a89c00ee6de7949c529ecd4bcf2d38578 | python/helper/asset_loading.py | python/helper/asset_loading.py | # Defining a function to load images
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:... | # Defining a function to load images
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:... | Fix error in file path of where images are loaded from in load_image() | Fix error in file path of where images are loaded from in load_image()
| Python | mit | AndyDeany/pygame-template | <REPLACE_OLD> "Image Files\\",
<REPLACE_NEW> "assets\\images\\",
<REPLACE_END> <REPLACE_OLD> "Image Files\\",
<REPLACE_NEW> "assets\\images\\",
<REPLACE_END> <|endoftext|> # Defining a function to load images
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be... | Fix error in file path of where images are loaded from in load_image()
# Defining a function to load images
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# de... |
60de17292159deb590de6e5c9c2a45f1b95b0094 | girder/app/app/__init__.py | girder/app/app/__init__.py | from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import GirderPlugin
@setting_utilities.validator... | from .configuration import Configuration
from girder.api.rest import Resource
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .launch_taskflow import launch_taskflow
from .user import get_orcid, set_orcid, get_twitter, set_twitter
from girder.plugin import Girde... | Put the endpoint at /launch_taskflow/launch | Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
| Python | bsd-3-clause | OpenChemistry/mongochemserver | <INSERT> girder.api.rest import Resource
from <INSERT_END> <REPLACE_OLD> info['apiRoot'].queues.route('POST', ('launchtaskflow',), <REPLACE_NEW> info['apiRoot'].launch_taskflow = Resource()
info['apiRoot'].launch_taskflow.route('POST', ('launch',), <REPLACE_END> <|endoftext|> from .configuration import Configur... | Put the endpoint at /launch_taskflow/launch
Put it here instead of under "queues"
Signed-off-by: Patrick Avery <743342299f279e7a8c3ff5eb40671fce3e95f13a@kitware.com>
from .configuration import Configuration
from girder.utility import setting_utilities
from .constants import Features, Branding, Deployment
from .laun... |
9108add7219d3d70ff0aab86c13cd4077cda6619 | setup.py | setup.py | from setuptools import setup
setup(
name='ingreedypy',
py_modules=['ingreedypy'],
version='1.3.2',
description='ingreedy-py parses recipe ingredient lines into a object',
author='Scott Cooper',
author_email='scttcper@gmail.com',
url='https://github.com/openculinary/ingreedy-py',
keywor... | from setuptools import setup
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
setup(
name='ingreedypy',
py_modules=['ingreedypy'],
version='1.3.2',
description='ingreedy-py parses recipe ingredient lines into a object',
long_description=long_description,
l... | Add long description for package | Add long description for package
| Python | mit | scttcper/ingreedy-py | <REPLACE_OLD> setup
setup(
<REPLACE_NEW> setup
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
setup(
<REPLACE_END> <INSERT> long_description=long_description,
long_description_content_type='text/markdown',
<INSERT_END> <|endoftext|> from setuptools import setup
wit... | Add long description for package
from setuptools import setup
setup(
name='ingreedypy',
py_modules=['ingreedypy'],
version='1.3.2',
description='ingreedy-py parses recipe ingredient lines into a object',
author='Scott Cooper',
author_email='scttcper@gmail.com',
url='https://github.com/ope... |
3c7c72ea00a7009e53cdd0404b35b887b6fb4e9e | setup.py | setup.py | from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.a... | from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.1'],
license='http://www.a... | Set version number to 0.7.0. | Set version number to 0.7.0.
| Python | apache-2.0 | STANAPO/slacker,techartorg/slacker,wkentaro/slacker,kashyap32/slacker,os/slacker,wasabi0522/slacker,hreeder/slacker | <REPLACE_OLD> version='0.6.8',
<REPLACE_NEW> version='0.7.0',
<REPLACE_END> <|endoftext|> from setuptools import setup
setup(
name='slacker',
version='0.7.0',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://gi... | Set version number to 0.7.0.
from setuptools import setup
setup(
name='slacker',
version='0.6.8',
packages=['slacker'],
description='Slack API client',
author='Oktay Sancak',
author_email='oktaysancak@gmail.com',
url='http://github.com/os/slacker/',
install_requires=['requests >= 2.2.... |
49bf8bd8137928a1dc5165f38f8abfe423f5e7f0 | pi_director/controllers/user_controls.py | pi_director/controllers/user_controls.py | from pyramid.response import Response
from pi_director.models.models import (
DBSession,
MyModel,
)
from pi_director.models.UserModel import UserModel
def authorize_user(email):
user=DBSession.query(UserModel).filter(UserModel.email==email).one()
user.AccessLevel=2
DBSession.flush()
def delet... | from pyramid.response import Response
from pi_director.models.models import (
DBSession,
MyModel,
)
from pi_director.models.UserModel import UserModel
def authorize_user(email):
user=DBSession.query(UserModel).filter(UserModel.email==email).one()
user.AccessLevel=2
DBSession.flush()
def delet... | Create the user if it isn't already in the database first, then make it an admin. | Create the user if it isn't already in the database first, then make it an admin.
| Python | mit | selfcommit/pi_director,PeterGrace/pi_director,selfcommit/pi_director,PeterGrace/pi_director,PeterGrace/pi_director,selfcommit/pi_director | <INSERT> if user == None:
user=UserModel()
user.email=email
DBSession.add(user)
<INSERT_END> <|endoftext|> from pyramid.response import Response
from pi_director.models.models import (
DBSession,
MyModel,
)
from pi_director.models.UserModel import UserModel
def authorize_user(e... | Create the user if it isn't already in the database first, then make it an admin.
from pyramid.response import Response
from pi_director.models.models import (
DBSession,
MyModel,
)
from pi_director.models.UserModel import UserModel
def authorize_user(email):
user=DBSession.query(UserModel).filter(Us... |
51c65f37ea5f0d2cd98de8e63f541d533e1f8a65 | setup.py | setup.py | #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-paginationlinks',
version='0.1.1',
description='Django Pagination Links',
long_description=readme,
url='https://github.... | #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-paginationlinks',
version='0.1.1',
description='Django Pagination Links',
long_description=readme,
url='https://github.... | Update GitHub repos from blancltd to developersociety | Update GitHub repos from blancltd to developersociety
| Python | bsd-3-clause | blancltd/django-paginationlinks | <REPLACE_OLD> url='https://github.com/blancltd/django-paginationlinks',
<REPLACE_NEW> url='https://github.com/developersociety/django-paginationlinks',
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
... | Update GitHub repos from blancltd to developersociety
#!/usr/bin/env python
from codecs import open
from setuptools import find_packages, setup
with open('README.rst', 'r', 'utf-8') as f:
readme = f.read()
setup(
name='django-paginationlinks',
version='0.1.1',
description='Django Pagination Links'... |
48b1cfaadd7642706a576d8ba9bf38c297a2d873 | runtests.py | runtests.py | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ALLOWED_HOSTS=[
'testserver',
],
INSTALLED_APPS=[
... | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ALLOWED_HOSTS=[
'testserver',
],
INSTALLED_APPS=[
... | Add MIDDLEWARE_CLASSES to test settings | Add MIDDLEWARE_CLASSES to test settings
Squelches a warning when using Django 1.7.
| Python | mit | PSU-OIT-ARC/django-perms,wylee/django-perms | <INSERT> MIDDLEWARE_CLASSES=[],
<INSERT_END> <|endoftext|> #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ALLOWED_... | Add MIDDLEWARE_CLASSES to test settings
Squelches a warning when using Django 1.7.
#!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
... |
d7387869c4500c4ddf8df728007cbc1f09dc767f | migrations/versions/0341_new_letter_rates.py | migrations/versions/0341_new_letter_rates.py | """
Revision ID: 0341_new_letter_rates
Revises: 0340_stub_training_broadcasts
Create Date: 2021-01-27 11:58:21.393227
"""
import itertools
import uuid
from datetime import datetime
from alembic import op
from sqlalchemy.sql import text
from app.models import LetterRate
revision = '0341_new_letter_rates'
down_revi... | Add February 2021 letter rates | Add February 2021 letter rates
All rates are changing, so we add an end date for the current rates and
insert new rates for every post_class, sheet count and crown status.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | <REPLACE_OLD> <REPLACE_NEW> """
Revision ID: 0341_new_letter_rates
Revises: 0340_stub_training_broadcasts
Create Date: 2021-01-27 11:58:21.393227
"""
import itertools
import uuid
from datetime import datetime
from alembic import op
from sqlalchemy.sql import text
from app.models import LetterRate
revision = '034... | Add February 2021 letter rates
All rates are changing, so we add an end date for the current rates and
insert new rates for every post_class, sheet count and crown status.
| |
8ea996de13e1ad3c9865866385fa0ecb49d6cbca | tests/help_test.py | tests/help_test.py | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
python_path ... | from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = os.path.dirname(mopidy.__file__)
args = [sys.executable, mopidy_dir, '--help']
process = su... | Revert "tests: Don't redefine PYTHONPATH" | Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.
| Python | apache-2.0 | jodal/mopidy,adamcik/mopidy,mokieyue/mopidy,jcass77/mopidy,glogiotatidis/mopidy,diandiankan/mopidy,bencevans/mopidy,quartz55/mopidy,dbrgn/mopidy,abarisain/mopidy,swak/mopidy,rawdlite/mopidy,jcass77/mopidy,ZenithDK/mopidy,mopidy/mopidy,bacontext/mopidy,diandiankan/mopidy,jodal/mopidy,diandiankan/mopidy,ali/mopidy,swak/m... | <DELETE> python_path = sys.path[:]
python_path.insert(0, os.path.join(mopidy_dir, '..'))
<DELETE_END> <REPLACE_OLD> ':'.join(python_path)},
<REPLACE_NEW> os.path.join(mopidy_dir, '..')},
<REPLACE_END> <|endoftext|> from __future__ import unicode_literals
import os
import subprocess
import sys
import ... | Revert "tests: Don't redefine PYTHONPATH"
This reverts commit 6be5cc0f1b1d34521fa8d8c91ca1cc2a96a65b69.
from __future__ import unicode_literals
import os
import subprocess
import sys
import unittest
import mopidy
class HelpTest(unittest.TestCase):
def test_help_has_mopidy_options(self):
mopidy_dir = o... |
bb70a98437c87fa5b9677716acbcbd948d93f982 | tests/syft/grid/messages/setup_msg_test.py | tests/syft/grid/messages/setup_msg_test.py | # syft absolute
import syft as sy
from syft.core.io.address import Address
from syft.grid.messages.setup_messages import CreateInitialSetUpMessage
from syft.grid.messages.setup_messages import CreateInitialSetUpResponse
from syft.grid.messages.setup_messages import GetSetUpMessage
from syft.grid.messages.setup_messages... | ADD PyGrid SetupService message tests | ADD PyGrid SetupService message tests
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | <REPLACE_OLD> <REPLACE_NEW> # syft absolute
import syft as sy
from syft.core.io.address import Address
from syft.grid.messages.setup_messages import CreateInitialSetUpMessage
from syft.grid.messages.setup_messages import CreateInitialSetUpResponse
from syft.grid.messages.setup_messages import GetSetUpMessage
from syft... | ADD PyGrid SetupService message tests
| |
729d3160f974c521ab6605c02cf64861be0fb6ab | fri/utils.py | fri/utils.py | import numpy as np
def distance(u, v):
"""
Distance measure custom made for feature comparison.
Parameters
----------
u: first feature
v: second feature
Returns
-------
"""
u = np.asarray(u)
v = np.asarray(v)
# Euclidean differences
diff = (u - v) ** 2
# Null... | import numpy as np
def distance(u, v):
"""
Distance measure custom made for feature comparison.
Parameters
----------
u: first feature
v: second feature
Returns
-------
"""
u = np.asarray(u)
v = np.asarray(v)
# Euclidean differences
diff = (u - v) ** 2
# Null... | Revert removal of necessary function | Revert removal of necessary function
| Python | mit | lpfann/fri | <REPLACE_OLD> np.sqrt(np.sum(diff))
<REPLACE_NEW> np.sqrt(np.sum(diff))
def permutate_feature_in_data(data, feature_i, random_state):
X, y = data
X_copy = np.copy(X)
# Permute selected feature
permutated_feature = random_state.permutation(X_copy[:, feature_i])
# Add permutation back to dataset
... | Revert removal of necessary function
import numpy as np
def distance(u, v):
"""
Distance measure custom made for feature comparison.
Parameters
----------
u: first feature
v: second feature
Returns
-------
"""
u = np.asarray(u)
v = np.asarray(v)
# Euclidean differen... |
06dd6fb991a9f68eea99d5943498688daa0b09c2 | tests/test_interaction.py | tests/test_interaction.py | import numpy.testing as npt
import pandas as pd
import pandas.util.testing as pdt
import pytest
from .. import interaction as inter
@pytest.fixture
def choosers():
return pd.DataFrame(
{'var1': range(5, 10),
'thing_id': ['a', 'c', 'e', 'g', 'i']})
@pytest.fixture
def alternatives():
return... | import numpy.testing as npt
import pandas as pd
import pandas.util.testing as pdt
import pytest
from .. import interaction as inter
@pytest.fixture
def choosers():
return pd.DataFrame(
{'var1': range(5, 10),
'thing_id': ['a', 'c', 'e', 'g', 'i']})
@pytest.fixture
def alternatives():
return... | Return DCM probabilities as MultiIndexed Series | Return DCM probabilities as MultiIndexed Series
Instead of separately returning probabilities and alternatives
information this groups them all together.
The probabilities have a MultiIndex with chooser IDs on the
outside and alternative IDs on the inside.
| Python | bsd-3-clause | UDST/choicemodels,UDST/choicemodels | <INSERT> assert merged['join_index'].isin(choosers.index).all()
<INSERT_END> <|endoftext|> import numpy.testing as npt
import pandas as pd
import pandas.util.testing as pdt
import pytest
from .. import interaction as inter
@pytest.fixture
def choosers():
return pd.DataFrame(
{'var1': range(5, 10),
... | Return DCM probabilities as MultiIndexed Series
Instead of separately returning probabilities and alternatives
information this groups them all together.
The probabilities have a MultiIndex with chooser IDs on the
outside and alternative IDs on the inside.
import numpy.testing as npt
import pandas as pd
import pandas... |
f670fabfecb6dbcf2ce5bcc3e312d61064463820 | tests/test_utils.py | tests/test_utils.py | # -*- coding: utf-8 -*-
"""
colorful
~~~~~~~~
Terminal string styling done right, in Python.
:copyright: (c) 2017 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import os
import pytest
# do not overwrite module
os.environ['COLORFUL_NO_MODULE_OVERWRITE'] = '... | Add tests for utils module | Add tests for utils module
| Python | mit | timofurrer/colorful | <INSERT> # -*- coding: utf-8 -*-
"""
<INSERT_END> <INSERT> colorful
~~~~~~~~
Terminal string styling done right, in Python.
:copyright: (c) 2017 by Timo Furrer <tuxtimo@gmail.com>
:license: MIT, see LICENSE for more details.
"""
import os
import pytest
# do not overwrite module
os.environ['COLO... | Add tests for utils module
| |
f9abd5434dded655591029ae45859e8608b4e5d6 | django_facebook/decorators.py | django_facebook/decorators.py | from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def facebook_required(function=None, redirect_field_name=REDIRECT... | from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def facebook_required(function=None, redirect_field_name=REDIRECT... | Fix possible problem with middleware | Fix possible problem with middleware
| Python | mit | tino/django-facebook2,srijanmishra/django-facebook,aidanlister/django-facebook,tino/django-facebook2,vstoykov/django4facebook | <REPLACE_OLD> r.facebook.uid,
<REPLACE_NEW> r.facebook,
<REPLACE_END> <|endoftext|> from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http impo... | Fix possible problem with middleware
from functools import update_wrapper, wraps
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def facebook_required(funct... |
505671b698490918fe0ea6c6dfdab8c0b25339be | tests/basics/subclass_native_containment.py | tests/basics/subclass_native_containment.py | # test containment operator on subclass of a native type
class mylist(list):
pass
class mydict(dict):
pass
class mybytes(bytes):
pass
l = mylist([1, 2, 3])
print(0 in l)
print(1 in l)
d = mydict({1:1, 2:2})
print(0 in l)
print(1 in l)
b = mybytes(b'1234')
print(0 in b)
print(b'1' in b)
| Add test for containment of a subclass of a native type. | tests/basics: Add test for containment of a subclass of a native type.
| Python | mit | MrSurly/micropython,dmazzella/micropython,infinnovation/micropython,bvernoux/micropython,selste/micropython,pfalcon/micropython,bvernoux/micropython,pozetroninc/micropython,kerneltask/micropython,torwag/micropython,infinnovation/micropython,ryannathans/micropython,pfalcon/micropython,swegener/micropython,dmazzella/micr... | <INSERT> # test containment operator on subclass of a native type
class mylist(list):
<INSERT_END> <INSERT> pass
class mydict(dict):
pass
class mybytes(bytes):
pass
l = mylist([1, 2, 3])
print(0 in l)
print(1 in l)
d = mydict({1:1, 2:2})
print(0 in l)
print(1 in l)
b = mybytes(b'1234')
print(0 in b)
pr... | tests/basics: Add test for containment of a subclass of a native type.
| |
c81670e3ab8b5dcedc37def3a10803dde9b7c8b1 | devicehive/transports/base_transport.py | devicehive/transports/base_transport.py | class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.d... | class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.d... | Remove action from required params | Remove action from required params
| Python | apache-2.0 | devicehive/devicehive-python | <DELETE> action, <DELETE_END> <DELETE> action, <DELETE_END> <|endoftext|> class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_... | Remove action from required params
class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
s... |
5f409fd075e1bf4d4d58cb280f25761965f6a446 | url_shortener/__main__.py | url_shortener/__main__.py | # -*- coding: utf-8 -*-
from url_shortener import app, custom_config_loaded, views
log_file = app.config['LOG_FILE']
if not app.debug and log_file is not None:
import logging
from logging.handlers import TimedRotatingFileHandler
file_handler = TimedRotatingFileHandler(log_file, when='d')
file_handler.... | # -*- coding: utf-8 -*-
from url_shortener import app, views
from url_shortener.validation import configure_url_validator
from url_shortener.models import configure_random_factory
log_file = app.config['LOG_FILE']
if not app.debug and log_file is not None:
import logging
from logging.handlers import TimedRota... | Refactor applying custom configuration after it is loaded | Refactor applying custom configuration after it is loaded
The call sending custom_config_loaded is being replaced with direct
calls to the functions configure_random_factory and configure_url_validator.
| Python | mit | piotr-rusin/url-shortener,piotr-rusin/url-shortener | <REPLACE_OLD> custom_config_loaded, views
log_file <REPLACE_NEW> views
from url_shortener.validation import configure_url_validator
from url_shortener.models import configure_random_factory
log_file <REPLACE_END> <REPLACE_OLD> app.logger.addHandler(file_handler)
app.config.from_envvar('URL_SHORTENER_CONFIGURATION')
... | Refactor applying custom configuration after it is loaded
The call sending custom_config_loaded is being replaced with direct
calls to the functions configure_random_factory and configure_url_validator.
# -*- coding: utf-8 -*-
from url_shortener import app, custom_config_loaded, views
log_file = app.config['LOG_FILE... |
f26e8927f83c3a897d4f474762bca9775467e74e | src/helpers/vyos-load-config.py | src/helpers/vyos-load-config.py | #!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program is distributed in the hope t... | Rewrite the config load script | T1424: Rewrite the config load script
Rewrite of the load functionality of vyatta-load-config.pl, removing the
dependency on Vyatta::Config.
| Python | lgpl-2.1 | vyos/vyos-1x,vyos/vyos-1x,vyos/vyos-1x,vyos/vyos-1x | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python3
#
# Copyright (C) 2019 VyOS maintainers and contributors
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 or later as
# published by the Free Software Foundation.
#
# This program... | T1424: Rewrite the config load script
Rewrite of the load functionality of vyatta-load-config.pl, removing the
dependency on Vyatta::Config.
| |
7eff20d706eb35513d8d1f420e59879e80400417 | pseudon/ast_translator.py | pseudon/ast_translator.py | from ast import AST
import yaml
class ASTTranslator:
def __init__(self, tree):
self.tree = tree
def translate(self):
return yaml.dump({'type': 'program', 'code': []})
| import ast
import yaml
class ASTTranslator:
def __init__(self, tree):
self.tree = tree
def translate(self):
return yaml.dump(self._translate_node(self.tree))
def _translate_node(self, node):
if isinstance(node, ast.AST):
return getattr('_translate_%s' % type(node).__... | Add a basic ast translator | Add a basic ast translator
| Python | mit | alehander42/pseudo-python | <DELETE> from ast <DELETE_END> <REPLACE_OLD> AST
import <REPLACE_NEW> ast
import <REPLACE_END> <REPLACE_OLD> yaml.dump({'type': <REPLACE_NEW> yaml.dump(self._translate_node(self.tree))
def _translate_node(self, node):
if isinstance(node, ast.AST):
return getattr('_translate_%s' % type(node).__n... | Add a basic ast translator
from ast import AST
import yaml
class ASTTranslator:
def __init__(self, tree):
self.tree = tree
def translate(self):
return yaml.dump({'type': 'program', 'code': []})
|
9b6a22a9cb908d1fbfa5f9b5081f6c96644115b0 | tests/test_tags.py | tests/test_tags.py |
from unittest import TestCase
from django.test.utils import setup_test_template_loader, override_settings
from django.template import Context
from django.template.loader import get_template
TEMPLATES = {
'basetag': '''{% load damn %}{% assets %}''',
'test2': '''
<!doctype html>{% load damn %}
<html>
<head>
{%... |
#from unittest import TestCase
from django.test import TestCase
from django.test.utils import setup_test_template_loader, override_settings
from django.template import Context
from django.template.loader import get_template
TEMPLATES = {
'basetag': '''{% load damn %}{% assets %}''',
'test2': '''
<!doctype ht... | Use TestCase from Django Set STATIC_URL | Use TestCase from Django
Set STATIC_URL
| Python | bsd-2-clause | funkybob/django-amn | <REPLACE_OLD>
from <REPLACE_NEW>
#from <REPLACE_END> <INSERT> django.test import TestCase
from <INSERT_END> <REPLACE_OLD> 'class': <REPLACE_NEW> 'processor': <REPLACE_END> <INSERT> STATIC_URL = '/',
<INSERT_END> <INSERT> STATIC_URL = '/',
<INSERT_END> <REPLACE_OLD> self.assertContains(o, '<script src... | Use TestCase from Django
Set STATIC_URL
from unittest import TestCase
from django.test.utils import setup_test_template_loader, override_settings
from django.template import Context
from django.template.loader import get_template
TEMPLATES = {
'basetag': '''{% load damn %}{% assets %}''',
'test2': '''
<!doct... |
bd8fdf1dccc3660be3b8e020a637f94d21dc2b3a | gaphas/tests/test_state.py | gaphas/tests/test_state.py | from builtins import object
import unittest
from gaphas.state import reversible_pair, observed, _reverse
class SList(object):
def __init__(self):
self.l = list()
def add(self, node, before=None):
if before: self.l.insert(self.l.index(before), node)
else: self.l.append(node)
add = o... | from builtins import object
import unittest
from gaphas.state import reversible_pair, observed, _reverse
class SList(object):
def __init__(self):
self.l = list()
def add(self, node, before=None):
if before: self.l.insert(self.l.index(before), node)
else: self.l.append(node)
add = o... | Fix function object has no attribute __func__ | Fix function object has no attribute __func__
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphas | <REPLACE_OLD> self.assertTrue(SList.add.__func__ <REPLACE_NEW> self.assertTrue(SList.add <REPLACE_END> <REPLACE_OLD> self.assertTrue(SList.remove.__func__ <REPLACE_NEW> self.assertTrue(SList.remove <REPLACE_END> <|endoftext|> from builtins import object
import unittest
from gaphas.state import reversible_pair, observe... | Fix function object has no attribute __func__
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
from builtins import object
import unittest
from gaphas.state import reversible_pair, observed, _reverse
class SList(object):
def __init__(self):
self.l = list()
def add(self, nod... |
cc9bfdb3185c2fbb6c7d0f6f2cb8b36f8e5024ed | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://w... | #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://w... | Revert use of bintrees; it's not a great fit. | Revert use of bintrees; it's not a great fit.
| Python | apache-2.0 | yossigo/mockredis,matejkloska/mockredis,path/mockredis,locationlabs/mockredis,optimizely/mockredis | <DELETE> 'bintrees==1.0.1'
<DELETE_END> <|endoftext|> #!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __bui... | Revert use of bintrees; it's not a great fit.
#!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __build__,
descr... |
470b7313fa9b176fa4492ac9f355acd21542265d | tests/test_lib_fallback.py | tests/test_lib_fallback.py | from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invali... | from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patc... | Test library fallback is overridden by setting a library | Test library fallback is overridden by setting a library
| Python | mit | wintersandroid/tvrenamr,ghickman/tvrenamr | <INSERT> tvrenamr.libraries import TheTvDb, TvRage
from <INSERT_END> <REPLACE_OLD> Deficiency'
<REPLACE_NEW> Deficiency'
def test_setting_library_stops_fallback(self):
libraries = self.tv._get_libraries('thetvdb')
assert type(libraries) == list
assert len(libraries) == 1
assert lib... | Test library fallback is overridden by setting a library
from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest)... |
6dab43543e1b6a1e1e8119db9b38cc685dd81f82 | ckanext/qa/controllers/base.py | ckanext/qa/controllers/base.py | from ckan.lib.base import BaseController
from pylons import config
class QAController(BaseController):
def __init__(self, *args, **kwargs):
super(QAController, self).__init(*args, **kwargs) | from ckan.lib.base import BaseController
from pylons import config
class QAController(BaseController):
pass
| Fix typo in constructor. Seems unnecessary anyway. | Fix typo in constructor. Seems unnecessary anyway.
| Python | mit | ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa | <REPLACE_OLD> QAController(BaseController):
<REPLACE_NEW> QAController(BaseController):
<REPLACE_END> <REPLACE_OLD> def __init__(self, *args, **kwargs):
super(QAController, self).__init(*args, **kwargs) <REPLACE_NEW> pass
<REPLACE_END> <|endoftext|> from ckan.lib.base import BaseController
from pylons impor... | Fix typo in constructor. Seems unnecessary anyway.
from ckan.lib.base import BaseController
from pylons import config
class QAController(BaseController):
def __init__(self, *args, **kwargs):
super(QAController, self).__init(*args, **kwargs) |
341dcac3331a21c1b747075ab73601cb08d4868d | compliance_checker/tests/helpers.py | compliance_checker/tests/helpers.py | from netCDF4 import Dataset
import tempfile
class MockNetCDF(Dataset):
"""
Wrapper object around NetCDF Dataset to write data only to memory.
"""
def __init__(self):
# taken from test/tst_diskless.py NetCDF library
# even though we aren't persisting data to disk, the constructor
... | from netCDF4 import Dataset
import tempfile
class MockNetCDF(Dataset):
"""
Wrapper object around NetCDF Dataset to write data only to memory.
"""
def __init__(self):
# taken from test/tst_diskless.py NetCDF library
# even though we aren't persisting data to disk, the constructor
... | Add name and dimensions attributes to MockVariable class | Add name and dimensions attributes to MockVariable class
| Python | apache-2.0 | DanielJMaher/compliance-checker,aodn/compliance-checker,ioos/compliance-checker,lukecampbell/compliance-checker,ocefpaf/compliance-checker | <INSERT> self.name = copy_var.name
self.dimensions = copy_var.dimensions
<INSERT_END> <|endoftext|> from netCDF4 import Dataset
import tempfile
class MockNetCDF(Dataset):
"""
Wrapper object around NetCDF Dataset to write data only to memory.
"""
def __init__(self):
# ta... | Add name and dimensions attributes to MockVariable class
from netCDF4 import Dataset
import tempfile
class MockNetCDF(Dataset):
"""
Wrapper object around NetCDF Dataset to write data only to memory.
"""
def __init__(self):
# taken from test/tst_diskless.py NetCDF library
# even though... |
274511db02b95c14c19564d1e0b3d30ccf1bf532 | core/migrations/0011_auto_20150602_0128.py | core/migrations/0011_auto_20150602_0128.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0010_currentrate'),
]
operations = [
migrations.AlterModelOptions(
name='price',
options={'o... | Add migration for meta options | Add migration for meta options
| Python | unlicense | kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no,kvikshaug/btc.kvikshaug.no | <INSERT> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
<INSERT_END> <INSERT> dependencies = [
('core', '0010_currentrate'),
]
operations = [
migrations.AlterModelOptions(
name='p... | Add migration for meta options
| |
c267818a28018a6f386c6f4d11eefc9987efe7bd | py/find-mode-in-binary-search-tree.py | py/find-mode-in-binary-search-tree.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inOrder(self, cur):
if cur:
for x in self.inOrder(cur.left):
yield x
... | Add py solution for 501. Find Mode in Binary Search Tree | Add py solution for 501. Find Mode in Binary Search Tree
501. Find Mode in Binary Search Tree: https://leetcode.com/problems/find-mode-in-binary-search-tree/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | <REPLACE_OLD> <REPLACE_NEW> # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def inOrder(self, cur):
if cur:
for x in self.inOrder(cur.left):
... | Add py solution for 501. Find Mode in Binary Search Tree
501. Find Mode in Binary Search Tree: https://leetcode.com/problems/find-mode-in-binary-search-tree/
| |
c8bf52d51a5cc678160add7db937ed92aaa6bb09 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
... | from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
'psqlgraph',
'gdcdictionary',
'cdisutils',
'python-dateutil==2.4.2',
],
... | Update to point to release/horton | chore(pins): Update to point to release/horton
- Update to point to release/horton of gdcdictionary
| Python | apache-2.0 | NCI-GDC/gdcdatamodel,NCI-GDC/gdcdatamodel | <REPLACE_OLD> 'git+https://github.com/NCI-GDC/gdcdictionary.git@86a4e6dd7b78d50ec17dc4bcdd1a3d25c658b88b#egg=gdcdictionary',
<REPLACE_NEW> 'git+https://github.com/NCI-GDC/gdcdictionary.git@release/horton#egg=gdcdictionary',
<REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
setup(
name='gdcd... | chore(pins): Update to point to release/horton
- Update to point to release/horton of gdcdictionary
from setuptools import setup, find_packages
setup(
name='gdcdatamodel',
packages=find_packages(),
install_requires=[
'pytz==2016.4',
'graphviz==0.4.2',
'jsonschema==2.5.1',
... |
afa94ea297c6042f4444c0ce833c9b1ee02373c1 | stowaway.py | stowaway.py | import time
import socket
import datetime
from ipaddress import ip_address
import zmq
import yaml
import quick2wire.i2c as i2c
from database import Writer
from database import Temperature, Base
if __name__ == '__main__':
context = zmq.Context()
publisher = context.socket(zmq.PUB)
database = context.soc... | import time
import socket
import datetime
from ipaddress import ip_address
import zmq
import yaml
import quick2wire.i2c as i2c
from database import Writer
from database import Temperature, Base
if __name__ == '__main__':
context = zmq.Context()
publisher = context.socket(zmq.PUB)
database = context.soc... | Send timestamp to the outside world | Send timestamp to the outside world
| Python | bsd-3-clause | CojoCompany/stowaway | <REPLACE_OLD> now, <REPLACE_NEW> now.timestamp(), <REPLACE_END> <|endoftext|> import time
import socket
import datetime
from ipaddress import ip_address
import zmq
import yaml
import quick2wire.i2c as i2c
from database import Writer
from database import Temperature, Base
if __name__ == '__main__':
context = zm... | Send timestamp to the outside world
import time
import socket
import datetime
from ipaddress import ip_address
import zmq
import yaml
import quick2wire.i2c as i2c
from database import Writer
from database import Temperature, Base
if __name__ == '__main__':
context = zmq.Context()
publisher = context.socke... |
dea4ed78fef278c2cb87b052c98a67940339835a | tagalog/_compat.py | tagalog/_compat.py | try:
from urlparse import urlparse
except ImportError: # Python3
from urllib import parse as urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
| try:
from urlparse import urlparse
except ImportError: # Python3
from urllib.parse import urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
| Fix compat module for Python 3 | Fix compat module for Python 3
| Python | mit | nickstenning/tagalog,alphagov/tagalog,alphagov/tagalog,nickstenning/tagalog | <REPLACE_OLD> urllib <REPLACE_NEW> urllib.parse <REPLACE_END> <DELETE> parse as <DELETE_END> <|endoftext|> try:
from urlparse import urlparse
except ImportError: # Python3
from urllib.parse import urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
| Fix compat module for Python 3
try:
from urlparse import urlparse
except ImportError: # Python3
from urllib import parse as urlparse
try:
_xrange = xrange
except NameError:
_xrange = range
|
f6fabf476e49d0d857217c428ed2ad1af7f034cd | candidates/management/commands/candidates_delete_everything_from_popit.py | candidates/management/commands/candidates_delete_everything_from_popit.py | import json
from candidates.models import PopItPerson
from candidates.popit import PopItApiMixin, get_base_url
from django.core.management.base import BaseCommand
class Command(PopItApiMixin, BaseCommand):
def handle(self, **options):
message = "WARNING: this will delete all people, posts, " \
... | Add a command to delete all objects from PopIt | Add a command to delete all objects from PopIt
| Python | agpl-3.0 | YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,YoQuieroSaber/yournextrepresentative,neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextrepres... | <REPLACE_OLD> <REPLACE_NEW> import json
from candidates.models import PopItPerson
from candidates.popit import PopItApiMixin, get_base_url
from django.core.management.base import BaseCommand
class Command(PopItApiMixin, BaseCommand):
def handle(self, **options):
message = "WARNING: this will delete all... | Add a command to delete all objects from PopIt
| |
6a9193fdc43361ca12b7f22d18954d17c2049ba1 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name = 'CommonModules',
packages = find_packages(where = '.'), # this must be the same as the name above
version = '0.1.11',
description = 'Common Python modules/functionalities used in practice.',
author = 'Wang Hewen',
author_email = 'w... | from setuptools import setup, find_packages
setup(
name = 'CommonModules',
packages = find_packages(where = '.'), # this must be the same as the name above
version = '0.1.13',
description = 'Common Python modules/functionalities used in practice.',
author = 'Wang Hewen',
author_email = 'w... | Fix version number. Will check the file in another machine and fix the conflict | Fix version number. Will check the file in another machine and fix the conflict
| Python | mit | wanghewen/CommonModules | <REPLACE_OLD> '0.1.11',
<REPLACE_NEW> '0.1.13',
<REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
setup(
name = 'CommonModules',
packages = find_packages(where = '.'), # this must be the same as the name above
version = '0.1.13',
description = 'Common Python modules/functi... | Fix version number. Will check the file in another machine and fix the conflict
from setuptools import setup, find_packages
setup(
name = 'CommonModules',
packages = find_packages(where = '.'), # this must be the same as the name above
version = '0.1.11',
description = 'Common Python modules/funct... |
e8fc301de8fab1d9dfcb99aa94e7c4467dab689a | amy/workshops/migrations/0223_membership_agreement_link.py | amy/workshops/migrations/0223_membership_agreement_link.py | # Generated by Django 2.2.13 on 2020-11-18 20:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0222_workshoprequest_workshop_listed'),
]
operations = [
migrations.AddField(
model_name='membership',
... | # Generated by Django 2.2.17 on 2020-11-29 10:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0222_workshoprequest_workshop_listed'),
]
operations = [
migrations.AddField(
model_name='membership',
... | Update help text in migration | Update help text in migration
| Python | mit | swcarpentry/amy,pbanaszkiewicz/amy,swcarpentry/amy,pbanaszkiewicz/amy,swcarpentry/amy,pbanaszkiewicz/amy | <REPLACE_OLD> 2.2.13 <REPLACE_NEW> 2.2.17 <REPLACE_END> <REPLACE_OLD> 2020-11-18 20:58
from <REPLACE_NEW> 2020-11-29 10:58
from <REPLACE_END> <INSERT> document <INSERT_END> <|endoftext|> # Generated by Django 2.2.17 on 2020-11-29 10:58
from django.db import migrations, models
class Migration(migrations.Migration):... | Update help text in migration
# Generated by Django 2.2.13 on 2020-11-18 20:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0222_workshoprequest_workshop_listed'),
]
operations = [
migrations.AddField(
model... |
04a738253bbd0018784ce6ad81480b38a61b006f | etc/bin/xcode_bots/testflight/before_integration.py | etc/bin/xcode_bots/testflight/before_integration.py | # This script should be copied into the Run Script trigger of an Xcode Bot
# Utilizes `cavejohnson` for Xcode Bot scripting
# https://github.com/drewcrawford/CaveJohnson
#!/bin/bash
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH
# Set unique Build Number prior to TestFlight upload
cavejohnson setBu... | # This script should be copied into the Run Script trigger of an Xcode Bot
# Utilizes `cavejohnson` for Xcode Bot scripting
# https://github.com/drewcrawford/CaveJohnson
#!/bin/bash
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH
# Set unique Build Number prior to TestFlight upload
cavejohnson setBu... | Use the correct Info.plist in the new version of FeedbackDemo | Use the correct Info.plist in the new version of FeedbackDemo
| Python | bsd-3-clause | Jawbone/apptentive-ios,ALHariPrasad/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,sahara108/apptentive-ios,Jawbone/apptentive-ios,hibu/apptentive-ios,apptentive/apptentive-ios,sahara108/apptentive-ios,apptentive/apptentive-ios,hibu/apptentive-ios,ALHariPrasad/apptentive-ios | <REPLACE_OLD> ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist
# <REPLACE_NEW> ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist
# <REPLACE_END> <REPLACE_OLD> ./apptentive-ios/FeedbackDemo/FeedbackDemo/FeedbackDemo-Info.plist <REPLACE_NEW> ./apptentive-ios/FeedbackDemo/FeedbackDemo/Info.plist <R... | Use the correct Info.plist in the new version of FeedbackDemo
# This script should be copied into the Run Script trigger of an Xcode Bot
# Utilizes `cavejohnson` for Xcode Bot scripting
# https://github.com/drewcrawford/CaveJohnson
#!/bin/bash
PATH=/Library/Frameworks/Python.framework/Versions/3.4/bin:$PATH
# Set u... |
c1f71014218d9b6cdb6c45d9d1ce0cc0424f70f8 | doc/pyplots/stylesheet_gallery.py | doc/pyplots/stylesheet_gallery.py | # -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""
x = np.linspace(0, np.pi, 20)
fig, ax = plt... | # -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""
if stylename == 'typhon-dark':
# TODO: S... | Exclude dark-colored theme from stylesheet gallery. | Exclude dark-colored theme from stylesheet gallery.
| Python | mit | atmtools/typhon,atmtools/typhon | <INSERT> if stylename == 'typhon-dark':
# TODO: Sphinx build is broken for non-white figure facecolor.
return
<INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots imp... | Exclude dark-colored theme from stylesheet gallery.
# -*- coding: utf-8 -*-
"""Generate a gallery to compare all available typhon styles.
"""
import numpy as np
import matplotlib.pyplot as plt
from typhon.plots import styles
def simple_plot(stylename):
"""Generate a simple plot using a given matplotlib style."""... |
16a85be6597388092e497e642cdad8650fdfea95 | app/tasks/twitter/listener.py | app/tasks/twitter/listener.py | # -*- coding: utf-8 -*-
import time
import json
import sys
import pika
from tweepy.streaming import StreamListener
class Listener(StreamListener):
def __init__(self):
#setup rabbitMQ Connection
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
self.channel = conn... | # -*- coding: utf-8 -*-
import time
import json
import sys
import pika
import os
from tweepy.streaming import StreamListener
class Listener(StreamListener):
def __init__(self):
#setup rabbitMQ Connection
host = os.environ['CLOUDAMQP_URL']
connection = pika.BlockingConnection(pika.Connectio... | Set up environment specific connection to rabbitmq | Set up environment specific connection to rabbitmq
| Python | mit | robot-overlord/syriarightnow | <REPLACE_OLD> pika
from <REPLACE_NEW> pika
import os
from <REPLACE_END> <REPLACE_OLD> connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
<REPLACE_NEW> host = os.environ['CLOUDAMQP_URL']
connection = pika.BlockingConnection(pika.ConnectionParameters(host=host))
<REPLACE_EN... | Set up environment specific connection to rabbitmq
# -*- coding: utf-8 -*-
import time
import json
import sys
import pika
from tweepy.streaming import StreamListener
class Listener(StreamListener):
def __init__(self):
#setup rabbitMQ Connection
connection = pika.BlockingConnection(pika.ConnectionPar... |
bfeb07b70237dfae49eb18cc44c7150360c06fbd | PRESUBMIT.py | PRESUBMIT.py | # Copyright (c) 2012, 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.
"""Top-level presubmit script for Dart.
See http://dev.chromium.org/developers/how-tos/depottools/presubm... | Add gcl presubmit script to the dart src tree. | Add gcl presubmit script to the dart src tree.
Currently I just added a tree status check but we can extend this over time.
Review URL: https://chromiumcodereview.appspot.com//10891021
git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@11575 260f80e4-7a28-3924-810f-c04153c831b5
| Python | bsd-3-clause | dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dar... | <INSERT> # Copyright (c) 2012, the Dart project authors. <INSERT_END> <INSERT> 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.
"""Top-level presubmit script for Dart.
See http://dev.chromium.org/develop... | Add gcl presubmit script to the dart src tree.
Currently I just added a tree status check but we can extend this over time.
Review URL: https://chromiumcodereview.appspot.com//10891021
git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@11575 260f80e4-7a28-3924-810f-c04153c831b5
| |
48fc33be592e27e632958a58de99356494a4e511 | test/dbusdef.py | test/dbusdef.py | import dbus
bus = dbus.SystemBus()
dummy = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.freedesktop.DBus.Introspectable')
#print dummy.Introspect()
manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Manager')
database = dbus.Interface(bus.get_object('org.bluez', '/or... | import dbus
bus = dbus.SystemBus()
dummy = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.freedesktop.DBus.Introspectable')
#print dummy.Introspect()
manager = dbus.Interface(bus.get_object('org.bluez', '/'), 'org.bluez.Manager')
try:
adapter = dbus.Interface(bus.get_object('org.bluez', manager.DefaultAd... | Remove old 3.x API cruft | Remove old 3.x API cruft
| Python | lgpl-2.1 | pkarasev3/bluez,mapfau/bluez,silent-snowman/bluez,ComputeCycles/bluez,pstglia/external-bluetooth-bluez,ComputeCycles/bluez,pkarasev3/bluez,ComputeCycles/bluez,silent-snowman/bluez,pstglia/external-bluetooth-bluez,pstglia/external-bluetooth-bluez,mapfau/bluez,mapfau/bluez,silent-snowman/bluez,mapfau/bluez,pkarasev3/blue... | <REPLACE_OLD> '/org/bluez'), <REPLACE_NEW> '/'), <REPLACE_END> <REPLACE_OLD> '/org/bluez'), 'org.bluez.Manager')
database = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Database')
try:
adapter <REPLACE_NEW> '/'), 'org.bluez.Manager')
try:
adapter <REPLACE_END> <REPLACE_OLD> 'org.bluez.Adap... | Remove old 3.x API cruft
import dbus
bus = dbus.SystemBus()
dummy = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.freedesktop.DBus.Introspectable')
#print dummy.Introspect()
manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'), 'org.bluez.Manager')
database = dbus.Interface(bus.ge... |
79967811ffdd739bd7a653f4644eec5c4b014625 | setup.py | setup.py | """Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.0',
url='https://github.com/asyncdef/interfaces',
description='... | """Setuptools configuration for interfaces."""
from setuptools import setup
from setuptools import find_packages
with open('README.rst', 'r') as readmefile:
README = readmefile.read()
setup(
name='asyncdef.interfaces',
version='0.1.3',
url='https://github.com/asyncdef/interfaces',
description='... | Fix packaging to resolve the PEP420 namespace | Fix packaging to resolve the PEP420 namespace
Setuptools is still lacking support for PEP480 namespace packages
when using the find_packages function. Until it does all packages,
including the namespace, must be registered in the packages list.
| Python | apache-2.0 | asyncdef/interfaces | <REPLACE_OLD> version='0.1.0',
<REPLACE_NEW> version='0.1.3',
<REPLACE_END> <REPLACE_OLD> packages=find_packages(exclude=['build', 'dist', 'docs']),
<REPLACE_NEW> packages=[
'asyncdef',
'asyncdef.interfaces',
'asyncdef.interfaces.engine',
],
<REPLACE_END> <|endoftext|> """Setuptools conf... | Fix packaging to resolve the PEP420 namespace
Setuptools is still lacking support for PEP480 namespace packages
when using the find_packages function. Until it does all packages,
including the namespace, must be registered in the packages list.
"""Setuptools configuration for interfaces."""
from setuptools import se... |
939998db349c364aa0f5ba4705d4feb2da7104d5 | nn/flags.py | nn/flags.py | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... | Fix float type flag definition | Fix float type flag definition
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | <REPLACE_OLD> cell")
tf.app.flags.DEFINE_string("float32", "", <REPLACE_NEW> cell")
tf.app.flags.DEFINE_string("float-type", "float32", <REPLACE_END> <|endoftext|> import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-... | Fix float type flag definition
import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.f... |
524eb80f426a3a4530fe7ce5940eb0ef619b5396 | alerta/app/shell.py | alerta/app/shell.py |
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)',
formatter_class=argparse.ArgumentDefaul... |
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
description='Alerta server (for development purposes only)',
formatter_class=argparse.ArgumentDefaul... | Disable auto-reloader in debug mode | Disable auto-reloader in debug mode
This was causing issues with plugin initialisation happening twice
and was getting rate limited by Telegram Bot API.
| Python | apache-2.0 | guardian/alerta,guardian/alerta,guardian/alerta,skob/alerta,skob/alerta,guardian/alerta,skob/alerta,skob/alerta | <REPLACE_OLD> threaded=True)
<REPLACE_NEW> threaded=True, use_reloader=False)
<REPLACE_END> <|endoftext|>
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.ArgumentParser(
prog='alertad',
... | Disable auto-reloader in debug mode
This was causing issues with plugin initialisation happening twice
and was getting rate limited by Telegram Bot API.
import argparse
from alerta.app import app
from alerta.app import db
from alerta.version import __version__
LOG = app.logger
def main():
parser = argparse.A... |
66edf9f04c1b23681fae4234a8b297868e66b7aa | osmaxx-py/osmaxx/excerptexport/models/excerpt.py | osmaxx-py/osmaxx/excerptexport/models/excerpt.py | from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
class Excerpt(models.Model):
name = models.CharField(max_length=128, verbose_name=_('name'), blank=False)
is_public = models.BooleanField(default=False, verbose_name=_('is public'))
... | from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
class Excerpt(models.Model):
name = models.CharField(max_length=128, verbose_name=_('name'))
is_public = models.BooleanField(default=False, verbose_name=_('is public'))
is_active... | Remove value which is already default | Remove value which is already default
| Python | mit | geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx-frontend,geometalab/drf-utm-zone-info,geometalab/osmaxx | <REPLACE_OLD> verbose_name=_('name'), blank=False)
<REPLACE_NEW> verbose_name=_('name'))
<REPLACE_END> <|endoftext|> from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
class Excerpt(models.Model):
name = models.CharField(max_length=128... | Remove value which is already default
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
class Excerpt(models.Model):
name = models.CharField(max_length=128, verbose_name=_('name'), blank=False)
is_public = models.BooleanField(defau... |
46a568690a9a284ddc350519a15e092e1211d073 | reviewboard/site/urlresolvers.py | reviewboard/site/urlresolvers.py | from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
args=None, kwargs=None, *func_args, **func_kwargs):
"""Reverses a URL name, returning a working URL.
This works muc... | from __future__ import unicode_literals
from django.core.urlresolvers import NoReverseMatch, reverse
def local_site_reverse(viewname, request=None, local_site_name=None,
local_site=None, args=None, kwargs=None,
*func_args, **func_kwargs):
"""Reverses a URL name, retu... | Allow local_site_reverse to take an actual LocalSite. | Allow local_site_reverse to take an actual LocalSite.
local_site_reverse was able to take a LocalSite's name, or a request
object, but if you actually had a LocalSite (or None), you'd have to
write your own conditional to extract the name and pass it.
Now, local_site_reverse can take a LocalSite. This saves a databas... | Python | mit | custode/reviewboard,custode/reviewboard,bkochendorfer/reviewboard,custode/reviewboard,brennie/reviewboard,reviewboard/reviewboard,KnowNo/reviewboard,sgallagher/reviewboard,custode/reviewboard,sgallagher/reviewboard,brennie/reviewboard,davidt/reviewboard,chipx86/reviewboard,KnowNo/reviewboard,chipx86/reviewboard,KnowNo/... | <INSERT> local_site=None, <INSERT_END> <REPLACE_OLD> kwargs=None, <REPLACE_NEW> kwargs=None,
<REPLACE_END> <INSERT> assert not (local_site_name and local_site)
<INSERT_END> <REPLACE_OLD> local_site_name:
<REPLACE_NEW> local_site_name or local_site:
<REPLACE_END> <INSERT> local_site:
... | Allow local_site_reverse to take an actual LocalSite.
local_site_reverse was able to take a LocalSite's name, or a request
object, but if you actually had a LocalSite (or None), you'd have to
write your own conditional to extract the name and pass it.
Now, local_site_reverse can take a LocalSite. This saves a databas... |
58ca779abe014e85509555c274ae6960e152b9ca | eche/eche_types.py | eche/eche_types.py | class Symbol(str):
pass
# lists
class List(list):
def __add__(self, rhs):
return List(list.__add__(self, rhs))
def __getitem__(self, i):
if type(i) == slice:
return List(list.__getitem__(self, i))
elif i >= len(self):
return None
else:
r... | Create Symbol, List, Boolean, Nil and Atom types. | Create Symbol, List, Boolean, Nil and Atom types.
| Python | mit | skk/eche | <REPLACE_OLD> <REPLACE_NEW> class Symbol(str):
pass
# lists
class List(list):
def __add__(self, rhs):
return List(list.__add__(self, rhs))
def __getitem__(self, i):
if type(i) == slice:
return List(list.__getitem__(self, i))
elif i >= len(self):
return Non... | Create Symbol, List, Boolean, Nil and Atom types.
| |
c3571bf950862a17a0d2938167a3cb9912fab6d9 | setup.py | setup.py | import os
from setuptools import setup, find_packages
import uuid
from jirafs_list_table import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in... | import os
from setuptools import setup, find_packages
import uuid
from jirafs_list_table import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements = [
str(req.req) for req in... | Use the proper entry point name. | Use the proper entry point name.
| Python | mit | coddingtonbear/jirafs-list-table | <REPLACE_OLD> 'jirafs_list_table': <REPLACE_NEW> 'jirafs_plugins': <REPLACE_END> <|endoftext|> import os
from setuptools import setup, find_packages
import uuid
from jirafs_list_table import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
... | Use the proper entry point name.
import os
from setuptools import setup, find_packages
import uuid
from jirafs_list_table import __version__ as version_string
requirements_path = os.path.join(
os.path.dirname(__file__),
'requirements.txt',
)
try:
from pip.req import parse_requirements
requirements =... |
59e15749671009047ec62cae315a07719d583ac7 | build/fbcode_builder_config.py | build/fbcode_builder_config.py | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'
import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen
from ... | #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
'fbcode_builder steps to build & test Bistro'
import specs.fbthrift as fbthrift
import specs.folly as folly
import specs.proxygen as proxygen
from ... | Fix overquoting of thrift paths | oss: Fix overquoting of thrift paths
Summary: This overquotes the paths in travis builds. This will fix the opensource broken builds
Reviewed By: snarkmaster
Differential Revision: D5923131
fbshipit-source-id: 1ff3e864107b0074fc85e8a45a37455430cf4ba3
| Python | mit | facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro,facebook/bistro | <REPLACE_OLD> 'PATH="$PATH:{p}/bin" <REPLACE_NEW> 'PATH="$PATH:"{p}/bin <REPLACE_END> <REPLACE_OLD> 'TEMPLATES_PATH="{p}/include/thrift/templates" <REPLACE_NEW> 'TEMPLATES_PATH={p}/include/thrift/templates <REPLACE_END> <|endoftext|> #!/usr/bin/env python
from __future__ import absolute_import
from __future__ import di... | oss: Fix overquoting of thrift paths
Summary: This overquotes the paths in travis builds. This will fix the opensource broken builds
Reviewed By: snarkmaster
Differential Revision: D5923131
fbshipit-source-id: 1ff3e864107b0074fc85e8a45a37455430cf4ba3
#!/usr/bin/env python
from __future__ import absolute_import
fro... |
19e0b3f089c684fe4aaaed8a06b4baad31de2f41 | currencies/models.py | currencies/models.py | from django.db import models
from django.utils.translation import gettext_lazy as _
class Currency(models.Model):
code = models.CharField(_('code'), max_length=3)
name = models.CharField(_('name'), max_length=35)
symbol = models.CharField(_('symbol'), max_length=4, blank=True)
factor = models.DecimalF... | from django.db import models
from django.utils.translation import gettext_lazy as _
class Currency(models.Model):
code = models.CharField(_('code'), max_length=3)
name = models.CharField(_('name'), max_length=35)
symbol = models.CharField(_('symbol'), max_length=4, blank=True)
factor = models.DecimalF... | Order currencies by name by default | Order currencies by name by default
| Python | bsd-3-clause | marcosalcazar/django-currencies,jmp0xf/django-currencies,ydaniv/django-currencies,ydaniv/django-currencies,barseghyanartur/django-currencies,panosl/django-currencies,pathakamit88/django-currencies,bashu/django-simple-currencies,mysociety/django-currencies,pathakamit88/django-currencies,racitup/django-currencies,panosl/... | <INSERT> ordering = ('name', )
<INSERT_END> <|endoftext|> from django.db import models
from django.utils.translation import gettext_lazy as _
class Currency(models.Model):
code = models.CharField(_('code'), max_length=3)
name = models.CharField(_('name'), max_length=35)
symbol = models.CharField(_... | Order currencies by name by default
from django.db import models
from django.utils.translation import gettext_lazy as _
class Currency(models.Model):
code = models.CharField(_('code'), max_length=3)
name = models.CharField(_('name'), max_length=35)
symbol = models.CharField(_('symbol'), max_length=4, bla... |
4754c220e79aba7fc4c1ab67a1e834cc306d4493 | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with open('README.rst') as f:
readme = f.read()
with open('LI... | #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with open('README.rst') as f:
readme = f.read()
with open('LI... | Remove Django REST Framework from dependencies | Remove Django REST Framework from dependencies
| Python | mit | danxshap/django-rest-surveys | <DELETE> 'djangorestframework', <DELETE_END> <|endoftext|> #!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with o... | Remove Django REST Framework from dependencies
#!/usr/bin/env python
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist bdist_wininst upload -r pypi')
sys.exit()
with open('README... |
c35957b7219f572e80a550893150e8041c5f14b2 | create_ands_rif_cs_xml.py | create_ands_rif_cs_xml.py | """
Create an ANDS RIF-CS XML file.
Links
-----
- http://ands.org.au/guides/cpguide/cpgrifcs.html
- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
- http://www.ands.org.au/resource/rif-cs.html
"""
import logging
import os
from settings import (
ANDS_XML_FILE_NAME, ANDS_XML_FOLDER_PATH, AN... | """
Create an ANDS RIF-CS XML file.
Links
-----
- http://ands.org.au/guides/cpguide/cpgrifcs.html
- http://ands.org.au/resource/rif-cs.html
- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
"""
import logging
import os
from settings import (
ANDS_XML_FILE_NAME, ANDS_XML_FOLDER_PATH, ANDS_... | Fix links in ANDS RIF-CS script | Fix links in ANDS RIF-CS script
| Python | mit | AustralianAntarcticDataCentre/metadata_xml_convert,AustralianAntarcticDataCentre/metadata_xml_convert | <REPLACE_OLD> file.
Links
-----
- <REPLACE_NEW> file.
Links
-----
- <REPLACE_END> <REPLACE_OLD> http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
- http://www.ands.org.au/resource/rif-cs.html
"""
import <REPLACE_NEW> http://ands.org.au/resource/rif-cs.html
- http://services.ands.org.au/docu... | Fix links in ANDS RIF-CS script
"""
Create an ANDS RIF-CS XML file.
Links
-----
- http://ands.org.au/guides/cpguide/cpgrifcs.html
- http://services.ands.org.au/documentation/rifcs/guidelines/rif-cs.html
- http://www.ands.org.au/resource/rif-cs.html
"""
import logging
import os
from settings import (
ANDS_XML_FI... |
70efbd90d9d5601d368ddb5ea20a3b9910539b78 | members/urls.py | members/urls.py | from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url... | from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
url(r'^search/(?P<name>.*)/$', 'mem... | Change url and views for login/logout to django Defaults | Change url and views for login/logout to django Defaults
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | <REPLACE_OLD> url
from django.contrib import auth
urlpatterns <REPLACE_NEW> url
urlpatterns <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^... | Change url and views for login/logout to django Defaults
from django.conf.urls import patterns, url
from django.contrib import auth
urlpatterns = patterns('',
url(r'^login/$', 'django.contrib.auth.views.login',{'template_name': 'members/login_form.html'}, name='login'),
url(r'^logout/$', 'django.contrib.auth.... |
40af3e546a9024f7bb7786828d22534f8dff103a | neutron_fwaas/common/fwaas_constants.py | neutron_fwaas/common/fwaas_constants.py | # Copyright 2015 Cisco Systems, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | # Copyright 2015 Cisco Systems, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Remove unused constant for topics | Remove unused constant for topics
While reading the code, I found "L3_AGENT" topic is defined
but never be used.
Change-Id: I9b6da61f9fe5224d2c25bbe7cc55fd508b4e240f
| Python | apache-2.0 | openstack/neutron-fwaas,openstack/neutron-fwaas | <REPLACE_OLD> 'q-firewall-plugin'
L3_AGENT = 'l3_agent'
FW_AGENT <REPLACE_NEW> 'q-firewall-plugin'
FW_AGENT <REPLACE_END> <|endoftext|> # Copyright 2015 Cisco Systems, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... | Remove unused constant for topics
While reading the code, I found "L3_AGENT" topic is defined
but never be used.
Change-Id: I9b6da61f9fe5224d2c25bbe7cc55fd508b4e240f
# Copyright 2015 Cisco Systems, Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use ... |
18f43e38df3e21e3625351f531fc1d7d5e017621 | demo_propagation.py | demo_propagation.py | # Copyright (c) 2017, CNRS-LAAS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the f... | Add python script that plots the results of a fire propagation | Add python script that plots the results of a fire propagation
| Python | bsd-2-clause | fire-rs-laas/fire-rs-saop,fire-rs-laas/fire-rs-saop,fire-rs-laas/fire-rs-saop,fire-rs-laas/fire-rs-saop | <REPLACE_OLD> <REPLACE_NEW> # Copyright (c) 2017, CNRS-LAAS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# ... | Add python script that plots the results of a fire propagation
| |
fcc2013d1d3a21a1c23cafbaf24cb49a74d054ea | tools/committee_counter.py | tools/committee_counter.py | #!/usr/bin/env
from pupa.core import db
for orga in db.organizations.find({"classification": "committee"}):
memberships = db.memberships.find({
"organization_id": orga['_id'],
"end_date": None
}).count()
print memberships, orga['jurisdiction_id'], orga['name']
| Add a counter to help with debugging. | Add a counter to help with debugging.
| Python | bsd-3-clause | rshorey/pupa,influence-usa/pupa,opencivicdata/pupa,datamade/pupa,mileswwatkins/pupa,mileswwatkins/pupa,opencivicdata/pupa,datamade/pupa,rshorey/pupa,influence-usa/pupa | <INSERT> #!/usr/bin/env
from pupa.core import db
for orga in db.organizations.find({"classification": "committee"}):
<INSERT_END> <INSERT> memberships = db.memberships.find({
"organization_id": orga['_id'],
"end_date": None
}).count()
print memberships, orga['jurisdiction_id'], orga['name'... | Add a counter to help with debugging.
| |
a15c8bce9c59dcba3e7143903d95feb85ee7abe5 | tests/ex12_tests.py | tests/ex12_tests.py | from nose.tools import *
from exercises import ex12
def test_histogram():
'''
Test our histogram output is correct
'''
test_histogram = ex12.histogram([1, 2, 3])
# assert_equal(test_histogram, '*\n**\n***\n')
| from nose.tools import *
from exercises import ex12
try:
from io import StringIO
except:
from StringIO import StringIO
import sys
def test_histogram():
'''
Test our histogram output is correct
'''
std_out = sys.stdout
result = StringIO()
sys.stdout = result
test_histogram = ex12.h... | Update ex12 test so it actually reads output. | Update ex12 test so it actually reads output.
| Python | mit | gravyboat/python-exercises | <REPLACE_OLD> ex12
def <REPLACE_NEW> ex12
try:
from io import StringIO
except:
from StringIO import StringIO
import sys
def <REPLACE_END> <INSERT> std_out = sys.stdout
result = StringIO()
sys.stdout = result
<INSERT_END> <REPLACE_OLD> 3])
# <REPLACE_NEW> 3])
<REPLACE_END> <REPLACE_OLD> assert_eq... | Update ex12 test so it actually reads output.
from nose.tools import *
from exercises import ex12
def test_histogram():
'''
Test our histogram output is correct
'''
test_histogram = ex12.histogram([1, 2, 3])
# assert_equal(test_histogram, '*\n**\n***\n')
|
fdec47174afa276d3d173567bef62eb9b31cd5d0 | alembic/versions/4e1d46e710a2_use_jsonb_for_strokes.py | alembic/versions/4e1d46e710a2_use_jsonb_for_strokes.py | """use jsonb for strokes
Revision ID: 4e1d46e710a2
Revises: 5a7ec3d139df
Create Date: 2015-05-25 19:47:45.924915
"""
from alembic.op import execute
# revision identifiers, used by Alembic.
revision = '4e1d46e710a2'
down_revision = '5a7ec3d139df'
branch_labels = None
depends_on = None
def upgrade():
execute('A... | Use JSONB for storing strokes | Use JSONB for storing strokes
| Python | agpl-3.0 | favien/favien,favien/favien,favien/favien | <INSERT> """use jsonb for strokes
Revision ID: 4e1d46e710a2
Revises: 5a7ec3d139df
Create Date: 2015-05-25 19:47:45.924915
"""
from alembic.op import execute
# revision identifiers, used by Alembic.
revision = '4e1d46e710a2'
down_revision = '5a7ec3d139df'
branch_labels = None
depends_on = None
def upgrade():
<INS... | Use JSONB for storing strokes
| |
49fbd4c43465888d706d336c78f187c3849539e4 | hiora_cartpole/fourier_fa.py | hiora_cartpole/fourier_fa.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import itertools
import numpy as np
def make_feature_vec(state_ranges, order):
"""
Arguments:
state_ranges – (2, n_dims) minima and maxima of possible state values
n_acts – int, number of actions that can happen
order –... | Add untested Fourier linear function approximator | Add untested Fourier linear function approximator
| Python | mit | rmoehn/cartpole | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import itertools
import numpy as np
def make_feature_vec(state_ranges, order):
"""
Arguments:
state_ranges – (2, n_dims) minima and maxima of possible state values
n_acts – int, number of actions th... | Add untested Fourier linear function approximator
| |
436b005217ab92fd06526d9681bc37266c394212 | estmator_project/est_quote/views.py | estmator_project/est_quote/views.py | from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView
class QuoteCreateView(CreateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self, form):
form = super(QuoteCreateView, self).get_for... | from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView
class QuoteCreateView(CreateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self):
form = super(QuoteCreateView, self).get_form()
... | Update view for basic quote form. | Update view for basic quote form.
| Python | mit | Estmator/EstmatorApp,Estmator/EstmatorApp,Estmator/EstmatorApp | <REPLACE_OLD> get_form(self, form):
<REPLACE_NEW> get_form(self):
<REPLACE_END> <INSERT> # <INSERT_END> <INSERT> # <INSERT_END> <REPLACE_OLD> get_form(self, form):
<REPLACE_NEW> get_form(self):
<REPLACE_END> <|endoftext|> from .models import Quote, Category, Product
from django.views.generic.edit import CreateView,... | Update view for basic quote form.
from .models import Quote, Category, Product
from django.views.generic.edit import CreateView, UpdateView
class QuoteCreateView(CreateView):
model = Quote
fields = ['name']
template_name = 'quote.html'
success_url = '/'
def get_form(self, form):
form = s... |
f232d704a0c3b659b994d519c492651033a79a32 | examples/gstreamer/video_pipeline.py | examples/gstreamer/video_pipeline.py | #!/usr/bin/env python
import pygst
pygst.require("0.10")
import gst
import gtk
class Pipeline(object):
def __init__(self):
self.pipeline = gst.Pipeline("pipe")
self.webcam = gst.element_factory_make("v4l2src", "webcam")
self.webcam.set_property("device", "/dev/video0")
self.pipeli... | Add a video pipeline example. | Add a video pipeline example.
| Python | mit | peplin/astral | <INSERT> #!/usr/bin/env python
import pygst
pygst.require("0.10")
import gst
import gtk
class Pipeline(object):
<INSERT_END> <INSERT> def __init__(self):
self.pipeline = gst.Pipeline("pipe")
self.webcam = gst.element_factory_make("v4l2src", "webcam")
self.webcam.set_property("device", "/de... | Add a video pipeline example.
| |
98ca83d54eab97c81c5df86b415eb9ff0b201902 | src/__init__.py | src/__init__.py | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l... | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l... | Fix starting inet client when should use unix socket instead. Fix port to be int. | Fix starting inet client when should use unix socket instead.
Fix port to be int.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1240 a8f5125c-1e01-0410-8897-facf34644b8e
| Python | lgpl-2.1 | freevo/kaa-epg | <REPLACE_OLD> address <REPLACE_NEW> address.split(':')[0] <REPLACE_END> <REPLACE_OLD> port))
<REPLACE_NEW> int(port)))
<REPLACE_END> <|endoftext|> import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAU... | Fix starting inet client when should use unix socket instead.
Fix port to be int.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1240 a8f5125c-1e01-0410-8897-facf34644b8e
import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
... |
655bf4b4159e70b4a99185a1735ac63c3ee951dc | analysis/filter-by-result-type.py | analysis/filter-by-result-type.py | #!/usr/bin/env python
import argparse
import os
import logging
import pprint
import sys
import yaml
# HACK
_file = os.path.abspath(__file__)
_dir = os.path.dirname(os.path.dirname(_file))
sys.path.insert(0, _dir)
from BoogieRunner.ResultType import ResultType
def main(args):
resultTypes = [ r.name for r in list(R... | Add script to filter result by result type. | Add script to filter result by result type.
| Python | bsd-3-clause | symbooglix/boogie-runner,symbooglix/boogie-runner | <INSERT> #!/usr/bin/env python
import argparse
import os
import logging
import pprint
import sys
import yaml
# HACK
_file = os.path.abspath(__file__)
_dir = os.path.dirname(os.path.dirname(_file))
sys.path.insert(0, _dir)
from BoogieRunner.ResultType import ResultType
def main(args):
<INSERT_END> <INSERT> resultTy... | Add script to filter result by result type.
| |
ac3447251395a0f6ee445d76e1c32910505a5bd4 | scripts/remove_after_use/reindex_quickfiles.py | scripts/remove_after_use/reindex_quickfiles.py | import sys
import progressbar
from django.core.paginator import Paginator
from website.app import setup_django
setup_django()
from website.search.search import update_file
from osf.models import QuickFilesNode
PAGE_SIZE = 50
def reindex_quickfiles(dry):
qs = QuickFilesNode.objects.all().order_by('id')
coun... | 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... | <INSERT> import sys
import progressbar
from django.core.paginator import Paginator
from website.app import setup_django
setup_django()
from website.search.search import update_file
from osf.models import QuickFilesNode
PAGE_SIZE = 50
def reindex_quickfiles(dry):
<INSERT_END> <INSERT> qs = QuickFilesNode.objects... | Add script to re-index users' files in quickfiles nodes
| |
93623d3bc8336073b65f586e2d1573831c492084 | iatidataquality/__init__.py | iatidataquality/__init__.py |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3... |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3... | Add survey controller to routes | Add survey controller to routes
| Python | agpl-3.0 | pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality | <REPLACE_OLD> aggregationtypes
<REPLACE_NEW> aggregationtypes
import survey
<REPLACE_END> <|endoftext|>
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free soft... | Add survey controller to routes
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU... |
1e68f5f1fd565a812ef3fdf10c4c40649e3ef398 | foundation/organisation/search_indexes.py | foundation/organisation/search_indexes.py | from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
url = indexes.CharField(model_attr='url')
... | from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
url = indexes.CharField(model_attr='url')
... | Fix references to old model fields | organisation: Fix references to old model fields
| Python | mit | okfn/foundation,okfn/foundation,okfn/foundation,okfn/website,MjAbuz/foundation,okfn/website,okfn/foundation,okfn/website,okfn/website,MjAbuz/foundation,MjAbuz/foundation,MjAbuz/foundation | <REPLACE_OLD> mailinglist <REPLACE_NEW> twitter <REPLACE_END> <REPLACE_OLD> indexes.CharField(model_attr='mailinglist')
<REPLACE_NEW> indexes.CharField(model_attr='twitter')
<REPLACE_END> <REPLACE_OLD> homepage <REPLACE_NEW> homepage_url <REPLACE_END> <REPLACE_OLD> indexes.CharField(model_attr='homepage')
<REPLACE_N... | organisation: Fix references to old model fields
from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')... |
1db1dfe35a97080286577b78f4708cc9afd82232 | rx/checkedobserver.py | rx/checkedobserver.py | from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check_access()
... | from six import add_metaclass
from rx import Observer
from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 -... | Use extension method for Observer.checked | Use extension method for Observer.checked
| Python | mit | dbrattli/RxPY,ReactiveX/RxPY,ReactiveX/RxPY | <INSERT> six import add_metaclass
from <INSERT_END> <INSERT> rx.internal import ExtensionMethod
from <INSERT_END> <REPLACE_OLD> 1
def <REPLACE_NEW> 1
@add_metaclass(ExtensionMethod)
class ObserverChecked(Observer):
"""Uses a meta class to extend Observable with the methods in this class"""
def <REPLACE_END... | Use extension method for Observer.checked
from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self,... |
ab83c8a51cb2950226a5ccf341ad4bd9774a6df4 | client.py | client.py | # encoding=utf-8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)):
if value is not None:
value = value.encode('utf_8')
at = at.e... | # encoding=utf_8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)):
if value is not None:
value = value.encode('utf_8')
at = at.e... | Change encoding name for no reason | Change encoding name for no reason
| Python | mit | drkitty/arise | <REPLACE_OLD> encoding=utf-8
from <REPLACE_NEW> encoding=utf_8
from <REPLACE_END> <|endoftext|> # encoding=utf_8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)... | Change encoding name for no reason
# encoding=utf-8
from __future__ import unicode_literals
import socket
from time import sleep
def mount(s, at, uuid=None, label=None, name=None):
for name, value in ((b'uuid', uuid), (b'label', label), (b'name', name)):
if value is not None:
value = value.e... |
da722b889a2b637bf3895f9f0c5e614deee7e45f | scripts/util/add_clifiles.py | scripts/util/add_clifiles.py | """Utility script that copies neighboring clifiles when it is discovered
that we need new ones!"""
import psycopg2
import os
import sys
import shutil
def missing_logic(fn):
"""Figure out what to do when this filename is missing"""
print("Searching for replacement for '%s'" % (fn,))
lon = float(fn[17:23])
... | Add utility for copying clifiles when new points are needed. | Add utility for copying clifiles when new points are needed. | Python | mit | akrherz/idep,akrherz/idep,akrherz/dep,akrherz/dep,akrherz/dep,akrherz/idep,akrherz/dep,akrherz/dep,akrherz/idep,akrherz/idep,akrherz/idep | <REPLACE_OLD> <REPLACE_NEW> """Utility script that copies neighboring clifiles when it is discovered
that we need new ones!"""
import psycopg2
import os
import sys
import shutil
def missing_logic(fn):
"""Figure out what to do when this filename is missing"""
print("Searching for replacement for '%s'" % (fn,)... | Add utility for copying clifiles when new points are needed.
| |
f076acb05840c361890fbb5ef0c8b43d0de7e2ed | opsdroid/message.py | opsdroid/message.py | """ Class to encapsulate a message """
import logging
class Message:
""" A message object """
def __init__(self, text, user, room, connector):
""" Create object with minimum properties """
self.text = text
self.user = user
self.room = room
self.connector = connector
... | """ Class to encapsulate a message """
import logging
class Message:
""" A message object """
def __init__(self, text, user, room, connector):
""" Create object with minimum properties """
self.text = text
self.user = user
self.room = room
self.connector = connector
... | Make regex a None property | Make regex a None property
| Python | apache-2.0 | FabioRosado/opsdroid,jacobtomlinson/opsdroid,opsdroid/opsdroid | <REPLACE_OLD> connector
<REPLACE_NEW> connector
self.regex = None
<REPLACE_END> <|endoftext|> """ Class to encapsulate a message """
import logging
class Message:
""" A message object """
def __init__(self, text, user, room, connector):
""" Create object with minimum properties """
... | Make regex a None property
""" Class to encapsulate a message """
import logging
class Message:
""" A message object """
def __init__(self, text, user, room, connector):
""" Create object with minimum properties """
self.text = text
self.user = user
self.room = room
s... |
c93da26c35607518f286dbdf9023034288074fab | tests/test_unix.py | tests/test_unix.py | import asyncio
import os
import socket
import tempfile
import uvloop
from uvloop import _testbase as tb
class _TestUnix:
def test_create_server_1(self):
CNT = 0 # number of clients that were successful
TOTAL_CNT = 100 # total number of clients that test will create
TIMEOUT = 5... | Add a test for loop.create_unix_server | tests: Add a test for loop.create_unix_server
| Python | apache-2.0 | MagicStack/uvloop,1st1/uvloop,MagicStack/uvloop | <REPLACE_OLD> <REPLACE_NEW> import asyncio
import os
import socket
import tempfile
import uvloop
from uvloop import _testbase as tb
class _TestUnix:
def test_create_server_1(self):
CNT = 0 # number of clients that were successful
TOTAL_CNT = 100 # total number of clients that test wi... | tests: Add a test for loop.create_unix_server
| |
7b72dbb331c120eb5657ce9a81e725c550779485 | dataportal/broker/__init__.py | dataportal/broker/__init__.py | from .simple_broker import _DataBrokerClass, EventQueue, Header
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
| from .simple_broker import (_DataBrokerClass, EventQueue, Header,
LocationError, IntegrityError)
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
| Add Errors to the public API. | DOC: Add Errors to the public API.
| Python | bsd-3-clause | danielballan/dataportal,ericdill/datamuxer,tacaswell/dataportal,ericdill/datamuxer,tacaswell/dataportal,NSLS-II/dataportal,danielballan/datamuxer,danielballan/datamuxer,ericdill/databroker,NSLS-II/datamuxer,danielballan/dataportal,NSLS-II/dataportal,ericdill/databroker | <REPLACE_OLD> _DataBrokerClass, <REPLACE_NEW> (_DataBrokerClass, <REPLACE_END> <REPLACE_OLD> Header
from <REPLACE_NEW> Header,
LocationError, IntegrityError)
from <REPLACE_END> <|endoftext|> from .simple_broker import (_DataBrokerClass, EventQueue, Header,
Locatio... | DOC: Add Errors to the public API.
from .simple_broker import _DataBrokerClass, EventQueue, Header
from .handler_registration import register_builtin_handlers
DataBroker = _DataBrokerClass() # singleton
register_builtin_handlers()
|
2a3a5fba536877c0ba735244a986e49605ce3fc0 | tests/test_schematics_adapter.py | tests/test_schematics_adapter.py | from schematics.models import Model
from schematics.types import IntType
from hyp.adapters.schematics import SchematicsSerializerAdapter
class Post(object):
def __init__(self):
self.id = 1
class Simple(Model):
id = IntType()
def test_object_conversion():
adapter = SchematicsSerializerAdapter(... | import pytest
from schematics.models import Model
from schematics.types import IntType
from hyp.adapters.schematics import SchematicsSerializerAdapter
class Post(object):
def __init__(self):
self.id = 1
class Simple(Model):
id = IntType()
@pytest.fixture
def adapter():
return SchematicsSerial... | Convert the adapter into a pytest fixture | Convert the adapter into a pytest fixture
| Python | mit | kalasjocke/hyp | <REPLACE_OLD> from <REPLACE_NEW> import pytest
from <REPLACE_END> <REPLACE_OLD> IntType()
def test_object_conversion():
<REPLACE_NEW> IntType()
@pytest.fixture
def adapter():
<REPLACE_END> <REPLACE_OLD> adapter = SchematicsSerializerAdapter(Simple)
<REPLACE_NEW> return SchematicsSerializerAdapter(Simple)
def t... | Convert the adapter into a pytest fixture
from schematics.models import Model
from schematics.types import IntType
from hyp.adapters.schematics import SchematicsSerializerAdapter
class Post(object):
def __init__(self):
self.id = 1
class Simple(Model):
id = IntType()
def test_object_conversion():... |
88cd50a331c20fb65c495e92cc93867f03cd3826 | lib/exp/featx/__init__.py | lib/exp/featx/__init__.py | __all__ = []
from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer
class Featx(Feats):
def __init__(self, root, name):
Feats.__init__(self, root, name)
def get_slide_feats(self):
ss = Slider(self.roo... | __all__ = []
from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer
class Featx(Feats):
def __init__(self, root, name):
Feats.__init__(self, root, name)
def get_slide_feats(self):
ss = Slider(self.roo... | Load feats with zero length | Load feats with zero length
| Python | agpl-3.0 | speed-of-light/pyslider | <INSERT> def load_feats(self, key):
fd = self.load(key)
if fd is None:
return []
return fd
<INSERT_END> <REPLACE_OLD> self.load("s_{:03d}_kps".format(sid))
<REPLACE_NEW> self.load_feats("s_{:03d}_kps".format(sid))
<REPLACE_END> <REPLACE_OLD> self.load("s_{:03d}_des".format(sid... | Load feats with zero length
__all__ = []
from lib.exp.featx.base import Feats
from lib.exp.tools.slider import Slider
from lib.exp.tools.video import Video
from lib.exp.pre import Reducer
class Featx(Feats):
def __init__(self, root, name):
Feats.__init__(self, root, name)
def get_slide_feats(self):... |
de5fbf7d63245e9d14844e66fdf16f88dbfae2e5 | rest_framework/authtoken/migrations/0001_initial.py | rest_framework/authtoken/migrations/0001_initial.py |
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | Update initial migration to work on Python 3 | Update initial migration to work on Python 3 | Python | bsd-2-clause | ajaali/django-rest-framework,mgaitan/django-rest-framework,xiaotangyuan/django-rest-framework,wedaly/django-rest-framework,edx/django-rest-framework,uploadcare/django-rest-framework,brandoncazander/django-rest-framework,mgaitan/django-rest-framework,werthen/django-rest-framework,akalipetis/django-rest-framework,YBJAY00... | <REPLACE_OLD>
from <REPLACE_NEW> # -*- coding: utf-8 -*-
from <REPLACE_END> <REPLACE_OLD> models.CharField(max_length=40, <REPLACE_NEW> models.CharField(primary_key=True, <REPLACE_END> <REPLACE_OLD> primary_key=True)),
<REPLACE_NEW> max_length=40)),
<REPLACE_END> <REPLACE_OLD> models.OneToOneField(related_name=b'aut... | Update initial migration to work on Python 3
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
4a0d781c64da4a0ad211e5fb211dc317a4e3f4c5 | data_structures/doubly_linked_list.py | data_structures/doubly_linked_list.py | class Node(object):
def __init__(self, val, prev=None, next_=None):
self.val = val
self.prev = prev
self.next = next_
def __repr__(self):
return '{val}'.format(val=self.val)
class DoublLinkedList(object):
def __init__(self, iterable=()):
self._current = None
... | Add structure and methods to double linked list. | Add structure and methods to double linked list.
| Python | mit | sjschmidt44/python_data_structures | <REPLACE_OLD> <REPLACE_NEW> class Node(object):
def __init__(self, val, prev=None, next_=None):
self.val = val
self.prev = prev
self.next = next_
def __repr__(self):
return '{val}'.format(val=self.val)
class DoublLinkedList(object):
def __init__(self, iterable=()):
... | Add structure and methods to double linked list.
| |
c9d992cd69fd1ec5c0b8655b379862527b452fb6 | geotrek/settings/dev.py | geotrek/settings/dev.py | from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper Toolbar
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
#
... | from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper Toolbar
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
#
... | Set up console email backend in debug mode | Set up console email backend in debug mode
| Python | bsd-2-clause | makinacorpus/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,johan--/Geot... | <REPLACE_OLD> 'DEBUG'
<REPLACE_NEW> 'DEBUG'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
<REPLACE_END> <|endoftext|> from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
... | Set up console email backend in debug mode
from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper Toolbar
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
... |
cc754aeb16aa41f936d59a3b5746a3bec69489ef | sts/util/convenience.py | sts/util/convenience.py | import time
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_index(f, seq):
"""Return the index of the first item in sequence where f(ite... | import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(ite... | Add little functions for checking if a list is sorted without sorting it | Add little functions for checking if a list is sorted without sorting it
| Python | apache-2.0 | ucb-sts/sts,jmiserez/sts,jmiserez/sts,ucb-sts/sts | <INSERT> is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l[i] < l[i+1] for i in xrange(len(l)-1))
def <INSERT_END> <|endoftext|> import time
def is_sorted(l):
return all(l[i] <= l[i+1] for i in xrange(len(l)-1))
def is_strictly_sorted(l):
return all(l... | Add little functions for checking if a list is sorted without sorting it
import time
def timestamp_string():
return time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
def find(f, seq):
"""Return first item in sequence where f(item) == True."""
for item in seq:
if f(item):
return item
def find_inde... |
0652ab317db79ad7859aafba505c016cd6d58614 | modules/combined/tests/catch_release/catch_release_test.py | modules/combined/tests/catch_release/catch_release_test.py | from options import *
test = { INPUT : 'catch_release.i',
EXODIFF : ['catch_release_out.e']}
| from options import *
test = { INPUT : 'catch_release.i',
EXODIFF : ['catch_release_out.e'],
SKIP : 'temp'
}
| Test passes on my machine, dies on others. Skipping for now. | Test passes on my machine, dies on others. Skipping for now.
r8830
| Python | lgpl-2.1 | WilkAndy/moose,jinmm1992/moose,zzyfisherman/moose,tonkmr/moose,yipenggao/moose,tonkmr/moose,raghavaggarwal/moose,lindsayad/moose,SudiptaBiswas/moose,zzyfisherman/moose,YaqiWang/moose,permcody/moose,raghavaggarwal/moose,laagesen/moose,nuclear-wizard/moose,jasondhales/moose,idaholab/moose,harterj/moose,raghavaggarwal/moo... | <REPLACE_OLD> ['catch_release_out.e']}
<REPLACE_NEW> ['catch_release_out.e'],
SKIP : 'temp'
}
<REPLACE_END> <|endoftext|> from options import *
test = { INPUT : 'catch_release.i',
EXODIFF : ['catch_release_out.e'],
SKIP : 'temp'
}
| Test passes on my machine, dies on others. Skipping for now.
r8830
from options import *
test = { INPUT : 'catch_release.i',
EXODIFF : ['catch_release_out.e']}
|
b48cbb3a41372e785bb840a14880ebade4be4e67 | py/maximum-product-of-three-numbers.py | py/maximum-product-of-three-numbers.py | from operator import mul
import heapq
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
largest3 = heapq.nlargest(3, nums)
smallest3 = heapq.nsmallest(3, nums)
if largest3[0] <= 0:
if largest3[0] == 0... | Add py solution for 628. Maximum Product of Three Numbers | Add py solution for 628. Maximum Product of Three Numbers
628. Maximum Product of Three Numbers: https://leetcode.com/problems/maximum-product-of-three-numbers/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | <REPLACE_OLD> <REPLACE_NEW> from operator import mul
import heapq
class Solution(object):
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
largest3 = heapq.nlargest(3, nums)
smallest3 = heapq.nsmallest(3, nums)
if largest3[0] <= 0:
... | Add py solution for 628. Maximum Product of Three Numbers
628. Maximum Product of Three Numbers: https://leetcode.com/problems/maximum-product-of-three-numbers/
| |
feb147bf3ed487a72128c3bbd3f5a0548c26933a | src/tests/program_page_test.py | src/tests/program_page_test.py | from lib.constants.test import create_new_program
from lib import base, page
class TestProgramPage(base.Test):
def create_private_program_test(self):
dashboard = page.dashboard.DashboardPage(self.driver)
dashboard.navigate_to()
lhn_menu = dashboard.open_lhn_menu()
lhn_menu.select_a... | from lib.constants.test import create_new_program
from lib.page import dashboard
from lib import base
class TestProgramPage(base.Test):
def create_private_program_test(self):
dashboard_page = dashboard.DashboardPage(self.driver)
dashboard_page.navigate_to()
lhn_menu = dashboard_page.open_l... | Fix import error for program page test | Fix import error for program page test
| Python | apache-2.0 | VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc... | <INSERT> lib.page import dashboard
from <INSERT_END> <REPLACE_OLD> base, page
class <REPLACE_NEW> base
class <REPLACE_END> <REPLACE_OLD> dashboard = page.dashboard.DashboardPage(self.driver)
dashboard.navigate_to()
<REPLACE_NEW> dashboard_page = dashboard.DashboardPage(self.driver)
dashboard_page.n... | Fix import error for program page test
from lib.constants.test import create_new_program
from lib import base, page
class TestProgramPage(base.Test):
def create_private_program_test(self):
dashboard = page.dashboard.DashboardPage(self.driver)
dashboard.navigate_to()
lhn_menu = dashboard.o... |
22b92437c1ae672297bed8567b335ef7da100103 | dotfiles/utils.py | dotfiles/utils.py | """
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2))
def realpath_expanduser(path):
return realpath(os.path.expanduser(path))
def is_link_to(path, target):
def nor... | """
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2))
def realpath_expanduser(path):
return realpath(os.path.expanduser(path))
def is_link_to(path, target):
def nor... | Fix link detection when target is itself a symlink | Fix link detection when target is itself a symlink
This shows up on OSX where /tmp is actually a symlink to /private/tmp.
| Python | isc | aparente/Dotfiles,nilehmann/dotfiles-1,aparente/Dotfiles,aparente/Dotfiles,aparente/Dotfiles,Bklyn/dotfiles | <REPLACE_OLD> normalize(target)
<REPLACE_NEW> normalize(realpath(target))
<REPLACE_END> <|endoftext|> """
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2))
def realpath_ex... | Fix link detection when target is itself a symlink
This shows up on OSX where /tmp is actually a symlink to /private/tmp.
"""
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2)... |
a9bb32b91e2b742705b6292bd52fc869a8130766 | dymport/import_file.py | dymport/import_file.py | """
Various functions to dynamically import (abitrary names from) arbitrary files.
To import a file like it is a module, use `import_file`.
"""
from importlib.util import module_from_spec, spec_from_file_location
def import_file(name, file):
"""
Import `file` as a module with _name_.
Raises an ImportEr... | """
Various functions to dynamically import (abitrary names from) arbitrary files.
To import a file like it is a module, use `import_file`.
"""
from sys import version_info
def import_file(name, file):
"""
Import `file` as a module with _name_.
Raises an ImportError if it could not be imported.
"""... | Add check for supported Python versions | Add check for supported Python versions
Not all Python versions are supported by this package, because the import
mechanism changes in the different Python versions.
If an unsupported Python version is used, an ImportError is raised.
| Python | mit | ErwinJanssen/dymport.py | <REPLACE_OLD> importlib.util <REPLACE_NEW> sys <REPLACE_END> <REPLACE_OLD> module_from_spec, spec_from_file_location
def <REPLACE_NEW> version_info
def <REPLACE_END> <INSERT> if version_info > (3, 5):
from importlib.util import module_from_spec, spec_from_file_location
<INSERT_END> <INSERT> <IN... | Add check for supported Python versions
Not all Python versions are supported by this package, because the import
mechanism changes in the different Python versions.
If an unsupported Python version is used, an ImportError is raised.
"""
Various functions to dynamically import (abitrary names from) arbitrary files.
... |
590a1684c7c073879d74240685fe5a304afacfdd | setup.py | setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mock-firestore",
version="0.1.2",
author="Matt Dowds",
description="In-memory implementation of Google Cloud Firestore for use in tests",
long_description=long_description,
url="https:... | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mock-firestore",
version="0.1.2",
author="Matt Dowds",
description="In-memory implementation of Google Cloud Firestore for use in tests",
long_description=long_description,
long_descri... | Set description content type so it renders on PyPI | Set description content type so it renders on PyPI
| Python | mit | mdowds/python-mock-firestore | <INSERT> long_description_content_type="text/markdown",
<INSERT_END> <|endoftext|> import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mock-firestore",
version="0.1.2",
author="Matt Dowds",
description="In-memory implementation of Google Cl... | Set description content type so it renders on PyPI
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="mock-firestore",
version="0.1.2",
author="Matt Dowds",
description="In-memory implementation of Google Cloud Firestore for use in tests",
... |
9aec0558e4174c16c44a8a5598c14a1fbcee55a9 | stock_updater.py | stock_updater.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class StockUpdater:
def __init__(self, db_connection):
self.db_connection = db_connection
def set_items(self, items):
self.items = items
def set_table(self, table):
self.table = table
def set_destination_colums(self, product_code... | Add class for updating stock | Add class for updating stock
| Python | mit | stormaaja/csvconverter,stormaaja/csvconverter,stormaaja/csvconverter | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
# -*- coding: utf-8 -*-
class StockUpdater:
def __init__(self, db_connection):
self.db_connection = db_connection
def set_items(self, items):
self.items = items
def set_table(self, table):
self.table = table
def set_destinat... | Add class for updating stock
| |
08e2099f173bce115ba93c2b960bb1f09ef11269 | models.py | models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **kwargs):
if not self.id:
try... | Fix critical stupid copypaste error | Fix critical stupid copypaste error
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel,kirelagin/django-orderedmodel | <REPLACE_OLD> self.max_order <REPLACE_NEW> self.max_order() <REPLACE_END> <REPLACE_OLD> self.__class__.objects.order_by('-order')[0].order
<REPLACE_NEW> cls.objects.order_by('-order')[0].order
<REPLACE_END> <|endoftext|> from django.db import models
from django.core.exceptions import ValidationError
class OrderedMo... | Fix critical stupid copypaste error
from django.db import models
from django.core.exceptions import ValidationError
class OrderedModel(models.Model):
order = models.PositiveIntegerField(blank=True, unique=True)
class Meta:
abstract = True
ordering = ['order']
def save(self, swapping=False, *args, **k... |
7fc576f3dd4d8d7dbe64dbecfc6dcc9ac9ad6b12 | conman/routes/utils.py | conman/routes/utils.py | import os
def split_path(path):
"""
Split a url path into its sub-paths.
A url's sub-paths consist of all substrings ending in / and starting at
the start of the url.
"""
paths = ['/']
path = path.rstrip('/')
while path:
paths.insert(1, path + '/')
path = os.path.spli... | from collections import deque
def split_path(path):
"""
Split a url path into its sub-paths.
A url's sub-paths consist of all substrings ending in / and starting at
the start of the url.
eg: /path/containing/subpaths/ becomes:
/
/path/
/path/containing/
/path/con... | Refactor split_path code for brevity and clarity | Refactor split_path code for brevity and clarity
| Python | bsd-2-clause | meshy/django-conman,meshy/django-conman | <INSERT> from collections <INSERT_END> <REPLACE_OLD> os
def <REPLACE_NEW> deque
def <REPLACE_END> <REPLACE_OLD> url.
<REPLACE_NEW> url.
eg: /path/containing/subpaths/ becomes:
/
/path/
/path/containing/
/path/containing/subpaths/
<REPLACE_END> <REPLACE_OLD> ['/']
<REPLACE_NE... | Refactor split_path code for brevity and clarity
import os
def split_path(path):
"""
Split a url path into its sub-paths.
A url's sub-paths consist of all substrings ending in / and starting at
the start of the url.
"""
paths = ['/']
path = path.rstrip('/')
while path:
paths... |
4f5e20cc85395312ad66ef3731f2bf7e09987976 | commands/alias.py | commands/alias.py | from devbot import chat
def call(message, name, protocol, cfg, commands):
if message == '':
chat.say('/r ' + commands['help']['alias'].format('alias'), protocol)
return
aliases = ''
for tupl in commands['regex'].items():
if tupl[1] == message:
aliases = aliases + tupl[... | from devbot import chat
def call(message, name, protocol, cfg, commands):
if message == '':
chat.say('/r ' + commands['help']['alias'].format('alias'), protocol)
return
aliases = ''
for tupl in commands['regex'].items():
if tupl[1] == message:
aliases = aliases + tupl[... | Fix bug with DevotedBot speaking error in chat | Fix bug with DevotedBot speaking error in chat
| Python | mit | Ameliorate/DevotedBot,Ameliorate/DevotedBot | <REPLACE_OLD> chat.say('Sorry, <REPLACE_NEW> chat.say('/r Sorry, <REPLACE_END> <|endoftext|> from devbot import chat
def call(message, name, protocol, cfg, commands):
if message == '':
chat.say('/r ' + commands['help']['alias'].format('alias'), protocol)
return
aliases = ''
for tupl in co... | Fix bug with DevotedBot speaking error in chat
from devbot import chat
def call(message, name, protocol, cfg, commands):
if message == '':
chat.say('/r ' + commands['help']['alias'].format('alias'), protocol)
return
aliases = ''
for tupl in commands['regex'].items():
if tupl[1] =... |
830c3d7ac451805286bca32a04d6ba25db39b58d | setup.py | setup.py | from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
setup( name='lifecycle'
, author='Gittip, LLC'
, author_email='support@gittip.com'
, description="This library models a process lifecycle as a list of functions."
, url='http://lifecycl... | from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
setup( name='lifecycle'
, author='Gittip, LLC'
, author_email='support@gittip.com'
, description="This library models a process lifecycle as a list of functions."
, url='http://lifecycl... | Add install_requires so we can build at RTD | Add install_requires so we can build at RTD
| Python | mit | techtonik/algorithm.py,gratipay/algorithm.py,techtonik/algorithm.py,AspenWeb/algorithm.py,gratipay/algorithm.py | <INSERT> install_requires=['dependency_injection']
, <INSERT_END> <|endoftext|> from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
setup( name='lifecycle'
, author='Gittip, LLC'
, author_email='support@gittip.com'
, description="This li... | Add install_requires so we can build at RTD
from __future__ import absolute_import, division, print_function, unicode_literals
from setuptools import setup
setup( name='lifecycle'
, author='Gittip, LLC'
, author_email='support@gittip.com'
, description="This library models a process lifecycle as a li... |
8f322fd8dab9447721e6e1bfbb1d8776f66b8740 | stats_generator.py | stats_generator.py | #!/usr/bin/env python
from datetime import date, timedelta
import redis
def perdelta(start, end, delta):
curr = start
while curr < end:
yield curr
curr += delta
r = redis.Redis('localhost', 6334, db=1)
for result in perdelta(date(2015, 03, 01), date(2015, 12, 12), timedelta(days=1)):
va... | Add a script to generate stats | Add a script to generate stats
| Python | agpl-3.0 | CIRCL/url-abuse,CIRCL/url-abuse,CIRCL/url-abuse,CIRCL/url-abuse | <INSERT> #!/usr/bin/env python
from datetime import date, timedelta
import redis
def perdelta(start, end, delta):
<INSERT_END> <INSERT> curr = start
while curr < end:
yield curr
curr += delta
r = redis.Redis('localhost', 6334, db=1)
for result in perdelta(date(2015, 03, 01), date(2015, 12, 1... | Add a script to generate stats
| |
e8c9762cbfac6dbb4dab252bd9cdf0a4e01f3a36 | scipy/ndimage/tests/test_regression.py | scipy/ndimage/tests/test_regression.py | import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4... | import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4... | Use run_module_suite instead of deprecated NumpyTest. | Use run_module_suite instead of deprecated NumpyTest.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5310 d6536bca-fef9-0310-8506-e4c0a848fbcf
| Python | bsd-3-clause | jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,scipy/scipy-svn,scipy/scipy-svn,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn | <REPLACE_OLD> NumpyTest().run()
<REPLACE_NEW> run_module_suite()
<REPLACE_END> <|endoftext|> import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').... | Use run_module_suite instead of deprecated NumpyTest.
git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5310 d6536bca-fef9-0310-8506-e4c0a848fbcf
import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not h... |
2fa0c333cb92557b5ba39e91db41327ae381b6a7 | Tools/px4params/xmlout.py | Tools/px4params/xmlout.py | from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
for group in groups:
xml... | from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
xml_version = xml_document.createEle... | Add version number to parameter meta data | Add version number to parameter meta data
| Python | mit | darknight-007/Firmware,Aerotenna/Firmware,mcgill-robotics/Firmware,PX4/Firmware,PX4/Firmware,acfloria/Firmware,acfloria/Firmware,mcgill-robotics/Firmware,mcgill-robotics/Firmware,jlecoeur/Firmware,dagar/Firmware,PX4/Firmware,acfloria/Firmware,mje-nz/PX4-Firmware,dagar/Firmware,darknight-007/Firmware,PX4/Firmware,darkni... | <INSERT> xml_version = xml_document.createElement("version")
xml_parameters.appendChild(xml_version)
xml_version_value = xml_document.createTextNode("1")
xml_version.appendChild(xml_version_value)
<INSERT_END> <|endoftext|> from xml.dom.minidom import getDOMImplementation
import codecs
... | Add version number to parameter meta data
from xml.dom.minidom import getDOMImplementation
import codecs
class XMLOutput():
def __init__(self, groups):
impl = getDOMImplementation()
xml_document = impl.createDocument(None, "parameters", None)
xml_parameters = xml_document.documentElement
... |
a3c582df681aae77034e2db08999c89866cd6470 | utilities.py | utilities.py | import collections
def each(function, iterable):
for item in iterable:
function(item)
def each_unpack(function, iterable):
for item in iterable:
function(*item)
def minmax(*args):
min = None
max = None
for x in args:
if max < x:
max = x
if x > min:
min = x
return min, max
... | import collections
def each(function, iterable):
for item in iterable:
function(item)
def each_unpack(function, iterable):
for item in iterable:
function(*item)
def minmax(*args):
min = None
max = None
for x in args:
if max < x:
max = x
if x > min:
min = x
return min, max
... | Refactor earth mover's distance implementation | Refactor earth mover's distance implementation
| Python | mit | davidfoerster/schema-matching | <REPLACE_OLD> key_set = <REPLACE_NEW> return sum(
(abs(self.get(bin) - compare_to.get(bin))
for bin in <REPLACE_END> <REPLACE_OLD> compare_to.viewkeys()
currentEMD = 0
lastEMD = 0
totaldistance = 0
for key in key_set:
lastEMD = currentEMD
currentEMD = (self.get(key, 0) + last... | Refactor earth mover's distance implementation
import collections
def each(function, iterable):
for item in iterable:
function(item)
def each_unpack(function, iterable):
for item in iterable:
function(*item)
def minmax(*args):
min = None
max = None
for x in args:
if max < x:
max = x
... |
94ae82e8a2915c6c7d353d03aa363ae687805344 | testing/models/test_proposal.py | testing/models/test_proposal.py | import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import models
@pytest.fixture
def proposal():
return models.Proposal(proposal_id='abc', pi='pi', title='title',
pdf_url='pdf_url')
def test_proposal_printing(proposal):
assert re... | import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import models
@pytest.fixture
def proposal():
return models.Proposal(proposal_id='abc', pi='pi', title='title',
pdf_url='pdf_url')
def test_proposal_printing(proposal):
assert re... | Add more tests around the proposal model behaviour | Add more tests around the proposal model behaviour
| Python | mit | mindriot101/k2catalogue | <REPLACE_OLD> 'def')
@pytest.mark.parametrize('input,expected', <REPLACE_NEW> 'def')
def test_open_proposals_page(proposal):
with mock.patch.object(proposal, 'campaign') as campaign:
proposal.open_proposals_page()
campaign.open_proposals_page.assert_called_once_with()
def test_open_proposal(pr... | Add more tests around the proposal model behaviour
import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import models
@pytest.fixture
def proposal():
return models.Proposal(proposal_id='abc', pi='pi', title='title',
pdf_url='pdf_url')
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.