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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e1e7189bbe859d6dfa6f883d2ff46ff1faed4842 | scrape.py | scrape.py | import scholarly
import requests
_SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
def search(query, start_year, end_year):
"""Search by scholar query and return a generator of Publication objects"""
soup = scholarly._get_soup(
_SEARCH.format(requests.utils.quote(query),
str(star... | import scholarly
import requests
_EXACT_SEARCH = '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def search(query, exact=True, start_year=None, end_year=None):
"""Search by scholar query and return a generator of Publication objects"""
url = _EXACT_SEARCH.format(requests.utils.quote(query... | Make year range arguments optional in search | Make year range arguments optional in search
| Python | mit | Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker,Spferical/cure-alzheimers-fund-tracker | <REPLACE_OLD> requests
_SEARCH <REPLACE_NEW> requests
_EXACT_SEARCH <REPLACE_END> <REPLACE_OLD> '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
def <REPLACE_NEW> '/scholar?q="{}"'
_START_YEAR = '&as_ylo={}'
_END_YEAR = '&as_yhi={}'
def <REPLACE_END> <REPLACE_OLD> start_year, end_year):
<REPLACE_NEW> exact=True, start_year=N... | Make year range arguments optional in search
import scholarly
import requests
_SEARCH = '/scholar?q=\"{}\"&as_ylo={}&as_yhi={}'
def search(query, start_year, end_year):
"""Search by scholar query and return a generator of Publication objects"""
soup = scholarly._get_soup(
_SEARCH.format(requests.utils... |
9139a2efc445887f59b99052f1ffd05c98ee2c72 | tests/test_reporter.py | tests/test_reporter.py | """Test the Reporter base class."""
import pytest
@pytest.fixture
def klass():
"""Return the CUT."""
from agile_analytics.reporters import Reporter
return Reporter
def test_klass(klass):
"""Ensure the CUT exists."""
assert klass
@pytest.fixture
def instance(klass, days_ago):
"""Return a p... | Add tests for base class. | Add tests for base class.
| Python | mit | cmheisel/agile-analytics | <REPLACE_OLD> <REPLACE_NEW> """Test the Reporter base class."""
import pytest
@pytest.fixture
def klass():
"""Return the CUT."""
from agile_analytics.reporters import Reporter
return Reporter
def test_klass(klass):
"""Ensure the CUT exists."""
assert klass
@pytest.fixture
def instance(klass,... | Add tests for base class.
| |
fa77d7d83ed9150670ac374f1494b38f2338217a | migrations/versions/0028_add_default_permissions.py | migrations/versions/0028_add_default_permissions.py | """empty message
Revision ID: 0028_add_default_permissions
Revises: 0027_add_service_permission
Create Date: 2016-02-26 10:33:20.536362
"""
# revision identifiers, used by Alembic.
revision = '0028_add_default_permissions'
down_revision = '0027_add_service_permission'
import uuid
from datetime import datetime
from a... | Add default permissions for existing services. | Add default permissions for existing services.
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | <REPLACE_OLD> <REPLACE_NEW> """empty message
Revision ID: 0028_add_default_permissions
Revises: 0027_add_service_permission
Create Date: 2016-02-26 10:33:20.536362
"""
# revision identifiers, used by Alembic.
revision = '0028_add_default_permissions'
down_revision = '0027_add_service_permission'
import uuid
from da... | Add default permissions for existing services.
| |
f40dd24af6788e7de7d06254850b83edb179b423 | bootcamp/lesson4.py | bootcamp/lesson4.py | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
return datetime.datetime(2015, 06, 01)
# Question 2
# ----------
# Using the math module retu... | import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt():
# Write code here
pass
# Question 2
# ----------
# Using the math module return pi
def pl... | Revert "Added solutions for lesson 4" | Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.
| Python | mit | infoscout/python-bootcamp-pv | <REPLACE_OLD> return datetime.datetime(2015, 06, 01)
# <REPLACE_NEW> # Write code here
pass
# <REPLACE_END> <REPLACE_OLD> return math.pi
def <REPLACE_NEW> # Write code here
pass
def <REPLACE_END> <|endoftext|> import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using ... | Revert "Added solutions for lesson 4"
This reverts commit 58d049c78b16ec5b61f9681b605dc4e937ea7e3e.
import datetime
import math
from core import test_helper
# Question 1
# ----------
# Using the datetime module return a datetime object with the year of 2015, the month of June, and the day of 1
def playing_with_dt(... |
9201e9c433930da8fd0bfb13eadbc249469e4d84 | fireplace/cards/tourney/mage.py | fireplace/cards/tourney/mage.py | from ..utils import *
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost))
)
| from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Ar... | Implement Mage cards for The Grand Tournament | Implement Mage cards for The Grand Tournament
| Python | agpl-3.0 | Meerkov/fireplace,amw2104/fireplace,liujimj/fireplace,Ragowit/fireplace,smallnamespace/fireplace,jleclanche/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,Meerkov/fireplace,amw2104/fireplace,oftc-ftw/fireplace | <INSERT> Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Arcane Blast
class AT_... | Implement Mage cards for The Grand Tournament
from ..utils import *
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost))
)
|
c12d70090b47765a658a98c29fd332ca6ec057d7 | bin/migrate-tips.py | bin/migrate-tips.py | from gratipay.wireup import db, env
from gratipay.models.team import Team, AlreadyMigrated
db = db(env())
slugs = db.all("""
SELECT slug
FROM teams
WHERE is_approved IS TRUE
""")
for slug in slugs:
team = Team.from_slug(slug)
try:
team.migrate_tips()
print("Migrated tips for '%... | Add script for migrating tips to new teams | Add script for migrating tips to new teams
| Python | mit | studio666/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio6... | <INSERT> from gratipay.wireup import db, env
from gratipay.models.team import Team, AlreadyMigrated
db = db(env())
slugs = db.all("""
<INSERT_END> <INSERT> SELECT slug
FROM teams
WHERE is_approved IS TRUE
""")
for slug in slugs:
team = Team.from_slug(slug)
try:
team.migrate_tips()
... | Add script for migrating tips to new teams
| |
23f59f95ea3e7d6504e03949a1400be452166d17 | buildPy2app.py | buildPy2app.py | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... | """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resources/*.lua')),
]
OPTIONS = {
'icon... | Update py2app script for Qt 5.11 | Update py2app script for Qt 5.11
| Python | apache-2.0 | NeverDecaf/syncplay,alby128/syncplay,alby128/syncplay,Syncplay/syncplay,Syncplay/syncplay,NeverDecaf/syncplay | <REPLACE_OLD> 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib'],
'plist': <REPLACE_NEW> 'platforms/libqminimal.dylib','platforms/libqoffscreen.dylib', 'styles/libqmacstyle.dylib'],
'plist': <REPLACE_END> <|endoftext|> """
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app... | Update py2app script for Qt 5.11
"""
This is a setup.py script generated by py2applet
Usage:
python setup.py py2app
"""
from setuptools import setup
from glob import glob
import syncplay
APP = ['syncplayClient.py']
DATA_FILES = [
('resources', glob('resources/*.png') + glob('resources/*.rtf') + glob('resour... |
497f5085143322d4b9d3ad23d35d30cdf852d1f6 | test/unit/sorting/test_heap_sort.py | test/unit/sorting/test_heap_sort.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
from helper.read_data_file import read_int_array
from sorting.heap_sort import sort
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class InsertionSortTester(unittest.TestCase):
# Test sort in default order, i.e., in ascending orde... | Add unit test for heap sort implementation. | Add unit test for heap sort implementation.
| Python | mit | weichen2046/algorithm-study,weichen2046/algorithm-study | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
from helper.read_data_file import read_int_array
from sorting.heap_sort import sort
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class InsertionSortTester(unittest.TestCase):
# Test sort in default o... | Add unit test for heap sort implementation.
| |
1cb79216f992ea0f31abb28031a74f6e703582cb | YouKnowShit/DownloadPic.py | YouKnowShit/DownloadPic.py | import requests
import bs4
import os
import urllib.request
import shutil
import re
base_url = 'http://www.j8vlib.com/cn/vl_searchbyid.php?keyword='
srcDir = 'F:\\utorrent\\WEST'
filterWord = "video_jacket_img"
filenames = os.listdir(srcDir)
for filename in filenames:
preFileName = filename.split(".")[0]
if (p... | import requests
import bs4
import os
import urllib.request
import shutil
import re
base_url = 'http://www.jav11b.com/cn/vl_searchbyid.php?keyword='
srcDir = 'H:\\temp'
filterWord = "video_jacket_img"
filenames = os.listdir(srcDir)
for filename in filenames:
preFileName = filename.split(".")[0]
if (preFileName... | Update the pic download base url. | Update the pic download base url.
| Python | mit | jiangtianyu2009/PiSoftCake | <REPLACE_OLD> 'http://www.j8vlib.com/cn/vl_searchbyid.php?keyword='
srcDir = 'F:\\utorrent\\WEST'
filterWord <REPLACE_NEW> 'http://www.jav11b.com/cn/vl_searchbyid.php?keyword='
srcDir = 'H:\\temp'
filterWord <REPLACE_END> <|endoftext|> import requests
import bs4
import os
import urllib.request
import shutil
import re
... | Update the pic download base url.
import requests
import bs4
import os
import urllib.request
import shutil
import re
base_url = 'http://www.j8vlib.com/cn/vl_searchbyid.php?keyword='
srcDir = 'F:\\utorrent\\WEST'
filterWord = "video_jacket_img"
filenames = os.listdir(srcDir)
for filename in filenames:
preFileName... |
bd717b8056a69ee7074a94b3234d840dd431dd1f | src/341_flatten_nested_list_iterator.py | src/341_flatten_nested_list_iterator.py | """
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger(object):
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"... | Use stack to solve the problem | Use stack to solve the problem
| Python | apache-2.0 | zhuxiang/LeetCode-Python | <REPLACE_OLD> <REPLACE_NEW> """
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
"""
class NestedInteger(object):
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list... | Use stack to solve the problem
| |
c85f423960050fea76452818ce25f9dc287c922a | vumidash/dummy_client.py | vumidash/dummy_client.py | """MetricSource that serves dummy data."""
import random
from vumidash.base import MetricSource, UnknownMetricError
class DummyClient(MetricSource):
"""Serve dummy data."""
def __init__(self):
self.latest = None
self.metric_prefix = "test"
self.prev_values = {} # map of metrics to p... | """MetricSource that serves dummy data."""
import random
from vumidash.base import MetricSource, UnknownMetricError
class DummyClient(MetricSource):
"""Serve dummy data."""
def __init__(self):
self.latest = None
self.metric_prefix = "test"
self.prev_values = {} # map of metrics to p... | Fix steps calculation in dummy client -- how did this work before? | Fix steps calculation in dummy client -- how did this work before?
| Python | bsd-3-clause | praekelt/vumi-dashboard,praekelt/vumi-dashboard | <REPLACE_OLD> (self.total_seconds((-start) <REPLACE_NEW> int(self.total_seconds((-start) <REPLACE_END> <INSERT> <INSERT_END> <|endoftext|> """MetricSource that serves dummy data."""
import random
from vumidash.base import MetricSource, UnknownMetricError
class DummyClient(MetricSource):
"""Serve dummy data.""... | Fix steps calculation in dummy client -- how did this work before?
"""MetricSource that serves dummy data."""
import random
from vumidash.base import MetricSource, UnknownMetricError
class DummyClient(MetricSource):
"""Serve dummy data."""
def __init__(self):
self.latest = None
self.metric_... |
35c264819bac12fcb3baf8a2a33d63dd916f5f86 | mezzanine_fluent_pages/mezzanine_layout_page/widgets.py | mezzanine_fluent_pages/mezzanine_layout_page/widgets.py | from django.forms.widgets import Select
class LayoutSelector(Select):
"""
Modified `Select` class to select the original value.
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
"""
def render(self, name, value, attrs=None, choices=()):
... | from django.forms.widgets import Select
class LayoutSelector(Select):
"""
Modified `Select` class to select the original value.
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
"""
def render(self, name, value, attrs=None, *args, **kwar... | Remove keyword argument and allow generic argument passing. | Remove keyword argument and allow generic argument passing.
| Python | bsd-2-clause | sjdines/mezzanine-fluent-pages,sjdines/mezzanine-fluent-pages,sjdines/mezzanine-fluent-pages | <REPLACE_OLD> choices=()):
<REPLACE_NEW> *args, **kwargs):
<REPLACE_END> <REPLACE_OLD> choices: Available choices for the `Select` field.
<REPLACE_NEW> args: pass along any other arguments.
:param kwargs: pass along any other keyword arguments.
<REPLACE_END> <REPLACE_OLD> choices)
<REPLACE_NEW> *args, **kw... | Remove keyword argument and allow generic argument passing.
from django.forms.widgets import Select
class LayoutSelector(Select):
"""
Modified `Select` class to select the original value.
This was adapted from `fluent_pages/pagetypes/fluent_pages/widgets
.py` in the `django-fluent-pages` app.
""... |
e728d6ebdd101b393f3d87fdfbade2c4c52c5ef1 | cdent/emitter/perl.py | cdent/emitter/perl.py | """\
Perl code emitter for C'Dent
"""
from __future__ import absolute_import
from cdent.emitter import Emitter as Base
class Emitter(Base):
LANGUAGE_ID = 'pm'
def emit_includecdent(self, includecdent):
self.writeln('use CDent::Run;')
def emit_class(self, class_):
name = class_.name
... | """\
Perl code emitter for C'Dent
"""
from __future__ import absolute_import
from cdent.emitter import Emitter as Base
class Emitter(Base):
LANGUAGE_ID = 'pm'
def emit_includecdent(self, includecdent):
self.writeln('use CDent::Run;')
def emit_class(self, class_):
name = class_.name
... | Use Moose for Perl 5 | Use Moose for Perl 5
| Python | bsd-2-clause | ingydotnet/cdent-py,ingydotnet/cdent-py,ingydotnet/cdent-py,ingydotnet/cdent-py,ingydotnet/cdent-py,ingydotnet/cdent-py,ingydotnet/cdent-py,ingydotnet/cdent-py | <REPLACE_OLD> CDent::Class;')
<REPLACE_NEW> Moose;')
<REPLACE_END> <|endoftext|> """\
Perl code emitter for C'Dent
"""
from __future__ import absolute_import
from cdent.emitter import Emitter as Base
class Emitter(Base):
LANGUAGE_ID = 'pm'
def emit_includecdent(self, includecdent):
self.writeln('... | Use Moose for Perl 5
"""\
Perl code emitter for C'Dent
"""
from __future__ import absolute_import
from cdent.emitter import Emitter as Base
class Emitter(Base):
LANGUAGE_ID = 'pm'
def emit_includecdent(self, includecdent):
self.writeln('use CDent::Run;')
def emit_class(self, class_):
... |
cd0426dbbfc6f1573cf5d09485b8930eb498e1c6 | mbuild/tests/test_utils.py | mbuild/tests/test_utils.py | import difflib
import pytest
from mbuild.tests.base_test import BaseTest
from mbuild.utils.io import get_fn
from mbuild.utils.validation import assert_port_exists
class TestUtils(BaseTest):
def test_assert_port_exists(self, ch2):
assert_port_exists('up', ch2)
with pytest.raises(ValueError):
... | import difflib
import numpy as np
import pytest
from mbuild.tests.base_test import BaseTest
from mbuild.utils.io import get_fn, import_
from mbuild.utils.validation import assert_port_exists
class TestUtils(BaseTest):
def test_assert_port_exists(self, ch2):
assert_port_exists('up', ch2)
with py... | Add some unit test on utils.io | Add some unit test on utils.io
| Python | mit | iModels/mbuild,iModels/mbuild | <REPLACE_OLD> difflib
import pytest
from <REPLACE_NEW> difflib
import numpy as np
import pytest
from <REPLACE_END> <REPLACE_OLD> get_fn
from <REPLACE_NEW> get_fn, import_
from <REPLACE_END> <REPLACE_OLD> changes
<REPLACE_NEW> changes
def test_fn(self):
get_fn('benzene.mol2')
with pytest.raises(... | Add some unit test on utils.io
import difflib
import pytest
from mbuild.tests.base_test import BaseTest
from mbuild.utils.io import get_fn
from mbuild.utils.validation import assert_port_exists
class TestUtils(BaseTest):
def test_assert_port_exists(self, ch2):
assert_port_exists('up', ch2)
with ... |
b5bb360a78eb3493a52a4f085bb7ae2ef1355cdd | scavenger/net_utils.py | scavenger/net_utils.py | import subprocess
import requests
def logged_in():
"""Check whether the device has logged in.
Return a dictionary containing:
username
byte
duration (in seconds)
Return False if no logged in
"""
r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login',
... | import subprocess
import requests
def check_online():
"""Check whether the device has logged in.
Return a dictionary containing:
username
byte
duration (in seconds)
Return False if no logged in
"""
r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login',
... | Change name: logged_in => check_online | Change name: logged_in => check_online
| Python | mit | ThomasLee969/scavenger | <REPLACE_OLD> logged_in():
<REPLACE_NEW> check_online():
<REPLACE_END> <|endoftext|> import subprocess
import requests
def check_online():
"""Check whether the device has logged in.
Return a dictionary containing:
username
byte
duration (in seconds)
Return False if no logged in
... | Change name: logged_in => check_online
import subprocess
import requests
def logged_in():
"""Check whether the device has logged in.
Return a dictionary containing:
username
byte
duration (in seconds)
Return False if no logged in
"""
r = requests.post('http://net.tsinghua.e... |
12f4f47d0f9a4a24d37e16fb1afc0841399ccadf | setup.py | setup.py | # Use the newer `setuptools.setup()`, if available.
try:
from setuptools import setup
kw = {
'test_suite': 'tests',
'tests_require': ['astunparse'],
}
except ImportError:
from distutils.core import setup
kw = {}
setup(name='gast', # gast, daou naer!
version='0.2.0',
pac... | # Use the newer `setuptools.setup()`, if available.
try:
from setuptools import setup
kw = {
'test_suite': 'tests',
'tests_require': ['astunparse'],
}
except ImportError:
from distutils.core import setup
kw = {}
setup(name='gast', # gast, daou naer!
version='0.2.0',
pac... | Add python_requires to help pip, and Trove classifiers | Add python_requires to help pip, and Trove classifiers
| Python | bsd-3-clause | serge-sans-paille/gast | <REPLACE_OLD> 3'],
<REPLACE_NEW> 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
python_require... | Add python_requires to help pip, and Trove classifiers
# Use the newer `setuptools.setup()`, if available.
try:
from setuptools import setup
kw = {
'test_suite': 'tests',
'tests_require': ['astunparse'],
}
except ImportError:
from distutils.core import setup
kw = {}
setup(name='gas... |
be59230531d98dc25f806b2290a51a0f4fde1d3b | addons/survey/migrations/8.0.2.0/pre-migration.py | addons/survey/migrations/8.0.2.0/pre-migration.py | # coding: utf-8
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(cr, version):
openupgrade.rename_tables(cr, [('survey', 'survey_survey')])
openupgrade.rename_models(cr, [('survey', 'survey.survey')])
| Rename model to prevent crash during module upgrade in tests | [ADD] Rename model to prevent crash during module upgrade in tests
| Python | agpl-3.0 | grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,Endika/OpenUpgrade,Endika/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,OpenUpgrade/OpenUpgrade,Endika/OpenUpgrade,grap/OpenUpgrade,grap/OpenUpgrade,Endika/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,grap/OpenUpgrade,OpenUpgrade/OpenUpgrade,Endika/OpenUpgrade,End... | <INSERT> # coding: utf-8
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(cr, version):
<INSERT_END> <INSERT> openupgrade.rename_tables(cr, [('survey', 'survey_survey')])
openupgrade.rename_models(cr, [('survey', 'survey.survey')])
<INSERT_END> <|endoftext|> # coding: utf-8
from openu... | [ADD] Rename model to prevent crash during module upgrade in tests
| |
f7dd16abcab5d5e0134083267f21672de8e3d5e1 | hc/front/context_processors.py | hc/front/context_processors.py | from django.conf import settings
def branding(request):
return {
"site_name": settings.SITE_NAME,
"site_root": settings.SITE_ROOT,
"site_logo_url": settings.SITE_LOGO_URL,
}
| from django.conf import settings
def branding(request):
return {
"site_name": settings.SITE_NAME,
"site_logo_url": settings.SITE_LOGO_URL,
}
| Remove site_root from template context, it's never used | Remove site_root from template context, it's never used
| Python | bsd-3-clause | iphoting/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,healthchecks/healthchecks,iphoting/healthchecks,healthchecks/healthchecks,iphoting/healthchecks | <DELETE> "site_root": settings.SITE_ROOT,
<DELETE_END> <|endoftext|> from django.conf import settings
def branding(request):
return {
"site_name": settings.SITE_NAME,
"site_logo_url": settings.SITE_LOGO_URL,
}
| Remove site_root from template context, it's never used
from django.conf import settings
def branding(request):
return {
"site_name": settings.SITE_NAME,
"site_root": settings.SITE_ROOT,
"site_logo_url": settings.SITE_LOGO_URL,
}
|
513d8e83dc7aea052682df2bc93cd146b6799406 | client/examples/cycle-cards.py | client/examples/cycle-cards.py | #!/bin/python
import removinator
import subprocess
# This example cycles through each card slot in the Removinator. Any
# slots that have a card present will then have the certificates on the
# card printed out using the pkcs15-tool utility, which is provided by
# the OpenSC project.
#
# Examples of parsing the Remo... | #!/usr/bin/env python
import removinator
import subprocess
# This example cycles through each card slot in the Removinator. Any
# slots that have a card present will then have the certificates on the
# card printed out using the pkcs15-tool utility, which is provided by
# the OpenSC project.
#
# Examples of parsing ... | Use python from env in example script | Use python from env in example script
This makes the cycle-cards example script use python from the env
instead of harcoding the location. This allows a virtualenv to be
easily used.
| Python | apache-2.0 | nkinder/smart-card-removinator | <REPLACE_OLD> #!/bin/python
import <REPLACE_NEW> #!/usr/bin/env python
import <REPLACE_END> <|endoftext|> #!/usr/bin/env python
import removinator
import subprocess
# This example cycles through each card slot in the Removinator. Any
# slots that have a card present will then have the certificates on the
# card pr... | Use python from env in example script
This makes the cycle-cards example script use python from the env
instead of harcoding the location. This allows a virtualenv to be
easily used.
#!/bin/python
import removinator
import subprocess
# This example cycles through each card slot in the Removinator. Any
# slots tha... |
28bb129931e14d5681ba717f6c949e2305fd2e03 | django/website/main/tests/test_merge_coverage_handling.py | django/website/main/tests/test_merge_coverage_handling.py | from mock import Mock
from main.management.commands.merge_coverage_files import Command
from main.tests.helper_methods import mock_out_unwanted_methods
def test_merge_coverage_handle_calls_parse_options():
merge_coverage_files_command = Command()
# We don't want these methods to run
mock_out_unwanted_me... | Add tests to run command to merge content | Add tests to run command to merge content | Python | agpl-3.0 | daniell/kashana,aptivate/alfie,daniell/kashana,aptivate/alfie,daniell/kashana,daniell/kashana,aptivate/kashana,aptivate/kashana,aptivate/kashana,aptivate/alfie,aptivate/alfie,aptivate/kashana | <INSERT> from mock import Mock
from main.management.commands.merge_coverage_files import Command
from main.tests.helper_methods import mock_out_unwanted_methods
def test_merge_coverage_handle_calls_parse_options():
<INSERT_END> <INSERT> merge_coverage_files_command = Command()
# We don't want these methods t... | Add tests to run command to merge content
| |
97f81ddfdd78d062e5019793101926fb52b0db38 | sum.py | sum.py | import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_scratch(True)
| import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_view.set_scratch(True)
| Set new file to read-only | Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.
| Python | mit | jbrudvik/sublime-sum,jbrudvik/sublime-sum | <INSERT> new_view.set_read_only(True)
<INSERT_END> <|endoftext|> import sublime, sublime_plugin
class SumCommand(sublime_plugin.TextCommand):
def run(self, edit):
new_view = self.view.window().new_file()
new_view.set_name('Sum')
new_view.insert(edit, 0, '42')
new_view.set_read_only(True)
new_... | Set new file to read-only
Since the new file does not prompt about file changes when closed, if
the user were to edit the new file and close without saving, their
changes would be lost forever. By setting the new file to be read-only,
the user will not be able to make changes to it that may be lost.
import sublime, s... |
2ad1c276a96a77d2088f996ebc32fa74206d1cef | osf/migrations/0036_ensure_schemas.py | osf/migrations/0036_ensure_schemas.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-24 19:33
from __future__ import unicode_literals
import logging
from django.db import migrations
from osf.models import MetaSchema
from website.project.metadata.schemas import OSF_META_SCHEMAS
logger = logging.getLogger(__file__)
def add_schemas(*args... | Add migration for ensure schemas | Add migration for ensure schemas
| Python | apache-2.0 | CenterForOpenScience/osf.io,mattclark/osf.io,pattisdr/osf.io,caseyrollins/osf.io,crcresearch/osf.io,adlius/osf.io,erinspace/osf.io,baylee-d/osf.io,cslzchen/osf.io,laurenrevere/osf.io,felliott/osf.io,CenterForOpenScience/osf.io,baylee-d/osf.io,binoculars/osf.io,mattclark/osf.io,pattisdr/osf.io,sloria/osf.io,brianjgeiger... | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-24 19:33
from __future__ import unicode_literals
import logging
from django.db import migrations
from osf.models import MetaSchema
from website.project.metadata.schemas import OSF_META_SCHEMAS
logger = logging.getLogger(__fi... | Add migration for ensure schemas
| |
36021ba78d84dbb3aef8ea54369f88f6461eced6 | history_rewrite_scripts/config.py | history_rewrite_scripts/config.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
AUTOMERGER_NAME = 'Chromium+Blink automerger'
AUTOMERGER_EMAIL = 'chrome-blink-automerger@chromium.org'
BLINK_REPO_URL = 'https://chromium.googlesource.com... | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
AUTOMERGER_NAME = 'Chromium+Blink automerger'
AUTOMERGER_EMAIL = 'chrome-blink-automerger@chromium.org'
BLINK_REPO_URL = 'https://chromium.googlesource.com... | Switch to 2311 + 2357 branches | Switch to 2311 + 2357 branches
| Python | bsd-3-clause | primiano/chrome-blink-automerger | <REPLACE_OLD> ('refs/branch-heads/2214', 'refs/branch-heads/chromium/2214'),
<REPLACE_NEW> ('refs/branch-heads/2311', 'refs/branch-heads/chromium/2311'),
<REPLACE_END> <REPLACE_OLD> ('refs/branch-heads/2272', 'refs/branch-heads/chromium/2272'),
('refs/branch-heads/2311', 'refs/branch-heads/chromium/2311'),
]
MER... | Switch to 2311 + 2357 branches
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
AUTOMERGER_NAME = 'Chromium+Blink automerger'
AUTOMERGER_EMAIL = 'chrome-blink-automerger@chromium.org'
BLINK_REPO_URL = 'h... |
87cca84b6750a3176b86df2786a9b78f7647c062 | plugins/hello/hello_test.py | plugins/hello/hello_test.py | from p1tr.test import *
class HelloTest(PluginTestCase):
@test
def hello_test(self):
for data in self.dummy_data:
self.assertEqual(self.plugin.hello(data.server, data.channel,
data.nick, data.params),
'Hello, %s!' % data.nick.split('!')[0])
| Add test case for hello plugin | Add test case for hello plugin
| Python | mit | howard/p1tr-tng,howard/p1tr-tng | <INSERT> from p1tr.test import *
class HelloTest(PluginTestCase):
<INSERT_END> <INSERT> @test
def hello_test(self):
for data in self.dummy_data:
self.assertEqual(self.plugin.hello(data.server, data.channel,
data.nick, data.params),
'Hello, %s!' % ... | Add test case for hello plugin
| |
7d862be1aba5a062eeaf54ada9587278e7e93f5b | apps/provider/urls.py | apps/provider/urls.py | from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
url(r'^fhir/push$', fhir_practitioner_push, name="fhir_p... | from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
url(r'^fhir/practioner/push$', fhir_practitioner_push, n... | Change fhir practitioner url and add organization url | Change fhir practitioner url and add organization url
| Python | apache-2.0 | TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client,TransparentHealth/hhs_oauth_client | <REPLACE_OLD> url(r'^fhir/push$', <REPLACE_NEW> url(r'^fhir/practioner/push$', <REPLACE_END> <REPLACE_OLD> name="fhir_practitioner_push"),
) <REPLACE_NEW> name="fhir_practitioner_push"),
url(r'^fhir/organization/push$', fhir_organization_push, name="fhir_organization_push"),
)
<REPLACE_END> <|endoftext|> from _... | Change fhir practitioner url and add organization url
from __future__ import absolute_import
from __future__ import unicode_literals
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^pjson/push$', pjson_provider_push, name="pjson_provider_push"),
ur... |
155ab92dd2ff4340e4773e22762d52f557b300e8 | dividebatur/tests/test_ticket_sort_key.py | dividebatur/tests/test_ticket_sort_key.py | from ..aecdata import ticket_sort_key
def apply_ticket_sort(items):
return list(sorted(items, key=ticket_sort_key))
def test_a_c_already_sorted():
assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])
def test_a_c_reversed():
assert(apply_ticket_sort(['C', 'B', 'A']) == ['A', 'B', 'C'])
def ... | from ..aecdata.utils import ticket_sort_key
def apply_ticket_sort(items):
return list(sorted(items, key=ticket_sort_key))
def test_a_c_already_sorted():
assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])
def test_a_c_reversed():
assert(apply_ticket_sort(['C', 'B', 'A']) == ['A', 'B', 'C'])
... | Fix import in ticket_sort_key tests. | Fix import in ticket_sort_key tests.
| Python | apache-2.0 | grahame/dividebatur,grahame/dividebatur,grahame/dividebatur | <REPLACE_OLD> ..aecdata <REPLACE_NEW> ..aecdata.utils <REPLACE_END> <|endoftext|> from ..aecdata.utils import ticket_sort_key
def apply_ticket_sort(items):
return list(sorted(items, key=ticket_sort_key))
def test_a_c_already_sorted():
assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])
def test_... | Fix import in ticket_sort_key tests.
from ..aecdata import ticket_sort_key
def apply_ticket_sort(items):
return list(sorted(items, key=ticket_sort_key))
def test_a_c_already_sorted():
assert(apply_ticket_sort(['A', 'B', 'C']) == ['A', 'B', 'C'])
def test_a_c_reversed():
assert(apply_ticket_sort(['C',... |
1e6f3689a21e12104792236d88e7596cb8397ba5 | mezzanine/core/management.py | mezzanine/core/management.py |
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import models as auth_app
from django.db.models.signals import post_syncdb
def create_demo_user(app, created_models, verbosity, db, **kwargs):
if settings.DEBUG and User in created_models:
if verbosity >... |
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import models as auth_app
from django.db.models.signals import post_syncdb
def create_demo_user(app, created_models, verbosity, **kwargs):
if settings.DEBUG and User in created_models:
if verbosity >= 2:... | Fix post_syncdb signal for demo user to work with Django 1.1 | Fix post_syncdb signal for demo user to work with Django 1.1
| Python | bsd-2-clause | nikolas/mezzanine,AlexHill/mezzanine,webounty/mezzanine,douglaskastle/mezzanine,nikolas/mezzanine,christianwgd/mezzanine,jjz/mezzanine,guibernardino/mezzanine,stbarnabas/mezzanine,promil23/mezzanine,spookylukey/mezzanine,ryneeverett/mezzanine,gradel/mezzanine,jerivas/mezzanine,fusionbox/mezzanine,guibernardino/mezzanin... | <DELETE> db, <DELETE_END> <|endoftext|>
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import models as auth_app
from django.db.models.signals import post_syncdb
def create_demo_user(app, created_models, verbosity, **kwargs):
if settings.DEBUG and User in cr... | Fix post_syncdb signal for demo user to work with Django 1.1
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import models as auth_app
from django.db.models.signals import post_syncdb
def create_demo_user(app, created_models, verbosity, db, **kwargs):
if set... |
3bdc7250f7a40ef4b3ad5f431c6b6e3e92ccacc8 | app.py | app.py | from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save
app = Flask(__name__)
# @app.route('/')
# def main():
# return redirect('/index')
@app.route('/', methods=['GET', 'PO... | from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save
app = Flask(__name__)
@app.route('/')
def main():
return redirect('/index')
@app.route('/index', methods=['GET', 'POS... | Revert "Remove redirect to avoid Chrome privacy error" | Revert "Remove redirect to avoid Chrome privacy error"
This reverts commit e5322958f14b2428b74de726476fd98adae8c454.
| Python | mit | gsganden/pitcher-reports,gsganden/pitcher-reports | <REPLACE_OLD> Flask(__name__)
# @app.route('/')
# def main():
# <REPLACE_NEW> Flask(__name__)
@app.route('/')
def main():
<REPLACE_END> <REPLACE_OLD> redirect('/index')
@app.route('/', <REPLACE_NEW> redirect('/index')
@app.route('/index', <REPLACE_END> <|endoftext|> from flask import Flask, render_template, reque... | Revert "Remove redirect to avoid Chrome privacy error"
This reverts commit e5322958f14b2428b74de726476fd98adae8c454.
from flask import Flask, render_template, request, redirect
import requests
import pandas as pd
from datetime import datetime
from bokeh.plotting import figure, output_notebook, output_file, save
app ... |
9bb1aebbfc0ca0ff893bafe99de3c32c2ba99952 | tests/test_model.py | tests/test_model.py | from context import models
from models import model
import unittest
class test_logic_core(unittest.TestCase):
def setUp(self):
self.room = model.Room(20, 'new_room')
self.room1 = model.Room(6, 'new_room1')
self.livingspace = model.LivingSpace('orange')
self.office = model.Office(... | from context import models
from models import model
import unittest
class test_model(unittest.TestCase):
def setUp(self):
self.room = model.Room(20, 'new_room')
self.room1 = model.Room(6, 'new_room1')
self.livingspace = model.LivingSpace('orange')
self.office = model.Office('manj... | Refactor model test to test added properties | Refactor model test to test added properties
| Python | mit | georgreen/Geoogreen-Mamboleo-Dojo-Project | <REPLACE_OLD> test_logic_core(unittest.TestCase):
<REPLACE_NEW> test_model(unittest.TestCase):
<REPLACE_END> <INSERT> self.room1.name)
self.room1.name = "changedname"
self.assertEqual('changedname', <INSERT_END> <REPLACE_OLD> model.Room))
<REPLACE_NEW> model.Room))
def test_room_current_populati... | Refactor model test to test added properties
from context import models
from models import model
import unittest
class test_logic_core(unittest.TestCase):
def setUp(self):
self.room = model.Room(20, 'new_room')
self.room1 = model.Room(6, 'new_room1')
self.livingspace = model.LivingSpace... |
701238e19f4eaa6ce1f1c14e6e56d9544e402ed7 | test/test_language.py | test/test_language.py | import unittest
from charset_normalizer.normalizer import CharsetNormalizerMatches as CnM
from glob import glob
from os.path import basename
class TestLanguageDetection(unittest.TestCase):
SHOULD_BE = {
'sample.1.ar.srt': 'Arabic',
'sample.1.fr.srt': 'French',
'sample.1.gr.srt': 'Greek',
... | Add test to verify if language was detected properly | Add test to verify if language was detected properly
| Python | mit | Ousret/charset_normalizer,ousret/charset_normalizer,Ousret/charset_normalizer,ousret/charset_normalizer | <REPLACE_OLD> <REPLACE_NEW> import unittest
from charset_normalizer.normalizer import CharsetNormalizerMatches as CnM
from glob import glob
from os.path import basename
class TestLanguageDetection(unittest.TestCase):
SHOULD_BE = {
'sample.1.ar.srt': 'Arabic',
'sample.1.fr.srt': 'French',
... | Add test to verify if language was detected properly
| |
b2fbb48049abbfff7f1636059f8ad7eda07667c7 | test/single_system/all.py | test/single_system/all.py | import sys, unittest
import bmc_test
import power_test
import xmlrunner
tests = []
tests.extend(bmc_test.tests)
#tests.extend(power_test.tests)
if __name__ == '__main__':
for test in tests:
test.system = sys.argv[1]
suite = unittest.TestLoader().loadTestsFromTestCase(test)
xmlrunner.XMLTes... | import sys, unittest, os
import bmc_test
import power_test
import xmlrunner
tests = []
tests.extend(bmc_test.tests)
#tests.extend(power_test.tests)
if __name__ == '__main__':
for test in tests:
test.system = sys.argv[1]
suite = unittest.TestLoader().loadTestsFromTestCase(test)
result = xml... | Return a bad error code when a test fails | Return a bad error code when a test fails
| Python | bsd-3-clause | Cynerva/pyipmi,emaadmanzoor/pyipmi | <REPLACE_OLD> unittest
import <REPLACE_NEW> unittest, os
import <REPLACE_END> <INSERT> result = <INSERT_END> <INSERT> if result.failures or result.errors:
os.sys.exit(1)
<INSERT_END> <|endoftext|> import sys, unittest, os
import bmc_test
import power_test
import xmlrunner
tests = []
tests.extend(bm... | Return a bad error code when a test fails
import sys, unittest
import bmc_test
import power_test
import xmlrunner
tests = []
tests.extend(bmc_test.tests)
#tests.extend(power_test.tests)
if __name__ == '__main__':
for test in tests:
test.system = sys.argv[1]
suite = unittest.TestLoader().loadTests... |
3786d778f583f96cb4dce37a175d2c460a020724 | cnxauthoring/events.py | cnxauthoring/events.py | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from pyramid.events import NewRequest
def add_cors_headers(request, response):
settings = request.reg... | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from pyramid.events import NewRequest
def add_cors_headers(request, response):
settings = request.reg... | Fix Access-Control-Allow-Origin to return the request origin | Fix Access-Control-Allow-Origin to return the request origin
request.host is the host part of the request url. For example, if
webview is trying to access http://localhost:8080/users/profile,
request. It's the Origin field in the headers that we should be
matching.
| Python | agpl-3.0 | Connexions/cnx-authoring | <REPLACE_OLD> request.host <REPLACE_NEW> request.headers.get('Origin') <REPLACE_END> <REPLACE_OLD> request.host))
<REPLACE_NEW> request.headers.get('Origin')))
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero... | Fix Access-Control-Allow-Origin to return the request origin
request.host is the host part of the request url. For example, if
webview is trying to access http://localhost:8080/users/profile,
request. It's the Origin field in the headers that we should be
matching.
# -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013... |
de42731ab97a7d4272c44cc750891906aa5b4417 | buildlet/runner/ipythonparallel.py | buildlet/runner/ipythonparallel.py | """
Task runner using IPython parallel interface.
See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.
.. _The IPython task interface:
http://ipython.org/ipython-doc/dev/parallel/parallel_task.html
.. _DAG Dependencies:
http://ipython.org/ipython-doc/dev/parallel/dag_depe... | """
Task runner using IPython parallel interface.
See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.
.. _The IPython task interface:
http://ipython.org/ipython-doc/dev/parallel/parallel_task.html
.. _DAG Dependencies:
http://ipython.org/ipython-doc/dev/parallel/dag_depe... | Raise error if any in IPythonParallelRunner.wait_tasks | Raise error if any in IPythonParallelRunner.wait_tasks
| Python | bsd-3-clause | tkf/buildlet | <REPLACE_OLD> self.view.wait(self.results.values())
<REPLACE_NEW> for r in self.results.values():
r.get()
<REPLACE_END> <|endoftext|> """
Task runner using IPython parallel interface.
See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.
.. _The IPython task interfa... | Raise error if any in IPythonParallelRunner.wait_tasks
"""
Task runner using IPython parallel interface.
See `The IPython task interface`_ and `IPython Documentation`_
in `IPython Documentation`_.
.. _The IPython task interface:
http://ipython.org/ipython-doc/dev/parallel/parallel_task.html
.. _DAG Dependencies:... |
20b450c4cd0ff9c57d894fa263056ff4cd2dbf07 | vim_turing_machine/machines/merge_business_hours/vim_merge_business_hours.py | vim_turing_machine/machines/merge_business_hours/vim_merge_business_hours.py | from vim_turing_machine.machines.merge_business_hours.merge_business_hours import merge_business_hours_transitions
from vim_turing_machine.vim_machine import VimTuringMachine
if __name__ == '__main__':
merge_business_hours = VimTuringMachine(merge_business_hours_transitions(), debug=True)
merge_business_hours... | Add a vim version of merge business hours | Add a vim version of merge business hours
| Python | mit | ealter/vim_turing_machine,ealter/vim_turing_machine | <INSERT> from vim_turing_machine.machines.merge_business_hours.merge_business_hours import merge_business_hours_transitions
from vim_turing_machine.vim_machine import VimTuringMachine
if __name__ == '__main__':
<INSERT_END> <INSERT> merge_business_hours = VimTuringMachine(merge_business_hours_transitions(), debug=... | Add a vim version of merge business hours
| |
35c44f0f585d11dea632e509b9eec20d4697dc9d | functions/eitu/timeedit_to_csv.py | functions/eitu/timeedit_to_csv.py | import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url):
return ics_parser.parse(... | import requests
import csv
from datetime import datetime
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fetch_and_parse(url)... | Sort events by start and iso format datetimes | Sort events by start and iso format datetimes
| Python | mit | christianknu/eitu,christianknu/eitu,eitu/eitu,christianknu/eitu,eitu/eitu | <REPLACE_OLD> csv
import <REPLACE_NEW> csv
from datetime import datetime
import <REPLACE_END> <REPLACE_OLD> duplicate events
events <REPLACE_NEW> duplicates and sort
events <REPLACE_END> <REPLACE_OLD> events}.values()
# <REPLACE_NEW> events}.values()
events = sorted(events, key=lambda e: e['DTSTART'])
# <REPLACE_END>... | Sort events by start and iso format datetimes
import requests
import csv
import ics_parser
URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics'
URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics'
def fet... |
0fdb93fb73142315fe404b9a161ef19af0d920cd | tests/test_bawlerd.py | tests/test_bawlerd.py | import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.c... | import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_location_list(locations=())
user_conf = os.path.join(
os.path.expanduser('~'),
bawlerd.c... | Add simple test for config builder | Add simple test for config builder
Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
| Python | bsd-3-clause | beezz/pg_bawler,beezz/pg_bawler | <INSERT> config
def test_read_config_files(self):
config_base = os.path.join(
os.path.abspath(os.path.dirname(__file__)), 'configs')
locations = [
os.path.join(config_base, 'etc'),
os.path.join(config_base, 'home'),
]
config = bawlerd.conf.read_co... | Add simple test for config builder
Signed-off-by: Michal Kuffa <005ee1c97edba97d164343c993afee612ac25a0c@gmail.com>
import io
import os
from textwrap import dedent
from pg_bawler import bawlerd
class TestBawlerdConfig:
def test_build_config_location_list(self):
assert not bawlerd.conf.build_config_loc... |
33e1c781b0e430cb1e0df19d02ed06a193f9d202 | waterbutler/identity.py | waterbutler/identity.py | import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if r... | import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identi... | Make use of a register decorator | Make use of a register decorator
| Python | apache-2.0 | CenterForOpenScience/waterbutler,kwierman/waterbutler,TomBaxter/waterbutler,rafaeldelucena/waterbutler,Ghalko/waterbutler,RCOSDP/waterbutler,hmoco/waterbutler,felliott/waterbutler,rdhyee/waterbutler,Johnetordoff/waterbutler,icereval/waterbutler,chrisseto/waterbutler,cosenal/waterbutler | <REPLACE_OLD> asyncio
from <REPLACE_NEW> asyncio
import aiohttp
from <REPLACE_END> <REPLACE_OLD> settings
@asyncio.coroutine
def fetch_rest_identity(params):
<REPLACE_NEW> settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
ra... | Make use of a register decorator
import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# ... |
256dc6da740050f71615f00924cd85346aaa1e99 | rotational-cipher/rotational_cipher.py | rotational-cipher/rotational_cipher.py | import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
rules = shift_rules(n)
return "".join(map(lambda k: rules.get(k, k), s))
def shift_rules(n):
shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
return {k:v for k,v in zip(UPPER+LOWER, shifted)}
| import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
rules = shift_rules(n)
return "".join(rules.get(ch, ch) for ch in s)
def shift_rules(n):
shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
return {k:v for k,v in zip(UPPER+LOWER, shifted)}
| Use a comprehension instead of a lambda function | Use a comprehension instead of a lambda function
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | <REPLACE_OLD> "".join(map(lambda k: rules.get(k, k), s))
def <REPLACE_NEW> "".join(rules.get(ch, ch) for ch in s)
def <REPLACE_END> <|endoftext|> import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
rules = shift_rules(n)
return "".join(rules.get(ch, ch) for ch in... | Use a comprehension instead of a lambda function
import string
UPPER = string.ascii_uppercase
LOWER = string.ascii_lowercase
def rotate(s, n):
rules = shift_rules(n)
return "".join(map(lambda k: rules.get(k, k), s))
def shift_rules(n):
shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n]
retur... |
6547d653491adb6ab46e4a3a5f8251129719d3f7 | login/middleware.py | login/middleware.py | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api'):
... | from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
and not request.path.startswith('/api') \
... | Remove infinite loop if user is neither native nor verified | Remove infinite loop if user is neither native nor verified
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | <REPLACE_OLD> request.path.startswith('/api'):
<REPLACE_NEW> request.path.startswith('/api') \
and not request.user.is_anonymous:
<REPLACE_END> <REPLACE_OLD> request.user.is_anonymous \
<REPLACE_NEW> request.user.is_native:
if not request.path == DETACH_PATH:
<REPLACE_END> <REPLAC... | Remove infinite loop if user is neither native nor verified
from django.conf import settings
from django.http import HttpResponseRedirect
DETACH_PATH = '/user/detach'
ACTIVATE_PATH = '/user/activate'
class DetachMiddleware(object):
def process_request(self, request):
if not request.path == '/login/' \
... |
95529efca6a2e3c3544aeb306aaf62a02f2f5408 | primes.py | primes.py | import sys
Max=int(sys.argv[1]) # get Max from command line args
P = {x: True for x in range(2,Max)} # first assume numbers are prime
for i in range(2, int(Max** (0.5))): # until square root of Max
if P[i]: #
for j in range(i*i, Max, i): # mark all multiples of a prime
P[j]=False # as not beein... | import array
import math
import sys
n = int(sys.argv[1])
nums = array.array('i', [False] * 2 + [True] * (n - 2))
upper_lim = int(math.sqrt(n))
i = 2
while i <= upper_lim:
if nums[i]:
m = i**2
while m < n:
nums[m] = False
m += i
i += 1
print(len([x for x in nums if nums... | Make Python code equivalent to Ruby | Make Python code equivalent to Ruby
Using a dictionary instead is really unfair.
Small variation: m must not be equal to n. Not sure how the algorithm is meant is exactly...
| Python | mit | oliworx/chartbench,oliworx/chartbench,oliworx/chartbench,oliworx/chartbench,oliworx/chartbench | <REPLACE_OLD> sys
Max=int(sys.argv[1]) # get Max from command line args
P <REPLACE_NEW> array
import math
import sys
n <REPLACE_END> <REPLACE_OLD> {x: True <REPLACE_NEW> int(sys.argv[1])
nums = array.array('i', [False] * 2 + [True] * (n - 2))
upper_lim = int(math.sqrt(n))
i = 2
while i <= upper_lim:
if num... | Make Python code equivalent to Ruby
Using a dictionary instead is really unfair.
Small variation: m must not be equal to n. Not sure how the algorithm is meant is exactly...
import sys
Max=int(sys.argv[1]) # get Max from command line args
P = {x: True for x in range(2,Max)} # first assume numbers are prime
f... |
93b1f8e67b1154fd595a938ca41877eb76c7e995 | lcd.py | lcd.py | from telnetlib import Telnet
import time
tn = Telnet('192.168.1.15', 13666, None)
#tn.interact()
tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 string\n")
tn.write("widget_add s1 w2 string\n")
tn.write("widget_set s1 w1 1 1 {It is a truth u}\n")
tn.w... | #!/usr/bin/env python
from telnetlib import Telnet
import time
import sys
tn = Telnet('192.168.1.15', 13666, None)
pipe_contents = sys.stdin.read()
pipe_contents = pipe_contents.replace('\n', ' ')
tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 strin... | Read standard input instead of hard-coded strings. | Read standard input instead of hard-coded strings.
| Python | mit | zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie,zimolzak/Raspberry-Pi-newbie | <REPLACE_OLD> from <REPLACE_NEW> #!/usr/bin/env python
from <REPLACE_END> <REPLACE_OLD> time
tn <REPLACE_NEW> time
import sys
tn <REPLACE_END> <REPLACE_OLD> None)
#tn.interact()
tn.write("hello\n")
tn.write("screen_add <REPLACE_NEW> None)
pipe_contents = sys.stdin.read()
pipe_contents = pipe_contents.replace('\n', ... | Read standard input instead of hard-coded strings.
from telnetlib import Telnet
import time
tn = Telnet('192.168.1.15', 13666, None)
#tn.interact()
tn.write("hello\n")
tn.write("screen_add s1\n")
tn.write("screen_set s1 -priority 1\n")
tn.write("widget_add s1 w1 string\n")
tn.write("widget_add s1 w2 string\n")
tn.wr... |
52c5f4ddfde8db6179f11c3bec2bc8be69eed238 | flake8_docstrings.py | flake8_docstrings.py | # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __version__
def __in... | # -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import io
import pep8
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
version = __... | Handle stdin in the plugin | Handle stdin in the plugin
Closes #2
| Python | mit | PyCQA/flake8-docstrings | <INSERT> io
import pep8
import <INSERT_END> <INSERT> STDIN_NAMES = set(['stdin', '-', '(none)', None])
<INSERT_END> <REPLACE_OLD> filename
<REPLACE_NEW> filename
self.source = self.load_source()
self.checker = pep257.PEP257Checker()
<REPLACE_END> <REPLACE_OLD> pep257.check([self.filename]):
<... | Handle stdin in the plugin
Closes #2
# -*- coding: utf-8 -*-
"""pep257 docstrings convention needs error code and class parser for be
included as module into flake8
"""
import pep257
__version__ = '0.2.1.post1'
class pep257Checker(object):
"""flake8 needs a class to check python file."""
name = 'pep257'
... |
638f6fb659792ec69b9df25391001241d12c39bd | src/python/grpcio_tests/tests_aio/unit/init_test.py | src/python/grpcio_tests/tests_aio/unit/init_test.py | # Copyright 2019 The gRPC Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | # Copyright 2019 The gRPC Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | Expand alternatives to import aio module | Expand alternatives to import aio module
| Python | apache-2.0 | donnadionne/grpc,nicolasnoble/grpc,jtattermusch/grpc,vjpai/grpc,stanley-cheung/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,ejona86/grpc,stanley-cheung/grpc,stanley-cheung/grpc,nicolasnoble/grpc,stanley-cheung/grpc,jtattermusch/grpc,stanley-cheung/grpc,ejona86/grpc,stanley-cheung/grpc,ctiller/grpc,vjpai/grpc... | <REPLACE_OLD> unittest
import grpc
from <REPLACE_NEW> unittest
from <REPLACE_END> <INSERT> async def test_grpc(self):
import grpc # pylint: disable=wrong-import-position
channel = grpc.aio.insecure_channel('dummy')
self.assertIsInstance(channel, grpc.aio.Channel)
<INSERT_END> <INSERT> i... | Expand alternatives to import aio module
# Copyright 2019 The gRPC Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
20a92ff1ffe143193d95235c7a5ea8e9edb0df64 | yowsup/layers/protocol_acks/protocolentities/ack_outgoing.py | yowsup/layers/protocol_acks/protocolentities/ack_outgoing.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):
'''
<ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
</ack>
'''
def __init__(self, _id, _class, _ty... | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):
'''
<ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
</ack>
<ack to="{{GROUP_JID}}" participant="{{JID}... | Include participant in outgoing ack | Include participant in outgoing ack
| Python | mit | ongair/yowsup,biji/yowsup | <REPLACE_OLD> </ack>
<REPLACE_NEW> </ack>
<ack to="{{GROUP_JID}}" participant="{{JID}}" id="{{MESSAGE_ID}}" class="receipt" type="{{read | }}">
</ack>
<REPLACE_END> <REPLACE_OLD> _to):
<REPLACE_NEW> _to, _participant = None):
<REPLACE_END> <REPLACE_OLD> _to)
<REPLACE_NEW> _to, _participant)
<REPLACE_E... | Include participant in outgoing ack
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):
'''
<ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
</ack>
'''
... |
ea17a76c4ada65dac9e909b930c938a24ddb99b2 | tests/formatter/test_csver.py | tests/formatter/test_csver.py | import unittest, argparse
from echolalia.formatter.csver import Formatter
class CsverTestCase(unittest.TestCase):
def setUp(self):
self.parser = argparse.ArgumentParser()
self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
self.formatter = Formatter()
def test_add_args(self):
... | import unittest, argparse
from echolalia.formatter.csver import Formatter
class CsverTestCase(unittest.TestCase):
def setUp(self):
self.parser = argparse.ArgumentParser()
self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
self.formatter = Formatter()
def test_add_args(self):
... | Fix no header test for csv formatter | Fix no header test for csv formatter
| Python | mit | eiri/echolalia-prototype | <REPLACE_OLD> "a,1\r\nb,2\r\nc,3\r\n"
<REPLACE_NEW> "a,1\r\nb,2\r\nc,3\r\n"
self.assertEqual(result, expect)
<REPLACE_END> <|endoftext|> import unittest, argparse
from echolalia.formatter.csver import Formatter
class CsverTestCase(unittest.TestCase):
def setUp(self):
self.parser = argparse.ArgumentParse... | Fix no header test for csv formatter
import unittest, argparse
from echolalia.formatter.csver import Formatter
class CsverTestCase(unittest.TestCase):
def setUp(self):
self.parser = argparse.ArgumentParser()
self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
self.formatter = Forma... |
3b467abc665a1807d8a1adbba1be78d40f77b4ce | tests/unit/dataactcore/factories/job.py | tests/unit/dataactcore/factories/job.py | import factory
from factory import fuzzy
from datetime import date, datetime, timezone
from dataactcore.models import jobModels
class SubmissionFactory(factory.Factory):
class Meta:
model = jobModels.Submission
submission_id = None
datetime_utc = fuzzy.FuzzyDateTime(
datetime(2010, 1, 1... | Add factory for Submission model | Add factory for Submission model
| Python | cc0-1.0 | chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency/data-act-broker-backend,fedspendingtransparency/data-act-broker-backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend | <INSERT> import factory
from factory import fuzzy
from datetime import date, datetime, timezone
from dataactcore.models import jobModels
class SubmissionFactory(factory.Factory):
<INSERT_END> <INSERT> class Meta:
model = jobModels.Submission
submission_id = None
datetime_utc = fuzzy.FuzzyDateTim... | Add factory for Submission model
| |
05f0969ee8b9374c2fe5bce2c753fb4619432f0d | tests/integration/runners/jobs.py | tests/integration/runners/jobs.py | # -*- coding: utf-8 -*-
'''
Tests for the salt-run command
'''
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class ManageTest(integration.ShellCase):
'''
Test the manage runner
'''
def test_active(self)... | # -*- coding: utf-8 -*-
'''
Tests for the salt-run command
'''
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class ManageTest(integration.ShellCase):
'''
Test the manage runner
'''
def test_active(self)... | Fix the output now that we are using the default output (nested) instead of hard coding it to yaml | Fix the output now that we are using the default output (nested) instead of hard coding it to yaml
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | <REPLACE_OLD> ['{}'])
<REPLACE_NEW> [])
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
'''
Tests for the salt-run command
'''
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class ManageTest(integration.ShellCas... | Fix the output now that we are using the default output (nested) instead of hard coding it to yaml
# -*- coding: utf-8 -*-
'''
Tests for the salt-run command
'''
# Import Salt Testing libs
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
# Import salt libs
import integration
class Man... |
0177066012b3373753cba8baf86f00a365d7147b | findaconf/tests/config.py | findaconf/tests/config.py | # coding: utf-8
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
unset_app(db)
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = config(
'DATABASE_UR... | # coding: utf-8
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
# set test vars
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
# set test db
if db:
app.config['SQLALCHEMY_DATABASE_URI'] = co... | Fix bug that used dev db instead of test db | Fix bug that used dev db instead of test db
| Python | mit | cuducos/findaconf,koorukuroo/findaconf,cuducos/findaconf,koorukuroo/findaconf,koorukuroo/findaconf,cuducos/findaconf | <REPLACE_OLD> unset_app(db)
<REPLACE_NEW>
# set test vars
<REPLACE_END> <INSERT>
# set test db
<INSERT_END> <INSERT>
# create test app
<INSERT_END> <INSERT>
# create and feed db tables
<INSERT_END> <INSERT>
# start from a clean db
db.session.remove()
db.... | Fix bug that used dev db instead of test db
# coding: utf-8
from decouple import config
from findaconf.tests.fake_data import fake_conference, seed
def set_app(app, db=False):
unset_app(db)
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
if db:
app.config['SQLALCHEMY_DATA... |
d666c5c818fbfc00f642cfeb24cb90aab94035cd | keyring/devpi_client.py | keyring/devpi_client.py | import contextlib
import functools
import pluggy
import keyring
from keyring.errors import KeyringError
hookimpl = pluggy.HookimplMarker("devpiclient")
# https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205
suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}... | import contextlib
import functools
import pluggy
import keyring.errors
hookimpl = pluggy.HookimplMarker("devpiclient")
# https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205
suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {})
def restore_signature(func):
... | Remove superfluous import by using the exception from the namespace. | Remove superfluous import by using the exception from the namespace.
| Python | mit | jaraco/keyring | <REPLACE_OLD> keyring
from keyring.errors import KeyringError
hookimpl <REPLACE_NEW> keyring.errors
hookimpl <REPLACE_END> <REPLACE_OLD> wrapper
@hookimpl()
@restore_signature
@suppress(KeyringError)
def <REPLACE_NEW> wrapper
@hookimpl()
@restore_signature
@suppress(keyring.errors.KeyringError)
def <REPLACE_END... | Remove superfluous import by using the exception from the namespace.
import contextlib
import functools
import pluggy
import keyring
from keyring.errors import KeyringError
hookimpl = pluggy.HookimplMarker("devpiclient")
# https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205
suppress = t... |
06b9982ea716daa627a0beb700721c7ca53601fd | run.py | run.py | #!/usr/bin/env python
if __name__ == '__main__':
import os
import sys
if sys.version_info[0:2] < (3, 4):
raise SystemExit('python 3.4+ is required')
root_path = os.path.abspath(os.path.dirname(__file__))
try:
import mtp_common
# NB: this version does not need to be update... | #!/usr/bin/env python
if __name__ == '__main__':
import os
import sys
if sys.version_info[0:2] < (3, 6):
raise SystemExit('Python 3.6+ is required')
root_path = os.path.abspath(os.path.dirname(__file__))
try:
import mtp_common
# NB: this version does not need to be update... | Support only python versions 3.6+ explicitly …which has been the assumption for a while as 3.6 features are already in use and base docker images use 3.6. | Support only python versions 3.6+ explicitly
…which has been the assumption for a while as 3.6 features are already in use and base docker images use 3.6.
| Python | mit | ministryofjustice/money-to-prisoners-transaction-uploader | <REPLACE_OLD> 4):
raise SystemExit('python 3.4+ <REPLACE_NEW> 6):
raise SystemExit('Python 3.6+ <REPLACE_END> <|endoftext|> #!/usr/bin/env python
if __name__ == '__main__':
import os
import sys
if sys.version_info[0:2] < (3, 6):
raise SystemExit('Python 3.6+ is required')
root_... | Support only python versions 3.6+ explicitly
…which has been the assumption for a while as 3.6 features are already in use and base docker images use 3.6.
#!/usr/bin/env python
if __name__ == '__main__':
import os
import sys
if sys.version_info[0:2] < (3, 4):
raise SystemExit('python 3.4+ is requi... |
20654d833deb332dbbe683e6d4e38cef1cc58dd3 | webcomix/tests/test_comic_availability.py | webcomix/tests/test_comic_availability.py | import pytest
from webcomix.comic import Comic
from webcomix.supported_comics import supported_comics
from webcomix.util import check_first_pages
@pytest.mark.slow
def test_supported_comics():
for comic_name, comic_info in supported_comics.items():
first_pages = Comic.verify_xpath(*comic_info)
ch... | import pytest
from webcomix.comic import Comic
from webcomix.supported_comics import supported_comics
from webcomix.util import check_first_pages
@pytest.mark.slow
def test_supported_comics():
for comic_name, comic_info in supported_comics.items():
comic = Comic(comic_name, *comic_info)
first_pag... | Refactor comic availability test to reflect changes to Comic class | Refactor comic availability test to reflect changes to Comic class
| Python | mit | J-CPelletier/WebComicToCBZ,J-CPelletier/webcomix,J-CPelletier/webcomix | <INSERT> comic = Comic(comic_name, *comic_info)
<INSERT_END> <REPLACE_OLD> Comic.verify_xpath(*comic_info)
<REPLACE_NEW> comic.verify_xpath()
<REPLACE_END> <|endoftext|> import pytest
from webcomix.comic import Comic
from webcomix.supported_comics import supported_comics
from webcomix.util import check_first... | Refactor comic availability test to reflect changes to Comic class
import pytest
from webcomix.comic import Comic
from webcomix.supported_comics import supported_comics
from webcomix.util import check_first_pages
@pytest.mark.slow
def test_supported_comics():
for comic_name, comic_info in supported_comics.items... |
52da8be7ffe6ea2ba09acf3ce44b9a79758b115b | glance/version.py | glance/version.py | # Copyright 2012 OpenStack Foundation
#
# 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 l... | # Copyright 2012 OpenStack Foundation
#
# 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 l... | Remove runtime dep on python pbr | Remove runtime dep on python pbr
| Python | apache-2.0 | redhat-openstack/glance,redhat-openstack/glance | <REPLACE_OLD> License.
import pbr.version
version_info = pbr.version.VersionInfo('glance')
<REPLACE_NEW> License.
GLANCE_VENDOR = "OpenStack Foundation"
GLANCE_PRODUCT = "OpenStack Glance"
GLANCE_PACKAGE = None # OS distro package version suffix
loaded = False
class VersionInfo(object):
release = "REDHATG... | Remove runtime dep on python pbr
# Copyright 2012 OpenStack Foundation
#
# 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
#
# ... |
9261db252969c69ede633d4a4c02bb87c7bc1434 | quilt/__init__.py | quilt/__init__.py | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as ... | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as ... | Add docstring for main module | Add docstring for main module
| Python | mit | bjoernricks/python-quilt,vadmium/python-quilt | <REPLACE_OLD> USA
__version_info__ <REPLACE_NEW> USA
""" A python implementation of quilt """
__version_info__ <REPLACE_END> <REPLACE_OLD> '.'.join(__version_info__)
<REPLACE_NEW> '.'.join(__version_info__)
<REPLACE_END> <|endoftext|> # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implem... | Add docstring for main module
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Less... |
dfa76a4ad4a15e4068135b5f82ef5a00763c4b57 | open_humans/models.py | open_humans/models.py | from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
user = models.OneToOneField(User)
about_me = models.TextField()
@receiver(post_save, sender=User, dispatch_uid='create_pro... | Add Profile model and post-save hook | Add Profile model and post-save hook
| Python | mit | OpenHumans/open-humans,OpenHumans/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans,OpenHumans/open-humans,PersonalGenomesOrg/open-humans,PersonalGenomesOrg/open-humans | <INSERT> from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
class Profile(models.Model):
<INSERT_END> <INSERT> user = models.OneToOneField(User)
about_me = models.TextField()
@receiver(post_save, sender=... | Add Profile model and post-save hook
| |
1b921e83d000d024e38b0d7f81984b699cb49fac | fmriprep/cli/sample_openfmri_tasks_list.py | fmriprep/cli/sample_openfmri_tasks_list.py | # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
A tool to generate a tasks_list.sh file for running fmriprep
on subjects downloaded with datalad with sample_openfmri.py
"""
import os
import glob
CMDLINE = """\
{fmriprep_cm... | Add simple script to write tasks_list file | [skip ci] Add simple script to write tasks_list file
| Python | bsd-3-clause | poldracklab/fmriprep,poldracklab/preprocessing-workflow,oesteban/preprocessing-workflow,poldracklab/fmriprep,poldracklab/fmriprep,oesteban/fmriprep,oesteban/fmriprep,oesteban/fmriprep,poldracklab/preprocessing-workflow,oesteban/preprocessing-workflow | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
A tool to generate a tasks_list.sh file for running fmriprep
on subjects downloaded with datalad with sample_openfmri.py
"""
import os
import glob... | [skip ci] Add simple script to write tasks_list file
| |
7865d7a37562be8b0af9b3668043d8c08138814b | examples/get_each_args.py | examples/get_each_args.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from clint.arguments import Args
from clint.textui import puts, colored
all_args = Args().grouped
for item in all_args:
if item is not '_':
puts(colored.red("key:%s"%item))
print(all_args[item].all)
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from clint.arguments import Args
from clint.textui import puts, colored
all_args = Args().grouped
for item in all_args:
if item is not '_':
puts(colored.red("key:%s"%item))
print(all_ar... | Add clint to import paths | Add clint to import paths
| Python | isc | kennethreitz/clint | <REPLACE_OLD> -*-
from <REPLACE_NEW> -*-
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from <REPLACE_END> <|endoftext|> #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from clint.arguments import Args
from clint.textui import puts, co... | Add clint to import paths
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from clint.arguments import Args
from clint.textui import puts, colored
all_args = Args().grouped
for item in all_args:
if item is not '_':
puts(colored.red("key:%s"%item))
print(all_args[item].all)
|
8773f652a1cf78299e3dd5ba9296ca2a50143caa | aiopg/__init__.py | aiopg/__init__.py | import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.3.2'
version = __version__ +... | import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ = '0.4.0a0'
version = __version__... | Revert master version to 0.4.0a0 | Revert master version to 0.4.0a0
| Python | bsd-2-clause | eirnym/aiopg,graingert/aiopg,hyzhak/aiopg,aio-libs/aiopg,luhn/aiopg,nerandell/aiopg | <REPLACE_OLD> '0.3.2'
version <REPLACE_NEW> '0.4.0a0'
version <REPLACE_END> <|endoftext|> import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', '... | Revert master version to 0.4.0a0
import re
import sys
from collections import namedtuple
from .connection import connect, Connection
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info')
__version__ ... |
eacfca844e5ab590acfcd193e2ca1fa379e10009 | alg_strongly_connected_components.py | alg_strongly_connected_components.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def strongly_connected_components():
"""Strongly connected components for graph.
Procedure:
- Call (Depth First Search) DFS on graph G to
compute finish times for each vertex.
- C... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _previsit():
pass
def _postvisit():
pass
def dfs():
pass
def _transpose_graph():
pass
def _inverse_postvisit_vertex():
pass
def strongly_connected_components():
"""Strongl... | Add strongly connected components's methods | Add strongly connected components's methods
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | <INSERT> _previsit():
pass
def _postvisit():
pass
def dfs():
pass
def _transpose_graph():
pass
def _inverse_postvisit_vertex():
pass
def <INSERT_END> <REPLACE_OLD> finish <REPLACE_NEW> postvisit <REPLACE_END> <|endoftext|> from __future__ import absolute_import
from __future__ import print... | Add strongly connected components's methods
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def strongly_connected_components():
"""Strongly connected components for graph.
Procedure:
- Call (Depth First Search) DFS on graph G to
co... |
a15e363718ab41c5e02b9eaa919fb689cd266af6 | nose2/tests/_common.py | nose2/tests/_common.py | """Common functionality."""
import os.path
import tempfile
import shutil
import sys
class TestCase(unittest2.TestCase):
"""TestCase extension.
If the class variable _RUN_IN_TEMP is True (default: False), tests will be
performed in a temporary directory, which is deleted afterwards.
"""
... | Add common module for our tests | Add common module for our tests
| Python | bsd-2-clause | ptthiem/nose2,ojengwa/nose2,ezigman/nose2,ojengwa/nose2,leth/nose2,ezigman/nose2,ptthiem/nose2,little-dude/nose2,leth/nose2,little-dude/nose2 | <REPLACE_OLD> <REPLACE_NEW> """Common functionality."""
import os.path
import tempfile
import shutil
import sys
class TestCase(unittest2.TestCase):
"""TestCase extension.
If the class variable _RUN_IN_TEMP is True (default: False), tests will be
performed in a temporary directory, which is ... | Add common module for our tests
| |
8a573dae750b1b9415df0c9e2c019750171e66f0 | migrations.py | migrations.py | import os
import json
from dateutil.parser import parse
from scrapi.util import safe_filename
def migrate_from_old_scrapi():
for dirname, dirs, filenames in os.walk('archive'):
for filename in filenames:
oldpath = os.path.join(dirname, filename)
source, sid, dt = dirname.split('/... | import os
import json
from dateutil.parser import parse
from scrapi.util import safe_filename
def migrate_from_old_scrapi():
for dirname, dirs, filenames in os.walk('archive'):
for filename in filenames:
oldpath = os.path.join(dirname, filename)
source, sid, dt = dirname.split('/... | Move json print methods into if statement | Move json print methods into if statement
| Python | apache-2.0 | erinspace/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,fabianvf/scrapi,fabianvf/scrapi,ostwald/scrapi,mehanig/scrapi,alexgarciac/scrapi,jeffreyliu3230/scrapi,felliott/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,erinspace/scrapi | <REPLACE_OLD> sort_keys=True)
<REPLACE_NEW> sort_keys=True)
print old_json
print new_json
<REPLACE_END> <DELETE> print old_json
print new_json
<DELETE_END> <|endoftext|> import os
import json
from dateutil.parser import parse
from scrapi.util import safe_fil... | Move json print methods into if statement
import os
import json
from dateutil.parser import parse
from scrapi.util import safe_filename
def migrate_from_old_scrapi():
for dirname, dirs, filenames in os.walk('archive'):
for filename in filenames:
oldpath = os.path.join(dirname, filename)
... |
84c4097caf0db678859252c58c1822d12d11c924 | polly/plugins/publish/upload_avalon_asset.py | polly/plugins/publish/upload_avalon_asset.py | from pyblish import api
from avalon.api import Session
class UploadAvalonAsset(api.InstancePlugin):
"""Write to files and metadata
This plug-in exposes your data to others by encapsulating it
into a new version.
"""
label = "Upload"
order = api.IntegratorOrder + 0.1
depends = ["Integrat... | Implement automatic upload, enabled via AVALON_UPLOAD | Implement automatic upload, enabled via AVALON_UPLOAD
| Python | mit | mindbender-studio/config | <REPLACE_OLD> <REPLACE_NEW> from pyblish import api
from avalon.api import Session
class UploadAvalonAsset(api.InstancePlugin):
"""Write to files and metadata
This plug-in exposes your data to others by encapsulating it
into a new version.
"""
label = "Upload"
order = api.IntegratorOrder +... | Implement automatic upload, enabled via AVALON_UPLOAD
| |
d70360601669f9e58072cd121de79896690471fd | buildlet/datastore/tests/test_inmemory.py | buildlet/datastore/tests/test_inmemory.py | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.TestCase):
dstype = DataValueInMemory
... | import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase,
MixInNestableTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixIn... | Fix and add tests for datastore.inmemory | Fix and add tests for datastore.inmemory
| Python | bsd-3-clause | tkf/buildlet | <REPLACE_OLD> DataStreamInMemory, DataStoreNestableInMemory)
from <REPLACE_NEW> DataStreamInMemory,
DataStoreNestableInMemory, DataStoreNestableInMemoryAutoValue)
from <REPLACE_END> <REPLACE_OLD> MixInStreamTestCase, <REPLACE_NEW> MixInStreamTestCase,
MixInNestableTestCase, <REPLACE_END> <REPLACE_OLD> TestDataS... | Fix and add tests for datastore.inmemory
import unittest
from ..inmemory import (
DataValueInMemory, DataStreamInMemory, DataStoreNestableInMemory)
from .mixintestcase import (
MixInValueTestCase, MixInStreamTestCase, MixInNestableAutoValueTestCase)
class TestDataValueInMemory(MixInValueTestCase, unittest.T... |
5e3f3b83974c4826cddcfdb73f2d4eb4abe2aca1 | examples/test_download_files.py | examples/test_download_files.py | from seleniumbase import BaseCase
class DownloadTests(BaseCase):
def test_download_files(self):
self.open("https://pypi.org/project/seleniumbase/#files")
pkg_header = self.get_text("h1.package-header__name")
pkg_name = pkg_header.replace(" ", "-")
whl_file = pkg_name + "-... | Add test for asserting downloaded files | Add test for asserting downloaded files
| Python | mit | seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase | <INSERT> from seleniumbase import BaseCase
class DownloadTests(BaseCase):
<INSERT_END> <INSERT> def test_download_files(self):
self.open("https://pypi.org/project/seleniumbase/#files")
pkg_header = self.get_text("h1.package-header__name")
pkg_name = pkg_header.replace(" ", "-")
... | Add test for asserting downloaded files
| |
391c1681eaeabfdbe65a64a1bb8b05beca30141e | wqflask/utility/db_tools.py | wqflask/utility/db_tools.py | from MySQLdb import escape_string as escape
def create_in_clause(items):
"""Create an in clause for mysql"""
in_clause = ', '.join("'{}'".format(x) for x in mescape(*items))
in_clause = '( {} )'.format(in_clause)
return in_clause
def mescape(*items):
"""Multiple escape"""
escaped = [escape(str... | from MySQLdb import escape_string as escape_
def create_in_clause(items):
"""Create an in clause for mysql"""
in_clause = ', '.join("'{}'".format(x) for x in mescape(*items))
in_clause = '( {} )'.format(in_clause)
return in_clause
def mescape(*items):
"""Multiple escape"""
return [escape_(st... | Add global method to convert binary string to plain string | Add global method to convert binary string to plain string
* wqflask/utility/db_tools.py: escape_string returns a binary string which
introduces a bug when composing sql query string. The escaped strings have to be
converted to plain text.
| Python | agpl-3.0 | pjotrp/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,zsloan/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2,genenetwork/genenetwork2,zsloan/genenetwork2,genenetwork/genenetwork2,pjotrp/genenetwork2 | <REPLACE_OLD> escape
def <REPLACE_NEW> escape_
def <REPLACE_END> <REPLACE_OLD> in_clause
def <REPLACE_NEW> in_clause
def <REPLACE_END> <REPLACE_OLD> escaped = [escape(str(item)) <REPLACE_NEW> return [escape_(str(item)).decode('utf8') <REPLACE_END> <REPLACE_OLD> items]
#print("escaped is:", escaped)
<REPLACE_... | Add global method to convert binary string to plain string
* wqflask/utility/db_tools.py: escape_string returns a binary string which
introduces a bug when composing sql query string. The escaped strings have to be
converted to plain text.
from MySQLdb import escape_string as escape
def create_in_clause(items):
... |
35778c48ba197803e2688732cf11d346838e7b7f | tests/integration/test_sqs.py | tests/integration/test_sqs.py | import os
from asyncaws import SQS
from tornado.testing import AsyncTestCase, gen_test
aws_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']
aws_region = os.environ['AWS_REGION']
class TestSQS(AsyncTestCase):
sqs = SQS(aws_key_id, aws_key_secret, aws_region, async=Fals... | Add first integration test for SQS | Add first integration test for SQS
| Python | mit | MA3STR0/AsyncAWS | <INSERT> import os
from asyncaws import SQS
from tornado.testing import AsyncTestCase, gen_test
aws_key_id = os.environ['AWS_ACCESS_KEY_ID']
aws_key_secret = os.environ['AWS_SECRET_ACCESS_KEY']
aws_region = os.environ['AWS_REGION']
class TestSQS(AsyncTestCase):
<INSERT_END> <INSERT> sqs = SQS(aws_key_id, aws_key_... | Add first integration test for SQS
| |
8259a733e1f039cea55cfc5aad7d69e0fb37c43c | tests.py | tests.py | from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.asse... | from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance(twenty_usd, Money)
self.asse... | Add test that validates method call | Add test that validates method call
| Python | mit | mdsrosa/money-conversion-py | <REPLACE_OLD> twenty_brl.amount)
if <REPLACE_NEW> twenty_brl.amount)
def test_invalid_method_pattern_call(self):
with self.assertRaises(AttributeError):
twenty_brl = self.twenty_euro.batman()
if <REPLACE_END> <|endoftext|> from money_conversion.money import Money
import unittest
class Mo... | Add test that validates method call
from money_conversion.money import Money
import unittest
class MoneyClassTest(unittest.TestCase):
def setUp(self):
self.twenty_euro = Money(20, 'EUR')
def test_convert_euro_to_usd(self):
twenty_usd = self.twenty_euro.to_usd()
self.assertIsInstance... |
71db89cad06dc0aa81e0a7178712e8beb7e7cb01 | turbustat/tests/test_cramer.py | turbustat/tests/test_cramer.py | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for Cramer
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Cramer_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class testCramer... | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for Cramer
'''
import numpy.testing as npt
from ..statistics import Cramer_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
def test_cramer():
tester = \
Cramer_Distance(dataset1... | Remove importing UnitCase from Cramer tests | Remove importing UnitCase from Cramer tests
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat | <REPLACE_OLD> Cramer
'''
from unittest import TestCase
import numpy as np
import <REPLACE_NEW> Cramer
'''
import <REPLACE_END> <REPLACE_OLD> computed_distances
class testCramer(TestCase):
def test_cramer(self):
self.tester <REPLACE_NEW> computed_distances
def test_cramer():
tester <REPLACE_END> ... | Remove importing UnitCase from Cramer tests
# Licensed under an MIT open source license - see LICENSE
'''
Test functions for Cramer
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Cramer_Distance
from ._testing_data import \
dataset1, dataset2, compute... |
57051d3e59a4664a536588c19ae0581cb92f1350 | timed/redmine/admin.py | timed/redmine/admin.py | from django.contrib import admin
from timed.projects.admin import ProjectAdmin
from timed.projects.models import Project
from timed_adfinis.redmine.models import RedmineProject
admin.site.unregister(Project)
class RedmineProjectInline(admin.StackedInline):
model = RedmineProject
@admin.register(Project)
class... | Add RedmineProject as inline of ProjectAdmin | Add RedmineProject as inline of ProjectAdmin
| Python | agpl-3.0 | adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend | <INSERT> from django.contrib import admin
from timed.projects.admin import ProjectAdmin
from timed.projects.models import Project
from timed_adfinis.redmine.models import RedmineProject
admin.site.unregister(Project)
class RedmineProjectInline(admin.StackedInline):
<INSERT_END> <INSERT> model = RedmineProject
... | Add RedmineProject as inline of ProjectAdmin
| |
9732f5e1bb667b6683c9e97db03d293373909da6 | tests/test_process.py | tests/test_process.py | import unittest
import logging
import time
from util import get_hostname
from tests.common import load_check
from nose.plugins.attrib import attr
logging.basicConfig()
@attr('process')
class ProcessTestCase(unittest.TestCase):
def build_config(self, config, n):
critical_low = [2, 2, 2, -1, 2, -2, 2]
... | Add tests for process check | Add tests for process check
This test call the check method in process 7 times and check the process_check
output. The result should be:
1 OK
2 WARNING
4 CRITICAL
| Python | bsd-3-clause | jraede/dd-agent,benmccann/dd-agent,packetloop/dd-agent,PagerDuty/dd-agent,benmccann/dd-agent,truthbk/dd-agent,jshum/dd-agent,citrusleaf/dd-agent,gphat/dd-agent,AniruddhaSAtre/dd-agent,AniruddhaSAtre/dd-agent,jvassev/dd-agent,urosgruber/dd-agent,jraede/dd-agent,Mashape/dd-agent,huhongbo/dd-agent,oneandoneis2/dd-agent,br... | <REPLACE_OLD> <REPLACE_NEW> import unittest
import logging
import time
from util import get_hostname
from tests.common import load_check
from nose.plugins.attrib import attr
logging.basicConfig()
@attr('process')
class ProcessTestCase(unittest.TestCase):
def build_config(self, config, n):
critical_low =... | Add tests for process check
This test call the check method in process 7 times and check the process_check
output. The result should be:
1 OK
2 WARNING
4 CRITICAL
| |
27ab83010f7cc8308debfec16fab38544a9c7ce7 | running.py | running.py | import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky... | import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
import json
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encoding='utf-8')
darksky_key = parser.get('darksky', 'key')
tcx = tc... | Print all hourly temperatures from run date | Print all hourly temperatures from run date
| Python | mit | briansuhr/slowburn | <REPLACE_OLD> dateutil.parser
t = '1984-06-02T19:05:00.000Z'
# <REPLACE_NEW> dateutil.parser
import json
# <REPLACE_END> <REPLACE_OLD> "?exclude=currently,flags").read()
print(darksky_request)
class <REPLACE_NEW> "?exclude=currently,flags").read()
# Decode JSON
darksky_json = json.loads(darksky_request.decode('utf-... | Print all hourly temperatures from run date
import tcxparser
from configparser import ConfigParser
from datetime import datetime
import urllib.request
import dateutil.parser
t = '1984-06-02T19:05:00.000Z'
# Darksky weather API
# Create config file manually
parser = ConfigParser()
parser.read('slowburn.config', encodi... |
7e98a76ac455a8c69950104766719cde313bbb74 | tests/CrawlerProcess/asyncio_deferred_signal.py | tests/CrawlerProcess/asyncio_deferred_signal.py | import asyncio
import sys
import scrapy
from scrapy.crawler import CrawlerProcess
from twisted.internet.defer import Deferred
class UppercasePipeline:
async def _open_spider(self, spider):
spider.logger.info("async pipeline opened!")
await asyncio.sleep(0.1)
def open_spider(self, spider):
... | import asyncio
import sys
from scrapy import Spider
from scrapy.crawler import CrawlerProcess
from scrapy.utils.defer import deferred_from_coro
from twisted.internet.defer import Deferred
class UppercasePipeline:
async def _open_spider(self, spider):
spider.logger.info("async pipeline opened!")
a... | Use deferred_from_coro in asyncio test | Use deferred_from_coro in asyncio test
| Python | bsd-3-clause | elacuesta/scrapy,elacuesta/scrapy,scrapy/scrapy,pablohoffman/scrapy,dangra/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,dangra/scrapy,scrapy/scrapy,pawelmhm/scrapy,dangra/scrapy,pawelmhm/scrapy,pablohoffman/scrapy,elacuesta/scrapy,scrapy/scrapy | <REPLACE_OLD> sys
import scrapy
from <REPLACE_NEW> sys
from scrapy import Spider
from <REPLACE_END> <INSERT> scrapy.utils.defer import deferred_from_coro
from <INSERT_END> <REPLACE_OLD> Deferred.fromFuture(loop.create_task(self._open_spider(spider)))
<REPLACE_NEW> deferred_from_coro(self._open_spider(spider))
<R... | Use deferred_from_coro in asyncio test
import asyncio
import sys
import scrapy
from scrapy.crawler import CrawlerProcess
from twisted.internet.defer import Deferred
class UppercasePipeline:
async def _open_spider(self, spider):
spider.logger.info("async pipeline opened!")
await asyncio.sleep(0.... |
abe40e3c82ef1f351275a59b2e537f43530caa0c | app/cleanup_stories.py | app/cleanup_stories.py | from pymongo import MongoClient
from fetch_stories import get_mongo_client, close_mongo_client
from bson import ObjectId
from datetime import datetime, timedelta
def remove_old_stories():
client = get_mongo_client()
db = client.get_default_database()
article_collection = db['articles']
two_days_ag... | Clean up db script (remove articles older than two days). | Clean up db script (remove articles older than two days).
| Python | mit | hw3jung/Gucci,hw3jung/Gucci | <INSERT> from pymongo import MongoClient
from fetch_stories import get_mongo_client, close_mongo_client
from bson import ObjectId
from datetime import datetime, timedelta
def remove_old_stories():
<INSERT_END> <INSERT> client = get_mongo_client()
db = client.get_default_database()
article_collection = d... | Clean up db script (remove articles older than two days).
| |
7c49517c3c24d239c2bd44d82916b4f3d90ca1e2 | utilities/__init__.py | utilities/__init__.py | #! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
... | #! /usr/bin/env python
from subprocess import Popen, PIPE
def popen(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
def get_stdout(cmd):
"""
Fork the specified command, returning stdout
... | Switch to using popen as the function name to stick more to subprocess naming | Switch to using popen as the function name to stick more to subprocess naming
| Python | mit | IanLee1521/utilities | <REPLACE_OLD> launch(cmd):
<REPLACE_NEW> popen(cmd):
<REPLACE_END> <REPLACE_OLD> launch(cmd)[0]
def <REPLACE_NEW> popen(cmd)[0]
def <REPLACE_END> <REPLACE_OLD> launch(cmd)[1]
<REPLACE_NEW> popen(cmd)[1]
<REPLACE_END> <|endoftext|> #! /usr/bin/env python
from subprocess import Popen, PIPE
def popen(cmd):
... | Switch to using popen as the function name to stick more to subprocess naming
#! /usr/bin/env python
from subprocess import Popen, PIPE
def launch(cmd):
"""
Fork the specified command, returning a tuple of (stdout, stderr)
"""
return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
d... |
9a52024ff5b8175ee8b8d4665d3c8c667003019b | glitter/blocks/redactor/tests.py | glitter/blocks/redactor/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.contrib.auth import get_user_model
from django.contrib.conte... | Add test for redactor block creation | Add test for redactor block creation
| Python | bsd-3-clause | developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,developersociety/django-glitter,blancltd/django-glitter,blancltd/django-glitter | <REPLACE_OLD> """
This <REPLACE_NEW> # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
This <REPLACE_END> <INSERT> django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from <INSERT_END> <REPLACE_OLD> TestCase
class SimpleTest(TestCase):
<REPLACE_NEW> ... | Add test for redactor block creation
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
... |
ca6d80429cb8ccdac7669b444e5b4d2e88aed098 | site/cgi/csv-columns.py | site/cgi/csv-columns.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Give back the columns of a CSV and the in
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
import cgi
import csv
import sys
import codecs
import cgitb
CSV_DIR = '../csv/' # CSV upload directory
# UTF-8 hack
# from http://stackoverflow.com/a/11764727
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Give back the columns of a CSV and the in
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
import cgi
import csv
import sys
import codecs
import cgitb
CSV_DIR = '../csv/' # CSV upload directory
# UTF-8 hack
# from http://stackoverflow.com/a/11764727
... | Fix column listing, use double quotes for JSON remove old stuff | Fix column listing, use double quotes for JSON remove old stuff
| Python | agpl-3.0 | alejosanchez/CSVBenford,alejosanchez/CSVBenford | <REPLACE_OLD> next(r)
c2 = [ n.encode('utf-8') for n in col_names ]
response = { 'columns' : c2 }
print <REPLACE_NEW> next(r)
print <REPLACE_END> <REPLACE_OLD> 'columns' <REPLACE_NEW> "columns" <REPLACE_END> <REPLACE_OLD> "'" <REPLACE_NEW> '"' <REPLACE_END> <REPLACE_OLD> "','".join(col_names).encode('utf-8') <REPLA... | Fix column listing, use double quotes for JSON remove old stuff
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Give back the columns of a CSV and the in
# http://www.tutorialspoint.com/python/python_cgi_programming.htm
import cgi
import csv
import sys
import codecs
import cgitb
CSV_DIR = '../csv/' # CSV upload directo... |
9674a0869c2a333f74178e305677259e7ac379c3 | examples/ignore_websocket.py | examples/ignore_websocket.py | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CON... | # This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configured
# to use a proxy (i.e. mitmproxy's regular mode), send a CON... | Make the Websocket's connection header value case-insensitive | Make the Websocket's connection header value case-insensitive
| Python | mit | liorvh/mitmproxy,ccccccccccc/mitmproxy,dwfreed/mitmproxy,mhils/mitmproxy,ryoqun/mitmproxy,Kriechi/mitmproxy,azureplus/mitmproxy,dufferzafar/mitmproxy,ikoz/mitmproxy,jpic/mitmproxy,tfeagle/mitmproxy,rauburtin/mitmproxy,MatthewShao/mitmproxy,pombredanne/mitmproxy,pombredanne/mitmproxy,laurmurclar/mitmproxy,StevenVanAcker... | <INSERT> value = flow.response.headers.get_first("Connection", None)
<INSERT_END> <REPLACE_OLD> flow.response.headers.get_first("Connection", None) <REPLACE_NEW> value and value.upper() <REPLACE_END> <REPLACE_OLD> "Upgrade":
<REPLACE_NEW> "UPGRADE":
<REPLACE_END> <|endoftext|> # This script makes mitmproxy switch... | Make the Websocket's connection header value case-insensitive
# This script makes mitmproxy switch to passthrough mode for all HTTP
# responses with "Connection: Upgrade" header. This is useful to make
# WebSockets work in untrusted environments.
#
# Note: Chrome (and possibly other browsers), when explicitly configur... |
9f922f939ec19d0d9a9a91abb3e8b0d5b010c246 | djangoautoconf/management/commands/dump_settings.py | djangoautoconf/management/commands/dump_settings.py | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Crea... | import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCommand):
args = ''
help = 'Crea... | Work around for dump setting issue. | Work around for dump setting issue.
| Python | bsd-3-clause | weijia/djangoautoconf,weijia/djangoautoconf | <REPLACE_OLD> str(value)
<REPLACE_NEW> '"'+str(value)+'"'
<REPLACE_END> <|endoftext|> import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, ... | Work around for dump setting issue.
import os
from django.core.management import BaseCommand
from django.conf import settings
def dump_attrs(obj_instance):
for attr in dir(obj_instance):
if attr != attr.upper():
continue
yield attr, getattr(obj_instance, attr)
class Command(BaseCom... |
77038432486071c9459c5ce43492905e158b7713 | Topo/LoopTopo.py | Topo/LoopTopo.py | '''
SDN project testing topo
s1
/ \
s2--s3
| |
host.. host...
'''
from mininet.topo import Topo
class LoopTopo( Topo ):
def __init__( self , n=2 ):
# Initialize topology
Topo.__init__( self)
# Add Host
h1 = self.addHost( 'h1' )
h2 = self.addHost( 'h2' )
h3 = self.addHost(... | '''
SDN project testing topo
s1
/ \
s2--s3
| |
host.. host...
'''
from mininet.topo import Topo
class LoopTopo( Topo ):
def __init__( self , n=2 ):
# Initialize topology
Topo.__init__( self)
# Add Host
h1 = self.addHost( 'h1' )
h2 = self.addHost( 'h2' )
h3 = self.addHost(... | Rename the name of topo. | Rename the name of topo.
| Python | mit | ray6/sdn,ray6/sdn,ray6/sdn | <REPLACE_OLD> 'LoopTopo': <REPLACE_NEW> 'Loop': <REPLACE_END> <|endoftext|> '''
SDN project testing topo
s1
/ \
s2--s3
| |
host.. host...
'''
from mininet.topo import Topo
class LoopTopo( Topo ):
def __init__( self , n=2 ):
# Initialize topology
Topo.__init__( self)
# Add Host
... | Rename the name of topo.
'''
SDN project testing topo
s1
/ \
s2--s3
| |
host.. host...
'''
from mininet.topo import Topo
class LoopTopo( Topo ):
def __init__( self , n=2 ):
# Initialize topology
Topo.__init__( self)
# Add Host
h1 = self.addHost( 'h1' )
h2 = self.addHost( '... |
ba0ea7491fab383992013a8379592657eedfe1ce | scripts/contrib/model_info.py | scripts/contrib/model_info.py | #!/usr/bin/env python3
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints version and model type from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if S2S_SPECIAL_NODE not in model:
print("No special Ma... | #!/usr/bin/env python3
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints keys and values from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if args.special:
if S2S_SPECIAL_NODE not in model:
... | Add printing value for any key from model.npz | Add printing value for any key from model.npz
| Python | mit | emjotde/amunmt,emjotde/amunmt,marian-nmt/marian-train,emjotde/amunmt,amunmt/marian,emjotde/amunn,amunmt/marian,emjotde/amunn,emjotde/amunmt,marian-nmt/marian-train,emjotde/amunn,marian-nmt/marian-train,emjotde/amunn,marian-nmt/marian-train,emjotde/Marian,marian-nmt/marian-train,emjotde/Marian,amunmt/marian | <REPLACE_OLD> version <REPLACE_NEW> keys <REPLACE_END> <REPLACE_OLD> model type <REPLACE_NEW> values <REPLACE_END> <REPLACE_OLD> parse_args()
<REPLACE_NEW> parse_args()
<REPLACE_END> <REPLACE_OLD> np.load(args.model)
<REPLACE_NEW> np.load(args.model)
if args.special:
<REPLACE_END> <INSERT> <INSERT_END... | Add printing value for any key from model.npz
#!/usr/bin/env python3
import sys
import argparse
import numpy as np
import yaml
DESC = "Prints version and model type from model.npz file."
S2S_SPECIAL_NODE = "special:model.yml"
def main():
args = parse_args()
model = np.load(args.model)
if S2S_SPECIAL_... |
9ee87588b2d6694cafea6415af50110ba5263d3e | bitbots_body_behaviour/src/bitbots_body_behaviour/body/actions/wait.py | bitbots_body_behaviour/src/bitbots_body_behaviour/body/actions/wait.py | # -*- coding:utf-8 -*-
"""
Wait
^^^^
.. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de>
Just waits for something (i.e. that preconditions will be fullfilled)
"""
import rospy
from bitbots_body_behaviour.body.actions.go_to import Stand
from bitbots_stackmachine.abstract_action_module import Abstra... | # -*- coding:utf-8 -*-
"""
Wait
^^^^
.. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de>
Just waits for something (i.e. that preconditions will be fullfilled)
"""
import rospy
from bitbots_body_behaviour.body.actions.go_to import Stand
from bitbots_stackmachine.abstract_action_module import Abstra... | Fix Bug in Wait logic | Fix Bug in Wait logic
| Python | bsd-3-clause | bit-bots/bitbots_behaviour | <REPLACE_OLD> > <REPLACE_NEW> < <REPLACE_END> <|endoftext|> # -*- coding:utf-8 -*-
"""
Wait
^^^^
.. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de>
Just waits for something (i.e. that preconditions will be fullfilled)
"""
import rospy
from bitbots_body_behaviour.body.actions.go_to import Stand
fr... | Fix Bug in Wait logic
# -*- coding:utf-8 -*-
"""
Wait
^^^^
.. moduleauthor:: Martin Poppinga <1popping@informatik.uni-hamburg.de>
Just waits for something (i.e. that preconditions will be fullfilled)
"""
import rospy
from bitbots_body_behaviour.body.actions.go_to import Stand
from bitbots_stackmachine.abstract_acti... |
dba74cdd2fb2a8e5be1b56bba3fdcadc40827f73 | links/utils/testing_helpers.py | links/utils/testing_helpers.py | from django.test import TestCase
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
class APITestCase(TestCase):
def setUp(self):
self.client = APIClient()
class AuthenticatedAPITestCase(APITestCase):
def setUp(self):
super(AuthenticatedAPITestCase, sel... | Create some testing helper classes | Create some testing helper classes
| Python | mit | projectweekend/Links-API,projectweekend/Links-API | <INSERT> from django.test import TestCase
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
class APITestCase(TestCase):
<INSERT_END> <INSERT> def setUp(self):
self.client = APIClient()
class AuthenticatedAPITestCase(APITestCase):
def setUp(self):
super... | Create some testing helper classes
| |
e4c5f68da949683232b520796b380e8b8f2163c7 | test/tiles/bigwig_test.py | test/tiles/bigwig_test.py | import clodius.tiles.bigwig as hgbi
import os.path as op
def test_bigwig_tiles():
filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig')
meanval = hgbi.tiles(filename, ['x.0.0'])
minval = hgbi.tiles(filename, ['x.0.0.min'])
maxval = hgbi.tiles(filename, ['x.0.0.m... | import clodius.tiles.bigwig as hgbi
import os.path as op
def test_bigwig_tiles():
filename = op.join(
'data',
'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig'
)
meanval = hgbi.tiles(filename, ['x.0.0'])
minval = hgbi.tiles(filename, ['x.0.0.min'])
maxval = hgbi.tiles(... | Test for bigWig aggregation modes | Test for bigWig aggregation modes
| Python | mit | hms-dbmi/clodius,hms-dbmi/clodius | <REPLACE_OLD> op
def <REPLACE_NEW> op
def <REPLACE_END> <REPLACE_OLD> op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig')
<REPLACE_NEW> op.join(
'data',
'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig'
)
<REPLACE_END> <REPLACE_OLD> op.join('data', '... | Test for bigWig aggregation modes
import clodius.tiles.bigwig as hgbi
import os.path as op
def test_bigwig_tiles():
filename = op.join('data', 'wgEncodeCaltechRnaSeqHuvecR1x75dTh1014IlnaPlusSignalRep2.bigWig')
meanval = hgbi.tiles(filename, ['x.0.0'])
minval = hgbi.tiles(filename, ['x.0.0.min'])
maxv... |
abd97f71e54515c057e94f7d21aa953faba3f5fc | taskflow/examples/delayed_return.py | taskflow/examples/delayed_return.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Yahoo! 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... | Add a example that activates a future when a result is ready | Add a example that activates a future when a result is ready
To allow for an engine to continue to run while at the same time
returning from a function when a component of that engine finishes
a pattern can be used that ties and engines listeners to the function
return, allowing for both to be used simulatenously.
Ch... | Python | apache-2.0 | openstack/taskflow,junneyang/taskflow,openstack/taskflow,jimbobhickville/taskflow,pombredanne/taskflow-1,junneyang/taskflow,pombredanne/taskflow-1,jimbobhickville/taskflow | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
# Copyright (C) 2014 Yahoo! 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.... | Add a example that activates a future when a result is ready
To allow for an engine to continue to run while at the same time
returning from a function when a component of that engine finishes
a pattern can be used that ties and engines listeners to the function
return, allowing for both to be used simulatenously.
Ch... | |
a8818e2058fdfaec7f283a5115619d42d23b7dde | anchorhub/builtin/github/writer.py | anchorhub/builtin/github/writer.py | """
File that initializes a Writer object designed for GitHub style markdown files.
"""
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy
import anchorhub.builtin.github.switches as ghswit... | """
File that initializes a Writer object designed for GitHub style markdown files.
"""
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy
import anchorhub.builtin.github.switches as ghswit... | Use Setext strategy in GitHub built in Writer | Use Setext strategy in GitHub built in Writer
| Python | apache-2.0 | samjabrahams/anchorhub | <INSERT> setext = MarkdownSetextWriterStrategy(opts)
<INSERT_END> <INSERT> setext, <INSERT_END> <|endoftext|> """
File that initializes a Writer object designed for GitHub style markdown files.
"""
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
... | Use Setext strategy in GitHub built in Writer
"""
File that initializes a Writer object designed for GitHub style markdown files.
"""
from anchorhub.writer import Writer
from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \
MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy
imp... |
8e907ad431dfe5395741d26ea46c50c118355d69 | src/webassets/ext/werkzeug.py | src/webassets/ext/werkzeug.py | import logging
from webassets.script import CommandLineEnvironment
__all__ = ('make_assets_action',)
def make_assets_action(environment, loaders=[]):
"""Creates a ``werkzeug.script`` action which interfaces
with the webassets command line tools.
Since Werkzeug does not provide a way to have subcommands... | import logging
from webassets.script import CommandLineEnvironment
__all__ = ('make_assets_action',)
def make_assets_action(environment, loaders=[]):
"""Creates a ``werkzeug.script`` action which interfaces
with the webassets command line tools.
Since Werkzeug does not provide a way to have subcommands... | Make the "check" command available via the Werkzeug extension. | Make the "check" command available via the Werkzeug extension.
| Python | bsd-2-clause | scorphus/webassets,wijerasa/webassets,JDeuce/webassets,heynemann/webassets,heynemann/webassets,heynemann/webassets,aconrad/webassets,aconrad/webassets,glorpen/webassets,glorpen/webassets,john2x/webassets,florianjacob/webassets,0x1997/webassets,JDeuce/webassets,0x1997/webassets,wijerasa/webassets,glorpen/webassets,aconr... | <REPLACE_OLD> clean=False, <REPLACE_NEW> check=False, clean=False,
<REPLACE_END> <REPLACE_OLD> False),
<REPLACE_NEW> False), <REPLACE_END> <REPLACE_OLD> clean])) <REPLACE_NEW> clean, check])) <REPLACE_END> <REPLACE_OLD> --watch <REPLACE_NEW> --watch, --check <REPLACE_END> <REPLACE_OLD> 'cl... | Make the "check" command available via the Werkzeug extension.
import logging
from webassets.script import CommandLineEnvironment
__all__ = ('make_assets_action',)
def make_assets_action(environment, loaders=[]):
"""Creates a ``werkzeug.script`` action which interfaces
with the webassets command line tools... |
2dcfbc9dfecef4920a8dec9f3d2362f5ece13612 | sympy/printing/tests/test_numpy.py | sympy/printing/tests/test_numpy.py | from sympy import Piecewise
from sympy.abc import x
from sympy.printing.lambdarepr import NumPyPrinter
def test_numpy_piecewise_regression():
"""
NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
breaking compatibility with numpy 1.8. This is not necessary in numpy 1.9+.
See gh-97... | Add test for NumPyPrinter regression | Add test for NumPyPrinter regression
| Python | bsd-3-clause | kevalds51/sympy,aktech/sympy,maniteja123/sympy,madan96/sympy,atreyv/sympy,madan96/sympy,jbbskinny/sympy,Vishluck/sympy,iamutkarshtiwari/sympy,skidzo/sympy,chaffra/sympy,jbbskinny/sympy,saurabhjn76/sympy,kaichogami/sympy,sahmed95/sympy,abhiii5459/sympy,wyom/sympy,wyom/sympy,drufat/sympy,oliverlee/sympy,kumarkrishna/symp... | <INSERT> from sympy import Piecewise
from sympy.abc import x
from sympy.printing.lambdarepr import NumPyPrinter
def test_numpy_piecewise_regression():
<INSERT_END> <INSERT> """
NumPyPrinter needs to print Piecewise()'s choicelist as a list to avoid
breaking compatibility with numpy 1.8. This is not necessar... | Add test for NumPyPrinter regression
| |
57ed6bb3994342fce594c9cbbb0ecde4ee8c117c | setup.py | setup.py | from setuptools import setup
setup(
name="Flask-Redistore",
version="1.0",
url="",
license="BSD",
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
description="Adds Redis support to your Flask applications",
long_description=open("README.rst").read(),
py_modules=["fl... | import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
#import here, cause outsi... | Enable running tests with py.test | Enable running tests with py.test
| Python | bsd-2-clause | dstufft/Flask-Redistore | <REPLACE_OLD> from <REPLACE_NEW> import sys
from <REPLACE_END> <REPLACE_OLD> setup
setup(
<REPLACE_NEW> setup
from setuptools.command.test import test as TestCommand
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test... | Enable running tests with py.test
from setuptools import setup
setup(
name="Flask-Redistore",
version="1.0",
url="",
license="BSD",
author="Donald Stufft",
author_email="donald.stufft@gmail.com",
description="Adds Redis support to your Flask applications",
long_description=open("READM... |
5cd3b53f677fd6ab6e77bee5b7d42cf2ac85e47f | feincms/apps.py | feincms/apps.py | # flake8: noqa
from feincms.content.application.models import *
| def __getattr__(key):
# Work around Django 3.2's autoloading of *.apps modules (AppConfig
# autodiscovery)
if key in {
"ApplicationContent",
"app_reverse",
"app_reverse_lazy",
"permalink",
"UnpackTemplateResponse",
"standalone",
"unpack",
}:
... | Add a workaround for the AppConfig autodiscovery crashes with Django 3.2 | Add a workaround for the AppConfig autodiscovery crashes with Django 3.2
| Python | bsd-3-clause | mjl/feincms,feincms/feincms,mjl/feincms,feincms/feincms,feincms/feincms,mjl/feincms | <INSERT> def __getattr__(key):
<INSERT_END> <REPLACE_OLD> flake8: noqa
from feincms.content.application.models <REPLACE_NEW> Work around Django 3.2's autoloading of *.apps modules (AppConfig
# autodiscovery)
if key in {
"ApplicationContent",
"app_reverse",
"app_reverse_lazy",
... | Add a workaround for the AppConfig autodiscovery crashes with Django 3.2
# flake8: noqa
from feincms.content.application.models import *
|
1b97aa2dae43a8988802ca532a3200f444f85db3 | markups/common.py | markups/common.py | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'))
MA... | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'))
MA... | Add initial support for pygments styles | Add initial support for pygments styles
| Python | bsd-3-clause | retext-project/pymarkups,mitya57/pymarkups | <REPLACE_OLD> 'http://cdn.mathjax.org/mathjax/latest/MathJax.js'
def get_pygments_stylesheet(selector):
try:
from <REPLACE_NEW> 'http://cdn.mathjax.org/mathjax/latest/MathJax.js'
PYGMENTS_STYLE = 'default'
def get_pygments_stylesheet(selector, style=None):
try:
from <REPLACE_END> <REPLACE_OLD> HtmlFormatter().... | Add initial support for pygments styles
# This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME'... |
e5fa10e27d9c5911b0238d23fc13acc081accc79 | utils/dates.py | utils/dates.py | # This file is part of e-Giełda.
# Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at ... | # This file is part of e-Giełda.
# Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at ... | Fix error on date save | Fix error on date save
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda | <REPLACE_OLD> datetime_to_string(datetime):
<REPLACE_NEW> datetime_to_string(date):
<REPLACE_END> <REPLACE_OLD> datetime.strftime(datetime, DT_FORMAT)
def <REPLACE_NEW> date.strftime(DT_FORMAT)
def <REPLACE_END> <|endoftext|> # This file is part of e-Giełda.
# Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz... | Fix error on date save
# This file is part of e-Giełda.
# Copyright (C) 2014-2015 Mateusz Maćkowski and Tomasz Zieliński
#
# e-Giełda is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 o... |
3785b2804c88215114e0bb21f1aab6dc0554b30c | django_react_templatetags/ssr/hypernova.py | django_react_templatetags/ssr/hypernova.py | import logging
import json
from django.conf import settings
import hypernova
from hypernova.plugins.dev_mode import DevModePlugin
logger = logging.getLogger(__name__)
class HypernovaService():
def load_or_empty(self, component, headers={}, ssr_context=None):
renderer = hypernova.Renderer(
s... | import logging
import json
from django.conf import settings
import hypernova
logger = logging.getLogger(__name__)
class HypernovaService():
def load_or_empty(self, component, headers={}, ssr_context=None):
# from hypernova.plugins.dev_mode import DevModePlugin
renderer = hypernova.Renderer(
... | Disable DevModePlugin until py3 fix is fixed upstream | Disable DevModePlugin until py3 fix is fixed upstream
| Python | mit | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags | <REPLACE_OLD> hypernova
from hypernova.plugins.dev_mode import DevModePlugin
logger <REPLACE_NEW> hypernova
logger <REPLACE_END> <INSERT> # from hypernova.plugins.dev_mode import DevModePlugin
<INSERT_END> <INSERT> # <INSERT_END> <INSERT> [],
<INSERT_END> <|endoftext|> import logging
import jso... | Disable DevModePlugin until py3 fix is fixed upstream
import logging
import json
from django.conf import settings
import hypernova
from hypernova.plugins.dev_mode import DevModePlugin
logger = logging.getLogger(__name__)
class HypernovaService():
def load_or_empty(self, component, headers={}, ssr_context=None... |
fbd37fe6404bfc1e7cec4b2137c19e7323cdde02 | street_score/project/urls.py | street_score/project/urls.py | from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home', name='ho... | from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'project.views.home', name='ho... | Correct the url for the rating instance resource | Correct the url for the rating instance resource
| Python | mit | openplans/streetscore,openplans/streetscore,openplans/streetscore | <REPLACE_OLD> url(r'^ratings/(P<id>\d+)$',
<REPLACE_NEW> url(r'^ratings/(?P<id>\d+)$',
<REPLACE_END> <|endoftext|> from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import a... | Correct the url for the rating instance resource
from django.conf.urls import patterns, include, url
from django.views import generic as views
from . import resources
# Uncomment the next two lines to enable the admin:
from django.contrib.gis import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example... |
1ba88cf7d087c2783306854ea3fbc16c5fe17df4 | wagtail/utils/compat.py | wagtail/utils/compat.py | def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
return getattr(rel, 'related_model', rel.model)
| import django
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
if django.VERSION >= (1, 8):
return rel.related_model
else:
return r... | Check Django version instead of hasattr | Check Django version instead of hasattr
| Python | bsd-3-clause | mayapurmedia/wagtail,chrxr/wagtail,darith27/wagtail,mjec/wagtail,rv816/wagtail,rsalmaso/wagtail,stevenewey/wagtail,KimGlazebrook/wagtail-experiment,kurtw/wagtail,serzans/wagtail,m-sanders/wagtail,KimGlazebrook/wagtail-experiment,JoshBarr/wagtail,JoshBarr/wagtail,inonit/wagtail,kaedroho/wagtail,zerolab/wagtail,FlipperPA... | <REPLACE_OLD> def <REPLACE_NEW> import django
def <REPLACE_END> <INSERT> if django.VERSION >= (1, 8):
<INSERT_END> <REPLACE_OLD> getattr(rel, 'related_model', rel.model)
<REPLACE_NEW> rel.related_model
else:
return rel.model
<REPLACE_END> <|endoftext|> import django
def get_related_model(rel):... | Check Django version instead of hasattr
def get_related_model(rel):
# In Django 1.7 and under, the related model is accessed by doing: rel.model
# This was renamed in Django 1.8 to rel.related_model. rel.model now returns
# the base model.
return getattr(rel, 'related_model', rel.model)
|
21d5acb0ed340f15feccd5938ae51d47739f930a | falmer/commercial/queries.py | falmer/commercial/queries.py | import graphene
from .models import Offer
from . import types
class Query(graphene.ObjectType):
all_offers = graphene.List(types.Offer)
def resolve_all_offers(self, info):
return Offer.objects.all()
| import graphene
from .models import Offer
from . import types
class Query(graphene.ObjectType):
all_offers = graphene.List(types.Offer)
def resolve_all_offers(self, info):
return Offer.objects.order_by('company_name').all()
| Order offers by company name | Order offers by company name
Closes #373
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer | <REPLACE_OLD> Offer.objects.all()
<REPLACE_NEW> Offer.objects.order_by('company_name').all()
<REPLACE_END> <|endoftext|> import graphene
from .models import Offer
from . import types
class Query(graphene.ObjectType):
all_offers = graphene.List(types.Offer)
def resolve_all_offers(self, info):
return... | Order offers by company name
Closes #373
import graphene
from .models import Offer
from . import types
class Query(graphene.ObjectType):
all_offers = graphene.List(types.Offer)
def resolve_all_offers(self, info):
return Offer.objects.all()
|
62017dc7dc210d09e8f6753ad86365ac679f4a0a | oscar/apps/catalogue/categories.py | oscar/apps/catalogue/categories.py | from django.db.models import get_model
Category = get_model('catalogue', 'category')
def create_from_sequence(bits):
"""
Create categories from an iterable
"""
if len(bits) == 1:
# Get or create root node
try:
root = Category.objects.get(depth=1, name=bits[0])
exce... | from django.db.models import get_model
Category = get_model('catalogue', 'category')
def create_from_sequence(bits):
"""
Create categories from an iterable
"""
if len(bits) == 1:
# Get or create root node
name = bits[0]
try:
# Category names should be unique at the... | Rework category creation from breadcrumbs | Rework category creation from breadcrumbs
We now handle MultipleObjectsReturned exceptions, which are possible as
we are looking up based on non-unique filters.
| Python | bsd-3-clause | vovanbo/django-oscar,adamend/django-oscar,MatthewWilkes/django-oscar,manevant/django-oscar,django-oscar/django-oscar,WadeYuChen/django-oscar,elliotthill/django-oscar,sasha0/django-oscar,WillisXChen/django-oscar,jinnykoo/wuyisj,Jannes123/django-oscar,makielab/django-oscar,WadeYuChen/django-oscar,lijoantony/django-oscar,... | <INSERT> name = bits[0]
<INSERT_END> <INSERT> # Category names should be unique at the depth=1
<INSERT_END> <REPLACE_OLD> name=bits[0])
<REPLACE_NEW> name=name)
<REPLACE_END> <REPLACE_OLD> Category.add_root(name=bits[0])
<REPLACE_NEW> Category.add_root(name=name)
except Category.MultipleO... | Rework category creation from breadcrumbs
We now handle MultipleObjectsReturned exceptions, which are possible as
we are looking up based on non-unique filters.
from django.db.models import get_model
Category = get_model('catalogue', 'category')
def create_from_sequence(bits):
"""
Create categories from an... |
b97f97710a63c1d0c501c14e49dd0e26d8fb92d5 | rabbitmq-connector.py | rabbitmq-connector.py | import asyncio
import aioamqp
@asyncio.coroutine
def callback(channel, body, envelope, properties):
print(body)
@asyncio.coroutine
def connect():
try:
transport, protocol = yield from aioamqp.connect()
channel = yield from protocol.channel()
except aioamqp.AmqpClosedConnection:
pri... | Add basic python script for recieving mnemosyne AMQP messages | Add basic python script for recieving mnemosyne AMQP messages
| Python | agpl-3.0 | jgraichen/mnemosyne,jgraichen/mnemosyne,jgraichen/mnemosyne | <INSERT> import asyncio
import aioamqp
@asyncio.coroutine
def callback(channel, body, envelope, properties):
<INSERT_END> <INSERT> print(body)
@asyncio.coroutine
def connect():
try:
transport, protocol = yield from aioamqp.connect()
channel = yield from protocol.channel()
except aioamqp.Amq... | Add basic python script for recieving mnemosyne AMQP messages
| |
e6181c5d7c95af23ee6d51d125642104782f5cf1 | Python/136_SingleNumber.py | Python/136_SingleNumber.py | class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#Using XOR to find the single number.
#Because every number appears twice, while N^N=0, 0^N=N,
#XOR is cummutative, so the order of elements does not matter.
... | Add solution for 136_Single Number with XOR operation. | Add solution for 136_Single Number with XOR operation.
| Python | mit | comicxmz001/LeetCode,comicxmz001/LeetCode | <INSERT> class Solution(object):
<INSERT_END> <INSERT> def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#Using XOR to find the single number.
#Because every number appears twice, while N^N=0, 0^N=N,
#XOR is cummutative, so the order of e... | Add solution for 136_Single Number with XOR operation.
| |
0409580aed43b6a0556fcc4b8e6e9252d9f082ea | froide/publicbody/management/commands/validate_publicbodies.py | froide/publicbody/management/commands/validate_publicbodies.py | from io import StringIO
from contextlib import contextmanager
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from froide.helper.email_sending import send_mail
from ...validators import P... | from io import StringIO
from contextlib import contextmanager
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from froide.helper.email_sending import send_mail
from ...validators import P... | Use queryset in validate publicbodies command | Use queryset in validate publicbodies command | Python | mit | stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide | <REPLACE_OLD> PublicBody.objects.all().iterator()
<REPLACE_NEW> PublicBody.objects.all()
<REPLACE_END> <|endoftext|> from io import StringIO
from contextlib import contextmanager
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import translation
from django.util... | Use queryset in validate publicbodies command
from io import StringIO
from contextlib import contextmanager
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from froide.helper.email_sending... |
d698d4ce3002db3b518e061075f294cf9b0089a6 | aspc/senate/urls.py | aspc/senate/urls.py | from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', DocumentList.as_view(), name="document_list_page"),
url(r'^pre... | from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', DocumentList.as_view(), name="document_list_page"),
url(r'^pos... | Remove the preview prefix from the positions URL pattern | Remove the preview prefix from the positions URL pattern
| Python | mit | theworldbright/mainsite,aspc/mainsite,aspc/mainsite,aspc/mainsite,theworldbright/mainsite,aspc/mainsite,theworldbright/mainsite,theworldbright/mainsite | <REPLACE_OLD> url(r'^preview/positions/$', <REPLACE_NEW> url(r'^positions/$', <REPLACE_END> <|endoftext|> from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
... | Remove the preview prefix from the positions URL pattern
from django.conf.urls import patterns, include, url
from aspc.senate.views import DocumentList, AppointmentList
urlpatterns = patterns('',
url(r'^documents/$', DocumentList.as_view(), name="document_list"),
url(r'^documents/(?P<page>[0-9]+)/$', Document... |
4570ce14333ebc0bae3e09a59f28d7170cfc4621 | dci/alembic/versions/b58867f72568_add_feeder_role.py | dci/alembic/versions/b58867f72568_add_feeder_role.py | #
# Copyright (C) 2017 Red Hat, 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 writin... | Add the feeder role in the ROLES table | Feeder: Add the feeder role in the ROLES table
Change-Id: I4c09e0a5e7d08975602a683f4cecbf993cdec4ba
| Python | apache-2.0 | redhat-cip/dci-control-server,enovance/dci-control-server,redhat-cip/dci-control-server,enovance/dci-control-server | <REPLACE_OLD> <REPLACE_NEW> #
# Copyright (C) 2017 Red Hat, 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 applicab... | Feeder: Add the feeder role in the ROLES table
Change-Id: I4c09e0a5e7d08975602a683f4cecbf993cdec4ba
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.