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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c86b61a23ad9b3a152bb6644cb5dde5a4b42fbc9 | readthedocs/projects/management/commands/dump_project_remote_repo_relation.py | readthedocs/projects/management/commands/dump_project_remote_repo_relation.py | import json
from django.core.management.base import BaseCommand
from readthedocs.projects.models import Project
class Command(BaseCommand):
help = "Dump Project and RemoteRepository Relationship in JSON format"
def handle(self, *args, **options):
data = []
queryset = Project.objects.filter... | Add Management Command to Dump Project and RemoteRepository Relationship in JSON format | Add Management Command to Dump Project and RemoteRepository Relationship in JSON format
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | <REPLACE_OLD> <REPLACE_NEW> import json
from django.core.management.base import BaseCommand
from readthedocs.projects.models import Project
class Command(BaseCommand):
help = "Dump Project and RemoteRepository Relationship in JSON format"
def handle(self, *args, **options):
data = []
quer... | Add Management Command to Dump Project and RemoteRepository Relationship in JSON format
| |
760af101c3b47fa4cf4aaeba5bc67aa94d2ba060 | src/Exscript/Interpreter/stdlib/IPv4/util.py | src/Exscript/Interpreter/stdlib/IPv4/util.py | import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l << n) != 0:
return n + 1
return 0
def _highest_bit(number):
if number == 0:
return 0
number -= 1
number |= number >> 1
number |= number >> 2
number |= number >> 4... | import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l << n) != 0:
return n + 1
return 0
def _highest_bit(number):
if number == 0:
return 0
number -= 1
number |= number >> 1
number |= number >> 2
number |= number >> 4... | Enforce endianess when converting IPs to long. | Enforce endianess when converting IPs to long.
git-svn-id: 21715c51dd601a1fb57681abbfe4e8ed6f4259bf@205 4c10cf09-d433-0410-9a0a-09c53010615a
| Python | mit | maximumG/exscript,knipknap/exscript,knipknap/exscript,maximumG/exscript | <REPLACE_OLD> struct.unpack('L', <REPLACE_NEW> struct.unpack('!L', <REPLACE_END> <REPLACE_OLD> socket.inet_ntoa(struct.pack('L', <REPLACE_NEW> socket.inet_ntoa(struct.pack('!L', <REPLACE_END> <|endoftext|> import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l <... | Enforce endianess when converting IPs to long.
git-svn-id: 21715c51dd601a1fb57681abbfe4e8ed6f4259bf@205 4c10cf09-d433-0410-9a0a-09c53010615a
import socket, struct, math
def _least_bit(number):
for n in range(0, 31):
if number & (0x00000001l << n) != 0:
return n + 1
return 0
def _highest_... |
d535cf76b3129c0e5b6908a720bdf3e3a804e41b | mopidy/mixers/gstreamer_software.py | mopidy/mixers/gstreamer_software.py | import multiprocessing
from mopidy.mixers import BaseMixer
from mopidy.utils.process import pickle_connection
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*arg... | from mopidy.mixers import BaseMixer
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
super(GStreamerSoftwareMixer, self).__init__(*args, **kwargs)
def _get_volume(self):
return self.backend.output... | Update GStreamer software mixer to use new output API | Update GStreamer software mixer to use new output API
| Python | apache-2.0 | SuperStarPL/mopidy,bacontext/mopidy,dbrgn/mopidy,ali/mopidy,quartz55/mopidy,adamcik/mopidy,liamw9534/mopidy,ali/mopidy,swak/mopidy,liamw9534/mopidy,abarisain/mopidy,swak/mopidy,mopidy/mopidy,pacificIT/mopidy,swak/mopidy,diandiankan/mopidy,adamcik/mopidy,bencevans/mopidy,hkariti/mopidy,glogiotatidis/mopidy,vrs01/mopidy,... | <REPLACE_OLD> import multiprocessing
from <REPLACE_NEW> from <REPLACE_END> <REPLACE_OLD> BaseMixer
from mopidy.utils.process import pickle_connection
class <REPLACE_NEW> BaseMixer
class <REPLACE_END> <DELETE> my_end, other_end = multiprocessing.Pipe()
self.backend.output_queue.put({
'command': 'g... | Update GStreamer software mixer to use new output API
import multiprocessing
from mopidy.mixers import BaseMixer
from mopidy.utils.process import pickle_connection
class GStreamerSoftwareMixer(BaseMixer):
"""Mixer which uses GStreamer to control volume in software."""
def __init__(self, *args, **kwargs):
... |
c485ac39ede0bfbcc6b68fd10ed35ff692124c6d | server/api/auth.py | server/api/auth.py | """All routes regarding authentication."""
from datetime import datetime
from sqlalchemy import or_
from webargs.flaskparser import use_args
from server import user_bp
from server.extensions import db
from server.models import User
from server.responses import bad_request, ok
from server.validation.user import login_... | """All routes regarding authentication."""
from datetime import datetime
from sqlalchemy import or_
from webargs.flaskparser import use_args
from server import user_bp
from server.extensions import db
from server.models import User
from server.responses import bad_request, ok
from server.validation.user import login_... | Send user id and token | Send user id and token
| Python | mit | Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival | <REPLACE_OLD> db.session.commit()
# <REPLACE_NEW> db.session.commit()
<REPLACE_END> <REPLACE_OLD> token,
# "pod_id": user.pod.id})
# <REPLACE_NEW> token,
<REPLACE_END> <DELETE> return ok(f'{user.id}:{token}')
<DELETE_END> <|endoftext|> """All routes regarding authentication."""
from datetime impo... | Send user id and token
"""All routes regarding authentication."""
from datetime import datetime
from sqlalchemy import or_
from webargs.flaskparser import use_args
from server import user_bp
from server.extensions import db
from server.models import User
from server.responses import bad_request, ok
from server.valid... |
c0808574aaf410683f9c405e98be74a3ad4f4f2c | tests/events_test.py | tests/events_test.py | from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
self.manager = EventM... | from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event, set)
class T... | Add unit tests on events. | Add unit tests on events.
| Python | apache-2.0 | optiflows/nyuki,optiflows/nyuki,gdraynz/nyuki,gdraynz/nyuki | <REPLACE_OLD> Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class <REPLACE_NEW> TestOnEvent(TestCase):
def test_001_call(self):
@on_event(Event.Connected, Event.Disconnected)
def test():
pass
self.assertIsInstance(test.on_event,... | Add unit tests on events.
from unittest import TestCase
from mock import Mock
from nyuki.events import EventManager, Event, on_event
class Loop(Mock):
STACK = list()
def async(self, cb, *args):
self.STACK.append(cb)
class TestEventManager(TestCase):
def setUp(self):
loop = Mock()
... |
8902c7612d84a2d14e90c4aac6db78ad95dd213c | trading_as/__init__.py | trading_as/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | # -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | Change order of imports to fix install into blank db or as dependency of company config. | Change order of imports to fix install into blank db or as dependency of
company config.
| Python | agpl-3.0 | OpusVL/odoo-trading-as | <REPLACE_OLD> res_company,
<REPLACE_NEW> res_partner,
<REPLACE_END> <REPLACE_OLD> res_partner,
)
# <REPLACE_NEW> res_company,
)
# <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<ht... | Change order of imports to fix install into blank db or as dependency of
company config.
# -*- coding: utf-8 -*-
##############################################################################
#
# Trading As Brands
# Copyright (C) 2015 OpusVL (<http://opusvl.com/>)
#
# This program is free software: you can redistribu... |
4636fc514b0ebf7b16e82cc3eb7de6b69431cd43 | site_analytics.py | site_analytics.py | #!/usr/local/bin/python3.6
# read nginx access log
# parse and get the ip addresses and times
# match ip addresses to geoip
# possibly ignore bots
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
r = re... | #!/usr/local/bin/python3.6
# read nginx access log
# parse and get the ip addresses and times
# match ip addresses to geoip
# possibly ignore bots
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
... | Fix tab spacing from 2 to 4 spaces | Fix tab spacing from 2 to 4 spaces
| Python | mit | mouhtasi/basic_site_analytics | <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END> <INSERT> <INSERT_END... | Fix tab spacing from 2 to 4 spaces
#!/usr/local/bin/python3.6
# read nginx access log
# parse and get the ip addresses and times
# match ip addresses to geoip
# possibly ignore bots
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = [... |
0e6646de573dc04360634828cdb3b7da8cc31d2b | cobe/instatrace.py | cobe/instatrace.py | # Copyright (C) 2010 Peter Teichman
import math
import time
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class Instatrace:
def __init__(self):
self._fd = No... | # Copyright (C) 2010 Peter Teichman
import math
import time
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class Instatrace:
def __init__(self):
self._fd = No... | Allow Instatrace().init(None) to disable tracing at runtime | Allow Instatrace().init(None) to disable tracing at runtime
| Python | mit | meska/cobe,pteichman/cobe,DarkMio/cobe,wodim/cobe-ng,LeMagnesium/cobe,tiagochiavericosta/cobe,wodim/cobe-ng,DarkMio/cobe,LeMagnesium/cobe,meska/cobe,tiagochiavericosta/cobe,pteichman/cobe | <INSERT> if filename is None:
self._fd = None
else:
<INSERT_END> <|endoftext|> # Copyright (C) 2010 Peter Teichman
import math
import time
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return in... | Allow Instatrace().init(None) to disable tracing at runtime
# Copyright (C) 2010 Peter Teichman
import math
import time
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
cl... |
79087444a858c33362c5a31200f158c6edda95df | humans/utils.py | humans/utils.py | from django.conf import settings
from django.utils import timezone
from datetime import datetime
def key_state(key):
results = settings.GPG_OBJ.import_keys(key).results
keys = settings.GPG_OBJ.list_keys()
if not results or not results[0]["fingerprint"]:
return None, "invalid"
else:
sta... | from django.conf import settings
from django.utils import timezone
from datetime import datetime
def key_state(key):
results = settings.GPG_OBJ.import_keys(key).results
keys = settings.GPG_OBJ.list_keys()
if not results or not results[0]["fingerprint"]:
return None, "invalid"
else:
sta... | Fix 'float is required' when key has no exp date | Fix 'float is required' when key has no exp date
No expiration date was defaulting to "", which was throwing an error
when creating the expire date timestamp.
| Python | mit | whitesmith/hawkpost,whitesmith/hawkpost,whitesmith/hawkpost | <REPLACE_OLD> ""
<REPLACE_NEW> 0
<REPLACE_END> <|endoftext|> from django.conf import settings
from django.utils import timezone
from datetime import datetime
def key_state(key):
results = settings.GPG_OBJ.import_keys(key).results
keys = settings.GPG_OBJ.list_keys()
if not results or not results[0]["fing... | Fix 'float is required' when key has no exp date
No expiration date was defaulting to "", which was throwing an error
when creating the expire date timestamp.
from django.conf import settings
from django.utils import timezone
from datetime import datetime
def key_state(key):
results = settings.GPG_OBJ.import_ke... |
8bc4471b95884f00d58d1067ad90c6a3220ce61e | katagawa/sql/operators.py | katagawa/sql/operators.py | """
Operators - stuff like `column = 'value'`, and similar.
"""
import abc
from katagawa.sql import Token
from katagawa.sql.dialects.common import Field
class Operator(Token):
"""
The base class for an operator.
An operator has three attributes - the field, the other value, and the actual operator itsel... | Add operator module, which contains the base class for an Operator token. | [sql] Add operator module, which contains the base class for an Operator token.
| Python | mit | SunDwarf/asyncqlio | <REPLACE_OLD> <REPLACE_NEW> """
Operators - stuff like `column = 'value'`, and similar.
"""
import abc
from katagawa.sql import Token
from katagawa.sql.dialects.common import Field
class Operator(Token):
"""
The base class for an operator.
An operator has three attributes - the field, the other value, ... | [sql] Add operator module, which contains the base class for an Operator token.
| |
c4e74be4b508c226b907b27b4a00b197289680e0 | django/applications/catmaid/control/ajax_templates.py | django/applications/catmaid/control/ajax_templates.py | from django.template.loader_tags import BlockNode, ExtendsNode
from django.template import loader, Context, RequestContext, TextNode
# Most parts of this code has been taken from this Django snippet:
# http://djangosnippets.org/snippets/942/
def get_template(template):
if isinstance(template, (tuple, list)):
... | Add helper methods to render template blocks independently | Add helper methods to render template blocks independently
| Python | agpl-3.0 | htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID | <REPLACE_OLD> <REPLACE_NEW> from django.template.loader_tags import BlockNode, ExtendsNode
from django.template import loader, Context, RequestContext, TextNode
# Most parts of this code has been taken from this Django snippet:
# http://djangosnippets.org/snippets/942/
def get_template(template):
if isinstance(t... | Add helper methods to render template blocks independently
| |
2774139f64f83e5b173a5acb67f986648b52dd6f | error-propagation/error-propagation.py | error-propagation/error-propagation.py | #!/usr/bin/env python3
import numpy
import random
random.seed(54864218)
def f(a, b):
coefficients = numpy.array([[2*a + b, a + b], [a - b, a - 2*b]])
inv_coefficients = numpy.linalg.inv(coefficients)
vars = numpy.array([2.5306, 10.1])
elements = numpy.matmul(inv_coefficients, vars)
return elem... | Add a basic error propagation example. | Add a basic error propagation example.
| Python | mpl-2.0 | DanielBrookRoberge/MonteCarloExamples | <INSERT> #!/usr/bin/env python3
import numpy
import random
random.seed(54864218)
def f(a, b):
<INSERT_END> <INSERT> coefficients = numpy.array([[2*a + b, a + b], [a - b, a - 2*b]])
inv_coefficients = numpy.linalg.inv(coefficients)
vars = numpy.array([2.5306, 10.1])
elements = numpy.matmul(inv_coeffi... | Add a basic error propagation example.
| |
e5f22a2e59a44535cde1a3a41ccae4eee440bbf2 | mica/report/tests/test_write_report.py | mica/report/tests/test_write_report.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
assert db.conn._is_connected == 1
HAS_SYBA... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
assert db.conn._is_connected == 1
HAS_SYBA... | Add one more test skip on mica.report | Add one more test skip on mica.report
| Python | bsd-3-clause | sot/mica,sot/mica | <REPLACE_OLD> False
@pytest.mark.skipif('not <REPLACE_NEW> False
HAS_SC_ARCHIVE = os.path.exists(report.starcheck.FILES['data_root'])
@pytest.mark.skipif('not <REPLACE_END> <REPLACE_OLD> access')
def <REPLACE_NEW> access')
@pytest.mark.skipif('not HAS_SC_ARCHIVE', reason='Report test requires mica starcheck archiv... | Add one more test skip on mica.report
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import tempfile
import os
import shutil
import pytest
from .. import report
try:
import Ska.DBI
with Ska.DBI.DBI(server='sqlsao', dbi='sybase', user='aca_ops', database='axafocat') as db:
assert db.c... |
26efd98c88a627f76ebd0865053353eb7a30e3bb | .glerbl/repo_conf.py | .glerbl/repo_conf.py | checks = {
'pre-commit': [
# BEFORE_COMMIT in the root of the working tree can be used as
# reminder to do something before the next commit.
"no_before_commit",
# We only allow ASCII filenames.
"no_non_ascii_filenames",
# We don't allow trailing whitespaces.
... | import sys
import os
dirname = os.path.dirname(__file__)
python_path = os.path.join(os.path.dirname(dirname), "selenium_test", "lib")
if "PYTHONPATH" not in os.environ:
os.environ["PYTHONPATH"] = python_path
else:
os.environ["PYTHONPATH"] = python_path + ":" + os.environ["PYTHONPATH"]
checks = {
'pre-com... | Modify PYTHONPATH so that pylint is able to find wedutil. | Modify PYTHONPATH so that pylint is able to find wedutil.
| Python | mpl-2.0 | mangalam-research/wed,slattery/wed,lddubeau/wed,slattery/wed,mangalam-research/wed,slattery/wed,mangalam-research/wed,lddubeau/wed,mangalam-research/wed,lddubeau/wed,lddubeau/wed | <REPLACE_OLD> checks <REPLACE_NEW> import sys
import os
dirname = os.path.dirname(__file__)
python_path = os.path.join(os.path.dirname(dirname), "selenium_test", "lib")
if "PYTHONPATH" not in os.environ:
os.environ["PYTHONPATH"] = python_path
else:
os.environ["PYTHONPATH"] = python_path + ":" + os.environ["PY... | Modify PYTHONPATH so that pylint is able to find wedutil.
checks = {
'pre-commit': [
# BEFORE_COMMIT in the root of the working tree can be used as
# reminder to do something before the next commit.
"no_before_commit",
# We only allow ASCII filenames.
"no_non_ascii_filename... |
25fb55ed7d90834d36f0f536f4324facbb5db710 | examples/play_tvz.py | examples/play_tvz.py | import sc2
from sc2 import Race
from sc2.player import Human, Bot
from zerg_rush import ZergRushBot
def main():
sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
Human(Race.Terran),
Bot(Race.Zerg, ZergRushBot())
], realtime=True)
if __name__ == '__main__':
main()
| Add TvZ Human vs AI example | Add TvZ Human vs AI example
| Python | mit | Dentosal/python-sc2 | <INSERT> import sc2
from sc2 import Race
from sc2.player import Human, Bot
from zerg_rush import ZergRushBot
def main():
<INSERT_END> <INSERT> sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
Human(Race.Terran),
Bot(Race.Zerg, ZergRushBot())
], realtime=True)
if __name__ == '__main__':
main... | Add TvZ Human vs AI example
| |
5ecaed42c8f4389a6d12851d41c22dad22e2a2d8 | storm/src/py/resources/morelikethis.py | storm/src/py/resources/morelikethis.py | # -*- coding: utf-8 -*-
"""
zeit.recommend.morelikethis
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module has no description.
Copyright: (c) 2013 by Nicolas Drebenstedt.
License: BSD, see LICENSE for more details.
"""
from elasticsearch import Elasticsearch
from storm import Bolt
from storm import log
fro... | Add barebone content-based, Solr-powered recommender | Add barebone content-based, Solr-powered recommender
| Python | bsd-2-clause | cutoffthetop/recommender,cutoffthetop/recommender,cutoffthetop/recommender | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
"""
zeit.recommend.morelikethis
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module has no description.
Copyright: (c) 2013 by Nicolas Drebenstedt.
License: BSD, see LICENSE for more details.
"""
from elasticsearch import Elasticsearch
from storm import B... | Add barebone content-based, Solr-powered recommender
| |
63a26cbf76a3d0135f5b67dd10cc7f383ffa7ebf | helusers/jwt.py | helusers/jwt.py | from django.conf import settings
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = ap... | from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication sett... | Change authenticate_credentials method to raise an exception if the account is disabled | Change authenticate_credentials method to raise an exception if the account is disabled
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers | <INSERT> rest_framework import exceptions
from <INSERT_END> <INSERT> user = super().authenticate_credentials(payload)
if user and not user.is_active:
msg = _('User account is disabled.')
raise exceptions.AuthenticationFailed(msg)
<INSERT_END> <|endoftext|> from django.conf impo... | Change authenticate_credentials method to raise an exception if the account is disabled
from django.conf import settings
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
... |
89b9fb1cb14aeb99cb7c96717830898aead4fef1 | src/waldur_core/core/management/commands/createstaffuser.py | src/waldur_core/core/management/commands/createstaffuser.py | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
... | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help = "Create a user with a specified username and password. User will be created as staff."
def add_arguments(self, parser):
... | Allow setting email when creating a staff account. | Allow setting email when creating a staff account.
Otherwise makes it hard to start using HomePort as it requires email validation.
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind | <INSERT> required=True)
parser.add_argument('-e', '--email', dest='email', <INSERT_END> <REPLACE_OLD> options['password']
<REPLACE_NEW> options['password']
email = options['email']
<REPLACE_END> <REPLACE_OLD> username=username, <REPLACE_NEW> username=username,
email=email,
<R... | Allow setting email when creating a staff account.
Otherwise makes it hard to start using HomePort as it requires email validation.
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
class Command(BaseCommand):
help ... |
f3a327d8fc5f43ad82f0696cef4a14e6dd2533ea | ognskylines/commands/gateway.py | ognskylines/commands/gateway.py | import logging
from ognskylines.gateway import ognSkylinesGateway
from ognskylines.dbutils import session
from manager import Manager
gateway_manager = Manager()
@gateway_manager.command
def run(logfile=''):
"""Run the ogn-->skylines gateway."""
# Enable logging
log_handlers = [logging.StreamHandler()]
... | import logging
from ognskylines.gateway import ognSkylinesGateway
from ognskylines.dbutils import session
from manager import Manager
gateway_manager = Manager()
@gateway_manager.command
def run(skylines_host='127.0.0.1', skylines_port=5597, logfile=''):
"""Run the ogn-->skylines gateway."""
# Enable loggin... | Add arguments skylines-host and -port | manage.py: Add arguments skylines-host and -port
| Python | agpl-3.0 | kerel-fs/ogn-skylines-gateway,kerel-fs/ogn-skylines-gateway | <REPLACE_OLD> run(logfile=''):
<REPLACE_NEW> run(skylines_host='127.0.0.1', skylines_port=5597, logfile=''):
<REPLACE_END> <REPLACE_OLD> host='127.0.0.1', port=5597)
<REPLACE_NEW> host=skylines_host, port=skylines_port)
<REPLACE_END> <|endoftext|> import logging
from ognskylines.gateway import ognSkylinesGateway
... | manage.py: Add arguments skylines-host and -port
import logging
from ognskylines.gateway import ognSkylinesGateway
from ognskylines.dbutils import session
from manager import Manager
gateway_manager = Manager()
@gateway_manager.command
def run(logfile=''):
"""Run the ogn-->skylines gateway."""
# Enable log... |
7dd683be3df9d8e6ad9c67baa19dbaf5663bdd64 | pwnableapp/__init__.py | pwnableapp/__init__.py | import logging
import flask
import sys
class Flask(flask.Flask):
def __init__(self, *args, **kwargs):
super(Flask, self).__init__(*args, **kwargs)
# Set error handlers
self.register_error_handler(500, self.internal_error_handler)
for error in (400, 403, 404):
self.register_error_handler(error,... | import logging
import flask
import os
import sys
class Flask(flask.Flask):
def __init__(self, *args, **kwargs):
super(Flask, self).__init__(*args, **kwargs)
# Set error handlers
self.register_error_handler(500, self.internal_error_handler)
for error in (400, 403, 404):
self.register_error_hand... | Set umask before starting logging. | Set umask before starting logging.
| Python | apache-2.0 | Matir/pwnableweb,Matir/pwnableweb,Matir/pwnableweb,Matir/pwnableweb | <INSERT> os
import <INSERT_END> <INSERT> old_umask = os.umask(0077)
<INSERT_END> <REPLACE_OLD> self.logger.addHandler(handler)
<REPLACE_NEW> self.logger.addHandler(handler)
self.logger.info('Logging started.')
os.umask(old_umask)
<REPLACE_END> <|endoftext|> import logging
import flask
import os
im... | Set umask before starting logging.
import logging
import flask
import sys
class Flask(flask.Flask):
def __init__(self, *args, **kwargs):
super(Flask, self).__init__(*args, **kwargs)
# Set error handlers
self.register_error_handler(500, self.internal_error_handler)
for error in (400, 403, 404):
... |
b66b02be95e7b0c36a9ced53b07d91298190ca4a | test/test_dl.py | test/test_dl.py | from mpi4py import dl
import mpiunittest as unittest
import sys
import os
class TestDL(unittest.TestCase):
def testDL1(self):
if sys.platform == 'darwin':
libm = 'libm.dylib'
else:
libm = 'libm.so'
handle = dl.dlopen(libm, dl.RTLD_LOCAL|dl.RTLD_LAZY)
self.a... | Add tests for mpi4py.dl module | test: Add tests for mpi4py.dl module
| Python | bsd-2-clause | mpi4py/mpi4py,mpi4py/mpi4py,pressel/mpi4py,pressel/mpi4py,mpi4py/mpi4py,pressel/mpi4py,pressel/mpi4py | <REPLACE_OLD> <REPLACE_NEW> from mpi4py import dl
import mpiunittest as unittest
import sys
import os
class TestDL(unittest.TestCase):
def testDL1(self):
if sys.platform == 'darwin':
libm = 'libm.dylib'
else:
libm = 'libm.so'
handle = dl.dlopen(libm, dl.RTLD_LOCAL... | test: Add tests for mpi4py.dl module
| |
6e2362351d9ccaa46a5a2bc69c4360e4faff166d | iclib/qibla.py | iclib/qibla.py | from . import formula
def direction(lat, lng):
return formula.qibla(lat, lng)
def direction_dms(lat, lng):
return _dms(formula.qibla(lat, lng))
def direction_str(lat, lng, prec=0):
d, m, s = direction_dms(lat, lng)
# negative input might returns wrong result
return '{}° {}\' {:.{}f}"'.format(d, m, s, prec)
def... | # -*- coding: utf-8 -*-
from . import formula
def direction(lat, lng):
return formula.qibla(lat, lng)
def direction_dms(lat, lng):
return _dms(formula.qibla(lat, lng))
def direction_str(lat, lng, prec=0):
d, m, s = direction_dms(lat, lng)
# negative input might returns wrong result
return '{}° {}\' {:.{}f}"'.fo... | Add encoding spec to comply Python 2 | Add encoding spec to comply Python 2
| Python | apache-2.0 | fikr4n/iclib-python | <REPLACE_OLD> from <REPLACE_NEW> # -*- coding: utf-8 -*-
from <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
from . import formula
def direction(lat, lng):
return formula.qibla(lat, lng)
def direction_dms(lat, lng):
return _dms(formula.qibla(lat, lng))
def direction_str(lat, lng, prec=0):
d, m, s = direction... | Add encoding spec to comply Python 2
from . import formula
def direction(lat, lng):
return formula.qibla(lat, lng)
def direction_dms(lat, lng):
return _dms(formula.qibla(lat, lng))
def direction_str(lat, lng, prec=0):
d, m, s = direction_dms(lat, lng)
# negative input might returns wrong result
return '{}° {}\... |
c8b9c302421f0f49f00db381954e7fc7cc657f52 | application/__init__.py | application/__init__.py | import os
import logging
from flask import Flask
from flask.ext.basicauth import BasicAuth
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
db = SQLAlchemy(app)
# auth
if os.environ.get('BASIC_AUTH_USERNAME'):
app.config['BASIC_AUTH_FORCE'] = ... | import os
import logging
from flask import Flask
from flask.ext.basicauth import BasicAuth
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
db = SQLAlchemy(app)
# a... | Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry/historian-alpha,LandRegistry/historian-alpha,LandRegistry/historian-alpha | <REPLACE_OLD> Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
db <REPLACE_NEW> Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app <REPLACE_END> <REPLACE_OLD> SQLAlchemy(app)
# <REPLACE_NEW> ProxyFix(app.wsgi_app)
db = SQ... | Add proxy fix as in lr this will run with reverse proxy
import os
import logging
from flask import Flask
from flask.ext.basicauth import BasicAuth
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
db = SQLAlchemy(app)
# auth
if os.environ.get('BAS... |
ccf6626d86dd00b3f9848e19b3cb1139dba17e56 | tests/integration-test/test_junctions_create.py | tests/integration-test/test_junctions_create.py | #!/usr/bin/env python
from integrationtest import IntegrationTest, main
import unittest
class TestCreate(IntegrationTest, unittest.TestCase):
def test_junctions_create(self):
bam1 = self.inputFiles("test_hcc1395.bam")[0]
output_file = self.tempFile("create.out")
print "BAM1 is ", bam1
... | #!/usr/bin/env python
from integrationtest import IntegrationTest, main
import unittest
class TestCreate(IntegrationTest, unittest.TestCase):
def test_junctions_create(self):
bam1 = self.inputFiles("test_hcc1395.bam")[0]
output_file = self.tempFile("create.out")
print "BAM1 is ", bam1
... | Move positional argument to the end. | Move positional argument to the end.
This doesn't seem to work on a Mac when option comes after the positional
argument, not sure why this is, something to do with options parsing.
| Python | mit | tabbott/regtools,griffithlab/regtools,tabbott/regtools,tabbott/regtools,griffithlab/regtools,gatoravi/regtools,griffithlab/regtools,griffithlab/regtools,griffithlab/regtools,gatoravi/regtools,gatoravi/regtools,gatoravi/regtools,gatoravi/regtools,griffithlab/regtools,tabbott/regtools,tabbott/regtools | <DELETE> bam1, <DELETE_END> <REPLACE_OLD> output_file]
<REPLACE_NEW> output_file, bam1 ]
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
from integrationtest import IntegrationTest, main
import unittest
class TestCreate(IntegrationTest, unittest.TestCase):
def test_junctions_create(self):
bam1 = self.... | Move positional argument to the end.
This doesn't seem to work on a Mac when option comes after the positional
argument, not sure why this is, something to do with options parsing.
#!/usr/bin/env python
from integrationtest import IntegrationTest, main
import unittest
class TestCreate(IntegrationTest, unittest.Test... |
1005a41bd6fb3f854f75bd9d4d6ab69290778ba9 | kolibri/core/lessons/viewsets.py | kolibri/core/lessons/viewsets.py | from rest_framework.viewsets import ModelViewSet
from .serializers import LessonSerializer
from kolibri.core.lessons.models import Lesson
class LessonViewset(ModelViewSet):
serializer_class = LessonSerializer
def get_queryset(self):
return Lesson.objects.filter(is_archived=False)
| from rest_framework.viewsets import ModelViewSet
from .serializers import LessonSerializer
from kolibri.core.lessons.models import Lesson
class LessonViewset(ModelViewSet):
serializer_class = LessonSerializer
def get_queryset(self):
queryset = Lesson.objects.filter(is_archived=False)
classid ... | Add classid filter for Lessons | Add classid filter for Lessons
| Python | mit | learningequality/kolibri,mrpau/kolibri,mrpau/kolibri,lyw07/kolibri,christianmemije/kolibri,christianmemije/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,jonboiser/kolibri,benjaoming/kolibri,lyw07/kolibri,jonboiser/kolibri,learningequality/kolibri,christianmemije/kolibri,jonboiser/kolibri,DXCanas/kolibri,mrpau/kol... | <INSERT> queryset = Lesson.objects.filter(is_archived=False)
classid = self.request.query_params.get('classid', None)
if classid is not None:
queryset = queryset.filter(collection_id=classid)
<INSERT_END> <REPLACE_OLD> Lesson.objects.filter(is_archived=False)
<REPLACE_NEW> querys... | Add classid filter for Lessons
from rest_framework.viewsets import ModelViewSet
from .serializers import LessonSerializer
from kolibri.core.lessons.models import Lesson
class LessonViewset(ModelViewSet):
serializer_class = LessonSerializer
def get_queryset(self):
return Lesson.objects.filter(is_archi... |
b87c9002aeabde283f2cf5e37de311fb3469af2b | lib/ansible/modules/cloud/openstack/os_client_config.py | lib/ansible/modules/cloud/openstack/os_client_config.py | #!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... | Add OpenStack Client Config module | Add OpenStack Client Config module
All of the ansible OpenStack modules are driven by a clouds.yaml config
file which is processed by os-client-config. Expose the data returned by
that library to enable playbooks to iterate over available clouds.
| Python | mit | thaim/ansible,thaim/ansible | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/python
# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, o... | Add OpenStack Client Config module
All of the ansible OpenStack modules are driven by a clouds.yaml config
file which is processed by os-client-config. Expose the data returned by
that library to enable playbooks to iterate over available clouds.
| |
fe3559103917f6e9b61d0f6515502e3e530896cf | inidiff/cli.py | inidiff/cli.py | from __future__ import print_function
from . import diff
import argparse
RED = '\033[1;31m'
GREEN = '\033[1;32m'
END = '\033[0m'
def format_option(opt):
"""Return a formatted option in the form name=value."""
return '{}={}\n'.format(opt.option, opt.value)
def format_output(first, second, color=True):
... | from __future__ import print_function
import argparse
import sys
from . import diff
RED = '\033[1;31m'
GREEN = '\033[1;32m'
END = '\033[0m'
def format_option(opt):
"""Return a formatted option in the form name=value."""
return '{}={}\n'.format(opt.option, opt.value)
def format_output(first, second, colo... | Exit with 1 if there's a difference | Exit with 1 if there's a difference
| Python | mit | kragniz/inidiff | <REPLACE_OLD> print_function
from <REPLACE_NEW> print_function
import argparse
import sys
from <REPLACE_END> <REPLACE_OLD> diff
import argparse
RED <REPLACE_NEW> diff
RED <REPLACE_END> <REPLACE_OLD> print(format_output(first, second), end='')
<REPLACE_NEW> out = format_output(first, second)
print(out, end=... | Exit with 1 if there's a difference
from __future__ import print_function
from . import diff
import argparse
RED = '\033[1;31m'
GREEN = '\033[1;32m'
END = '\033[0m'
def format_option(opt):
"""Return a formatted option in the form name=value."""
return '{}={}\n'.format(opt.option, opt.value)
def format_... |
a3ac011c35fa8918a4828a2c6eb119d5ca18a857 | src/example/bench_wsh.py | src/example/bench_wsh.py | # Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | Add a handler for performing client load testing. | Add a handler for performing client load testing.
Review URL: http://codereview.appspot.com/3844044 | Python | bsd-3-clause | google/pywebsocket,googlearchive/pywebsocket,GoogleChromeLabs/pywebsocket3,google/pywebsocket,googlearchive/pywebsocket,GoogleChromeLabs/pywebsocket3,google/pywebsocket,GoogleChromeLabs/pywebsocket3,googlearchive/pywebsocket | <REPLACE_OLD> <REPLACE_NEW> # Copyright 2011, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this... | Add a handler for performing client load testing.
Review URL: http://codereview.appspot.com/3844044
| |
7718608741b7126e9239af71d8b2e140dce81303 | common/djangoapps/microsite_configuration/templatetags/microsite.py | common/djangoapps/microsite_configuration/templatetags/microsite.py | """
Template tags and helper functions for displaying breadcrumbs in page titles
based on the current micro site.
"""
from django import template
from django.conf import settings
from microsite_configuration.middleware import MicrositeConfiguration
register = template.Library()
def page_title_breadcrumbs(*crumbs, **... | """
Template tags and helper functions for displaying breadcrumbs in page titles
based on the current micro site.
"""
from django import template
from django.conf import settings
from microsite_configuration.middleware import MicrositeConfiguration
register = template.Library()
def page_title_breadcrumbs(*crumbs, **... | Fix unicode error in subsection | Fix unicode error in subsection
| Python | agpl-3.0 | kxliugang/edx-platform,ZLLab-Mooc/edx-platform,rhndg/openedx,beni55/edx-platform,chudaol/edx-platform,beni55/edx-platform,openfun/edx-platform,atsolakid/edx-platform,romain-li/edx-platform,jonathan-beard/edx-platform,torchingloom/edx-platform,deepsrijit1105/edx-platform,stvstnfrd/edx-platform,ubc/edx-platform,nttks/jen... | <REPLACE_OLD> '{}{}{}'.format(separator.join(crumbs), <REPLACE_NEW> u'{}{}{}'.format(separator.join(crumbs), <REPLACE_END> <REPLACE_OLD> settings.PLATFORM_NAME) <REPLACE_NEW> settings.PLATFORM_NAME)
<REPLACE_END> <|endoftext|> """
Template tags and helper functions for displaying breadcrumbs in page titles
based on th... | Fix unicode error in subsection
"""
Template tags and helper functions for displaying breadcrumbs in page titles
based on the current micro site.
"""
from django import template
from django.conf import settings
from microsite_configuration.middleware import MicrositeConfiguration
register = template.Library()
def p... |
b2adc19e5f28c16bc7cfcd38ed35043d7b1fbe29 | profile_collection/startup/15-machines.py | profile_collection/startup/15-machines.py | from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO
from ophyd import Component as Cpt
# Undulator
class Undulator(PVPositionerPC):
readback = Cpt(EpicsSignalRO, '-LEnc}Gap')
setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos')
actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go')
actuate_value = 1
stop_si... | from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO
from ophyd import Component as Cpt
# Undulator
class Undulator(PVPositionerPC):
readback = Cpt(EpicsSignalRO, '-LEnc}Gap')
setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos')
actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go')
actuate_value = 1
stop_si... | ADD readback.name in iuv_gap to fix speck save prob | ADD readback.name in iuv_gap to fix speck save prob
| Python | bsd-2-clause | NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd | <REPLACE_OLD> name='ivu_gap')
ivu_gap.readback <REPLACE_NEW> name='ivu_gap')
# ivu_gap.readback <REPLACE_END> <REPLACE_OLD> 'ivu_gap'
# <REPLACE_NEW> 'ivu_gap' ####what the ^*(*()**)(* !!!!
#To solve the "KeyError Problem" when doing dscan and trying to save to a spec file, Y.G., 20170110
ivu_gap.readback.name = 'iv... | ADD readback.name in iuv_gap to fix speck save prob
from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO
from ophyd import Component as Cpt
# Undulator
class Undulator(PVPositionerPC):
readback = Cpt(EpicsSignalRO, '-LEnc}Gap')
setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos')
actuate = Cpt(EpicsSign... |
5a5a83abb5265dd0abc3c6306f65930c4ce012f2 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="globus-cli",
version="0.1.0",
packages=find_packages(),
install_requires=['globus-sdk-python'],
# for now, install directly from GitHub
# TODO: once this is on pypi, install from there
dependency_links=[
('https://github.com/g... | from setuptools import setup, find_packages
setup(
name="globus-cli",
version="0.1.0",
packages=find_packages(),
install_requires=['globus-sdk'],
# for now, install directly from GitHub
# TODO: once this is on pypi, install from there
dependency_links=[
('https://github.com/globuson... | Fix globus-sdk python package name | Fix globus-sdk python package name
To match recent change in SDK repo
| Python | apache-2.0 | globus/globus-cli,globus/globus-cli | <REPLACE_OLD> install_requires=['globus-sdk-python'],
<REPLACE_NEW> install_requires=['globus-sdk'],
<REPLACE_END> <REPLACE_OLD> 'archive/master.zip#egg=globus-sdk-python-0.1')
<REPLACE_NEW> 'archive/master.zip#egg=globus-sdk-0.1')
<REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
setup(
... | Fix globus-sdk python package name
To match recent change in SDK repo
from setuptools import setup, find_packages
setup(
name="globus-cli",
version="0.1.0",
packages=find_packages(),
install_requires=['globus-sdk-python'],
# for now, install directly from GitHub
# TODO: once this is on pypi, ... |
24dba96be4a9202fdac5fa779c52789ec6cd13c4 | api/common/views.py | api/common/views.py | import subprocess
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def dep... | import subprocess
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken.models import Token
@csrf_exempt
def dep... | Improve subprocess call during deployment | Improve subprocess call during deployment
| Python | apache-2.0 | prattl/teamfinder,prattl/teamfinder,prattl/teamfinder,prattl/teamfinder | <REPLACE_OLD> subprocess.Popen(['scripts/deploy.sh', commit], stdout=subprocess.PIPE)
<REPLACE_NEW> subprocess.run(['scripts/deploy.sh', commit],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
<REPLACE_END> <|endoftext|> import subprocess
from django.conf import settings
from django.co... | Improve subprocess call during deployment
import subprocess
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from rest_framework.authtoken... |
9ff346834a39605a707d66d4a2c6e3dc20dcdd78 | markov_chain.py | markov_chain.py | from random import choice
class MarkovChain(object):
""" An interface for signle-word states Markov Chains """
def __init__(self, text=None):
self._states_map = {}
if text is not None:
self.add_text(text)
def add_text(self, text, separator=" "):
""" Adds text ... | from random import choice
class MarkovChain(object):
""" An interface for signle-word states Markov Chains """
def __init__(self, text=None):
self._states_map = {}
if text is not None:
self.add_text(text)
def add_text(self, text, separator=" "):
""" Adds text to the ma... | Add Markov Chain representation class | Add Markov Chain representation class
| Python | mit | iluxonchik/lyricist | <DELETE>
<DELETE_END> <INSERT> def add_text_collection(self, text_col, separator=" "):
""" Adds a collection of text strings to the markov chain """
for line in text_col:
if line not in ["", "\n", None]:
self.add_text(line, separator)
<INSERT_END> <|endoftext|>... | Add Markov Chain representation class
from random import choice
class MarkovChain(object):
""" An interface for signle-word states Markov Chains """
def __init__(self, text=None):
self._states_map = {}
if text is not None:
self.add_text(text)
def add_text(self, text,... |
0983361e6fba5812416d8fb5b695f6b3034bc927 | registration/management/commands/cleanupregistration.py | registration/management/commands/cleanupregistration.py | """
A management command which deletes expired accounts (e.g.,
accounts which signed up but never activated) from the database.
Calls ``RegistrationProfile.objects.delete_expired_users()``, which
contains the actual logic for determining which accounts are deleted.
"""
from django.core.management.base import NoArgsC... | """
A management command which deletes expired accounts (e.g.,
accounts which signed up but never activated) from the database.
Calls ``RegistrationProfile.objects.delete_expired_users()``, which
contains the actual logic for determining which accounts are deleted.
"""
from django.core.management.base import BaseCom... | Fix deprecated class NoArgsCommand class. | Fix deprecated class NoArgsCommand class.
Solve the warning RemovedInDjango110Warning: NoArgsCommand class is deprecated and will be removed in Django 1.10. Use BaseCommand instead, which takes no arguments by default.
| Python | bsd-3-clause | sergafts/django-registration,timgraham/django-registration,sergafts/django-registration,pando85/django-registration,pando85/django-registration,allo-/django-registration,allo-/django-registration,timgraham/django-registration | <REPLACE_OLD> NoArgsCommand
from <REPLACE_NEW> BaseCommand
from <REPLACE_END> <REPLACE_OLD> Command(NoArgsCommand):
<REPLACE_NEW> Command(BaseCommand):
<REPLACE_END> <REPLACE_OLD> handle_noargs(self, <REPLACE_NEW> handle(self, *args, <REPLACE_END> <|endoftext|> """
A management command which deletes expired account... | Fix deprecated class NoArgsCommand class.
Solve the warning RemovedInDjango110Warning: NoArgsCommand class is deprecated and will be removed in Django 1.10. Use BaseCommand instead, which takes no arguments by default.
"""
A management command which deletes expired accounts (e.g.,
accounts which signed up but never a... |
ea62a1cd9642dbff69cbfae3f8b540604a8a8fca | mine/__init__.py | mine/__init__.py | #!/usr/bin/env python
"""Package for mine."""
import sys
__project__ = 'mine'
__version__ = '0.1'
CLI = 'mine'
VERSION = __project__ + '-' + __version__
DESCRIPTION = "Manages running applications across multiple computers."
PYTHON_VERSION = 3, 3
if not sys.version_info >= PYTHON_VERSION: # pragma: no cover (man... | #!/usr/bin/env python
"""Package for mine."""
import sys
__project__ = 'mine'
__version__ = '0.1'
CLI = 'mine'
VERSION = __project__ + '-' + __version__
DESCRIPTION = "For applications that haven't learned to share."
PYTHON_VERSION = 3, 3
if not sys.version_info >= PYTHON_VERSION: # pragma: no cover (manual test... | Update headline to match GitHub | Update headline to match GitHub
| Python | mit | jacebrowning/mine | <REPLACE_OLD> "Manages running <REPLACE_NEW> "For <REPLACE_END> <REPLACE_OLD> across multiple computers."
PYTHON_VERSION <REPLACE_NEW> that haven't learned to share."
PYTHON_VERSION <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""Package for mine."""
import sys
__project__ = 'mine'
__version__ = '0.1'
CLI = ... | Update headline to match GitHub
#!/usr/bin/env python
"""Package for mine."""
import sys
__project__ = 'mine'
__version__ = '0.1'
CLI = 'mine'
VERSION = __project__ + '-' + __version__
DESCRIPTION = "Manages running applications across multiple computers."
PYTHON_VERSION = 3, 3
if not sys.version_info >= PYTHON_... |
54c46aaafe5b99b4da01911b4133dfaace7f6a43 | _priorityQ.py | _priorityQ.py | import bin_heap as bh
class Priority(object):
"""docstring for priority"""
def __init__(self):
self.bin_heap = bh
def insert(self, item, rank):
bh.push(item, rank)
def pop(self):
item = self.bin_heap.pop()
return item
def peek(self, item):
return item
| import bin_heap as bh
class Priority(object):
"""docstring for priority"""
def __init__(self):
self.bin_heap = bh()
def insert(self, item, rank):
bh.push(item, rank)
def pop(self):
item = self.bin_heap.pop()
return item
def peek(self, item):
return item
| Fix typo; bin_heap will now properly instate | Fix typo; bin_heap will now properly instate
| Python | mit | jwarren116/data-structures | <REPLACE_OLD> bh
<REPLACE_NEW> bh()
<REPLACE_END> <|endoftext|> import bin_heap as bh
class Priority(object):
"""docstring for priority"""
def __init__(self):
self.bin_heap = bh()
def insert(self, item, rank):
bh.push(item, rank)
def pop(self):
item = self.bin_heap.pop()
... | Fix typo; bin_heap will now properly instate
import bin_heap as bh
class Priority(object):
"""docstring for priority"""
def __init__(self):
self.bin_heap = bh
def insert(self, item, rank):
bh.push(item, rank)
def pop(self):
item = self.bin_heap.pop()
return item
... |
eda91552ae26188afbad74115495e44e07827c4d | typ/version.py | typ/version.py | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | Add a -vvv mode to log when tests are queued for running. | Add a -vvv mode to log when tests are queued for running.
If one is running a bunch of tests in parallel and something
is not working right, it can be useful to see which tests are
currently executing at the same time. There isn't a great way
to do this in typ, because we don't know when tests are actually
picked up f... | Python | apache-2.0 | dpranke/typ | <REPLACE_OLD> '0.9.4'
<REPLACE_NEW> '0.9.4pre'
<REPLACE_END> <|endoftext|> # Copyright 2014 Google 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://ww... | Add a -vvv mode to log when tests are queued for running.
If one is running a bunch of tests in parallel and something
is not working right, it can be useful to see which tests are
currently executing at the same time. There isn't a great way
to do this in typ, because we don't know when tests are actually
picked up f... |
c935f85d62d0375d07685eeff14859e5a5a9b161 | tests/test_spotifile.py | tests/test_spotifile.py | import unittest
import os
from subprocess import check_call
from sh import ls
mountpoint = '/tmp/spotifile_test_mount'
class SpotifileTestClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not os.path.exists(mountpoint):
os.mkdir(mountpoint)
@classmethod
def tearDownClass(cls):
if os.path.exis... | Add simple test to check that we populate the root as expected | tests: Add simple test to check that we populate the root as expected
Signed-off-by: Anton Lofgren <64e2cb85477d4abaea4b354af986fde12a3e64f3@op5.com>
| Python | bsd-3-clause | catharsis/spotifile,raoulh/spotifile,chelmertz/spotifile,raoulh/spotifile,raoulh/spotifile,chelmertz/spotifile,chelmertz/spotifile,catharsis/spotifile,catharsis/spotifile | <REPLACE_OLD> <REPLACE_NEW> import unittest
import os
from subprocess import check_call
from sh import ls
mountpoint = '/tmp/spotifile_test_mount'
class SpotifileTestClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not os.path.exists(mountpoint):
os.mkdir(mountpoint)
@classmethod
def tearDown... | tests: Add simple test to check that we populate the root as expected
Signed-off-by: Anton Lofgren <64e2cb85477d4abaea4b354af986fde12a3e64f3@op5.com>
| |
f9c9cd4505e9055a2905a87f91cdaab399352b27 | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.15.2"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.16.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.16.0 | Increment version number to 0.16.0
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | <REPLACE_OLD> "0.15.2"
__version_info__ <REPLACE_NEW> "0.16.0"
__version_info__ <REPLACE_END> <|endoftext|> """Configuration for Django system."""
__version__ = "0.16.0"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.16.0
"""Configuration for Django system."""
__version__ = "0.15.2"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
|
660aecd99935ef3073d8ff166c5bd131b2d95b22 | tests/unit/test_inotify.py | tests/unit/test_inotify.py | #!/usr/bin/env python
import pytest
from butter.inotify import watch
from subprocess import Popen
from tempfile import TemporaryDirectory
from time import sleep
import os
def test_watch():
FILENAME = 'inotify_test'
with TemporaryDirectory() as tmp_dir:
filename = os.path.join(tmp_dir, FILENAME)
... | Add tests for watch function | Add tests for watch function
| Python | bsd-3-clause | wdv4758h/butter,dasSOZO/python-butter | <INSERT> #!/usr/bin/env python
import pytest
from butter.inotify import watch
from subprocess import Popen
from tempfile import TemporaryDirectory
from time import sleep
import os
def test_watch():
<INSERT_END> <INSERT> FILENAME = 'inotify_test'
with TemporaryDirectory() as tmp_dir:
filename = os.path... | Add tests for watch function
| |
c107f80ba57847b8d195a9abeffd3d14d3048fe6 | numscons/__init__.py | numscons/__init__.py | # XXX those are needed by the scons command only...
from core.misc import get_scons_path, get_scons_build_dir, \
get_scons_configres_dir, get_scons_configres_filename
# XXX those should not be needed by the scons command only...
from core.extension import get_python_inc, get_pythonlib_dir
# Thos... | # XXX those are needed by the scons command only...
from core.misc import get_scons_path, get_scons_build_dir, \
get_scons_configres_dir, get_scons_configres_filename
from core.libinfo import get_paths as scons_get_paths
# XXX those should not be needed by the scons command only...
from core.exte... | Add more missing functions in numscons namespace | Add more missing functions in numscons namespace | Python | bsd-3-clause | cournape/numscons,cournape/numscons,cournape/numscons | <REPLACE_OLD> get_scons_configres_filename
# <REPLACE_NEW> get_scons_configres_filename
from core.libinfo import get_paths as scons_get_paths
# <REPLACE_END> <REPLACE_OLD> tools
<REPLACE_NEW> tools
# XXX: this is ugly, better find the mathlibs with a checker
# XXX: this had nothing to do here, too...
def scons_get... | Add more missing functions in numscons namespace
# XXX those are needed by the scons command only...
from core.misc import get_scons_path, get_scons_build_dir, \
get_scons_configres_dir, get_scons_configres_filename
# XXX those should not be needed by the scons command only...
from core.extension... |
15490a05696e5e37aa98af905669967fe406eb1d | runtests.py | runtests.py | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
... | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'django.contrib.sites', # for sitemap test
),
R... | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2. | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
| Python | mit | simonluijk/django-localeurl,jmagnusson/django-localeurl | <INSERT> 'django.contrib.sites', # for sitemap test
<INSERT_END> <|endoftext|> #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'... | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
#!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl'... |
c297b882cbe5139062672dbb295c2b42adfc1ed8 | setup.py | setup.py | from setuptools import setup
setup(
name='bwapi',
version='3.2.0',
description='A software development kit for the Brandwatch API',
url='https://github.com/BrandwatchLtd/api_sdk',
author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden',
author_email='amyb@brandwatch.com, paul@br... | from setuptools import setup
setup(
name='bwapi',
version='3.2.0',
description='A software development kit for the Brandwatch API',
url='https://github.com/BrandwatchLtd/api_sdk',
author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden',
author_email='amyb@brandwatch.com, paul@br... | Add authenticate.py to installed scripts | Add authenticate.py to installed scripts
| Python | mit | anthonybu/api_sdk,BrandwatchLtd/api_sdk | <INSERT> scripts=['authenticate.py'],
<INSERT_END> <|endoftext|> from setuptools import setup
setup(
name='bwapi',
version='3.2.0',
description='A software development kit for the Brandwatch API',
url='https://github.com/BrandwatchLtd/api_sdk',
author='Amy Barker, Jamie Lebovics, Paul Sieg... | Add authenticate.py to installed scripts
from setuptools import setup
setup(
name='bwapi',
version='3.2.0',
description='A software development kit for the Brandwatch API',
url='https://github.com/BrandwatchLtd/api_sdk',
author='Amy Barker, Jamie Lebovics, Paul Siegel and Jessica Bowden',
... |
3fd4244dbfd33bbf2fa369d81756e82b1cf1c467 | src/mmw/apps/modeling/migrations/0041_clear_nlcd2019_gwlfe_results.py | src/mmw/apps/modeling/migrations/0041_clear_nlcd2019_gwlfe_results.py | # Generated by Django 3.2.13 on 2022-10-17 13:47
from django.db import migrations
def clear_nlcd2019_gwlfe_results(apps, schema_editor):
"""
Clear the results for all scenarios belonging to GWLF-E projects made after
the release of 1.33.0, which had incorrectly aligned NLCD19 2019 on
2022-01-17:
... | Clear out unaligned NLCD19 GWLF-E results | Clear out unaligned NLCD19 GWLF-E results
Adds a migration that clears out all stored results for GWLF-E
projects created on or after 2022-01-17, which is when 1.33.0
was released with incorrectly aligned NLCD19 layers, which had
also been made the default. Thus, every project made after then
had slighly incorrect res... | Python | apache-2.0 | WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed,WikiWatershed/model-my-watershed | <REPLACE_OLD> <REPLACE_NEW> # Generated by Django 3.2.13 on 2022-10-17 13:47
from django.db import migrations
def clear_nlcd2019_gwlfe_results(apps, schema_editor):
"""
Clear the results for all scenarios belonging to GWLF-E projects made after
the release of 1.33.0, which had incorrectly aligned NLCD19... | Clear out unaligned NLCD19 GWLF-E results
Adds a migration that clears out all stored results for GWLF-E
projects created on or after 2022-01-17, which is when 1.33.0
was released with incorrectly aligned NLCD19 layers, which had
also been made the default. Thus, every project made after then
had slighly incorrect res... | |
2d8f221d55b0c04280a1b44ef72588882946fdea | takeoutStrings.py | takeoutStrings.py | #!/usr/bin/env python
# coding=utf-8
'''
This script will help you take out all strings.xml(Placed in a language-region folder) from an Android projectDir
We now use it to provide the strings and upload them to Crowdin.
'''
from os import system,listdir,path
from sys import argv
def takeoutStrings(resPath):
for... | Add script for Taking out of strings.xml files | Add script for Taking out of strings.xml files
| Python | apache-2.0 | androidyue/DroidPy | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
# coding=utf-8
'''
This script will help you take out all strings.xml(Placed in a language-region folder) from an Android projectDir
We now use it to provide the strings and upload them to Crowdin.
'''
from os import system,listdir,path
from sys import argv
def tak... | Add script for Taking out of strings.xml files
| |
d4274336756ed6d6c36f94cbaae7e8328ac50f9a | djedi/auth/__init__.py | djedi/auth/__init__.py | def has_permission(request):
user = request.user
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
return True
return False
def get_username(request):
user = request.user
if hasattr(user, 'ge... | import logging
_log = logging.getLogger(__name__)
def has_permission(request):
user = getattr(request, 'user', None)
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
return True
else:
_log.w... | Handle wrong order of middleware. | Handle wrong order of middleware.
| Python | bsd-3-clause | andreif/djedi-cms,andreif/djedi-cms,andreif/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms | <REPLACE_OLD> def <REPLACE_NEW> import logging
_log = logging.getLogger(__name__)
def <REPLACE_END> <REPLACE_OLD> request.user
<REPLACE_NEW> getattr(request, 'user', None)
<REPLACE_END> <REPLACE_OLD> True
<REPLACE_NEW> True
else:
_log.warning("Request does not have `user` attribute. Make sure that "
... | Handle wrong order of middleware.
def has_permission(request):
user = request.user
if user:
if user.is_superuser:
return True
if user.is_staff and user.groups.filter(name__iexact='djedi').exists():
return True
return False
def get_username(request):
user = re... |
09472f2cffb5fdd8481508d5a434ef9f1b1cd1a8 | code/python/knub/thesis/word2vec_converter.py | code/python/knub/thesis/word2vec_converter.py | import argparse
import logging
from gensim.models import Word2Vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == "__main__":
parser = argparse.ArgumentParser("Convert word2vec model from binary to txt")
parser.add_argument("model", type=str)
arg... | Add word2vec binary to txt format converter | Add word2vec binary to txt format converter
| Python | apache-2.0 | knub/master-thesis,knub/master-thesis,knub/master-thesis,knub/master-thesis | <INSERT> import argparse
import logging
from gensim.models import Word2Vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == "__main__":
<INSERT_END> <INSERT> parser = argparse.ArgumentParser("Convert word2vec model from binary to txt")
parser.add_argum... | Add word2vec binary to txt format converter
| |
5f945f5335cd5d989401fe99b0752e98595748c0 | chainer/functions/evaluation/binary_accuracy.py | chainer/functions/evaluation/binary_accuracy.py | import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class BinaryAccuracy(function.Function):
ignore_label = -1
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
x_type, t_type = in_types
type_check.ex... | import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class BinaryAccuracy(function.Function):
ignore_label = -1
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
x_type, t_type = in_types
type_check.ex... | Use maximum instead of if-statement | Use maximum instead of if-statement
| Python | mit | cupy/cupy,keisuke-umezawa/chainer,benob/chainer,ktnyt/chainer,anaruse/chainer,AlpacaDB/chainer,ktnyt/chainer,rezoo/chainer,niboshi/chainer,ysekky/chainer,jnishi/chainer,keisuke-umezawa/chainer,jnishi/chainer,niboshi/chainer,hvy/chainer,chainer/chainer,okuta/chainer,okuta/chainer,wkentaro/chainer,keisuke-umezawa/chainer... | <INSERT> xp.maximum(1, <INSERT_END> <REPLACE_OLD> self.ignore_label).sum()
if int(count) == 0:
count = 1
<REPLACE_NEW> self.ignore_label).sum())
<REPLACE_END> <|endoftext|> import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class BinaryAccura... | Use maximum instead of if-statement
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class BinaryAccuracy(function.Function):
ignore_label = -1
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
x_type, t_t... |
0c5b68ac40aeda415d1ccd551780f00eeafb54e8 | setup.py | setup.py | from setuptools import setup
import sys
install_requires = [
'oauth2client>=1.3.2',
'pyOpenSSL==0.14',
'simplejson>=2.3.2',
]
tests_require = list(install_requires)
# Python 2 requires Mock to run tests
if sys.version_info < (3, 0):
tests_require += ['pbr==1.6', 'Mock']
packages = ['identitytoolkit',]
s... | from setuptools import setup
import sys
install_requires = [
'oauth2client>=1.3.2',
'pyOpenSSL>=0.14',
'simplejson>=2.3.2',
]
tests_require = list(install_requires)
# Python 2 requires Mock to run tests
if sys.version_info < (3, 0):
tests_require += ['pbr==1.6', 'Mock']
packages = ['identitytoolkit',]
s... | Fix the pyOpenSSL version requirement. | Fix the pyOpenSSL version requirement. | Python | apache-2.0 | google/identity-toolkit-python-client | <REPLACE_OLD> 'pyOpenSSL==0.14',
<REPLACE_NEW> 'pyOpenSSL>=0.14',
<REPLACE_END> <|endoftext|> from setuptools import setup
import sys
install_requires = [
'oauth2client>=1.3.2',
'pyOpenSSL>=0.14',
'simplejson>=2.3.2',
]
tests_require = list(install_requires)
# Python 2 requires Mock to run tests
if sys.vers... | Fix the pyOpenSSL version requirement.
from setuptools import setup
import sys
install_requires = [
'oauth2client>=1.3.2',
'pyOpenSSL==0.14',
'simplejson>=2.3.2',
]
tests_require = list(install_requires)
# Python 2 requires Mock to run tests
if sys.version_info < (3, 0):
tests_require += ['pbr==1.6', 'Moc... |
83c5cc34539f68360cbab585af9465e95f3ec592 | tensorbayes/__init__.py | tensorbayes/__init__.py | from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function
| import sys
from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function
if 'ipykernel' in sys.argv[0]:
from . import nbutils
| Add nbutils import to base import | Add nbutils import to base import
| Python | mit | RuiShu/tensorbayes | <REPLACE_OLD> from <REPLACE_NEW> import sys
from <REPLACE_END> <REPLACE_OLD> function
<REPLACE_NEW> function
if 'ipykernel' in sys.argv[0]:
from . import nbutils
<REPLACE_END> <|endoftext|> import sys
from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions... | Add nbutils import to base import
from . import layers
from . import utils
from . import nputils
from . import tbutils
from . import distributions
from .utils import FileWriter
from .tbutils import function
|
e44dc4d68845845f601803f31e10833a24cdb27c | prosite_app.py | prosite_app.py | #!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
prositeMatcher = prosite_mat... | #!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expression: ")
if sequence != None and sequ... | Add check for empty sequence or regex. | Add check for empty sequence or regex.
| Python | mit | stack-overflow/py_finite_state | <REPLACE_OLD> ")
prositeMatcher <REPLACE_NEW> ")
if sequence != None and sequence != "" and regex != None and regex != "":
prositeMatcher <REPLACE_END> <REPLACE_OLD> prosite_matcher.PrositeMatcher()
prositeMatcher.compile(regex)
matches, <REPLACE_NEW> prosite_matcher.PrositeMatcher()
prositeMatcher.compile(r... | Add check for empty sequence or regex.
#!/bin/env python3
# Prosite regular expressions matcher
# Copyright (c) 2014 Tomasz Truszkowski
# All rights reserved.
import prosite_matcher
if __name__ == '__main__':
print("\n Hi, this is Prosite Matcher! \n")
sequence = input("Sequence: ")
regex = input("Regular expre... |
f25e0fe435f334e19fc84a9c9458a1bea4a051f9 | money/parser/__init__.py | money/parser/__init__.py | import csv
from money.models import Movement
def parse_csv(raw_csv, parser, header_lines=0):
reader = csv.reader(raw_csv, delimiter=',', quotechar='"')
rows = []
for row in reader:
if reader.line_num > header_lines and row:
rows.append(parser.parse_row(row))
return rows
def import_movements(data, bank_ac... | import csv
from money.models import Movement
def parse_csv(raw_csv, parser, header_lines=0, reverse_order=False):
reader = csv.reader(raw_csv, delimiter=',', quotechar='"')
rows = []
for row in reader:
if reader.line_num > header_lines and row:
rows.append(parser.parse_row(row))
... | Allow to reverse the order of the CSV for a proper reading | Allow to reverse the order of the CSV for a proper reading
| Python | bsd-3-clause | shakaran/casterly,shakaran/casterly | <REPLACE_OLD> header_lines=0):
reader <REPLACE_NEW> header_lines=0, reverse_order=False):
reader <REPLACE_END> <REPLACE_OLD> quotechar='"')
rows = []
for <REPLACE_NEW> quotechar='"')
rows = []
for <REPLACE_END> <REPLACE_OLD> reader:
if <REPLACE_NEW> reader:
if <REPLACE_END> <REPLACE_OLD> row:... | Allow to reverse the order of the CSV for a proper reading
import csv
from money.models import Movement
def parse_csv(raw_csv, parser, header_lines=0):
reader = csv.reader(raw_csv, delimiter=',', quotechar='"')
rows = []
for row in reader:
if reader.line_num > header_lines and row:
rows.append(parser.parse... |
a67b2c7280ab7e5ae831d372b1fc81f0a2f1f2ce | h5py/tests/hl/test_deprecation.py | h5py/tests/hl/test_deprecation.py | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Tests that deprecations work correctly
"""
from ... | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Tests that deprecations work correctly
"""
from ... | Fix test which appeared to not be run | BUG: Fix test which appeared to not be run
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py | <REPLACE_OLD> h5py
from <REPLACE_NEW> h5py
from h5py.h5py_warnings import H5pyDeprecationWarning
from <REPLACE_END> <REPLACE_OLD> hl <REPLACE_NEW> File <REPLACE_END> <REPLACE_OLD> h5py.highlevel
<REPLACE_NEW> h5py.highlevel.File
<REPLACE_END> <|endoftext|> # This file is part of h5py, a Python interface to the HDF5... | BUG: Fix test which appeared to not be run
# This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2018 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Test... |
4a404709081515fa0cc91683b5a9ad8f6a68eae6 | migrations/versions/630_remove_mandatory_assessment_methods_.py | migrations/versions/630_remove_mandatory_assessment_methods_.py | """Remove mandatory assessment methods from briefs
Revision ID: 630
Revises: 620
Create Date: 2016-06-03 15:26:53.890401
"""
# revision identifiers, used by Alembic.
revision = '630'
down_revision = '620'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, column
from sqlalchemy.dialect... | Add a migration to drop mandatory assessment methods from brief data | Add a migration to drop mandatory assessment methods from brief data
Removes work history and written proposal from all briefs, since
they're no longer a valid option for evaluationType and are added
automatically to all briefs.
Downgrade will add the options to all briefs based on lot. Since we
don't know if the bri... | Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api | <REPLACE_OLD> <REPLACE_NEW> """Remove mandatory assessment methods from briefs
Revision ID: 630
Revises: 620
Create Date: 2016-06-03 15:26:53.890401
"""
# revision identifiers, used by Alembic.
revision = '630'
down_revision = '620'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import table, c... | Add a migration to drop mandatory assessment methods from brief data
Removes work history and written proposal from all briefs, since
they're no longer a valid option for evaluationType and are added
automatically to all briefs.
Downgrade will add the options to all briefs based on lot. Since we
don't know if the bri... | |
0d6805bf6dce4b652f1b4f4556696c7521820790 | feder/users/autocomplete_light_registry.py | feder/users/autocomplete_light_registry.py | import autocomplete_light
from models import User
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['username']
def choices_for_request(self, *args, **kwargs):
qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
return qs.only('username')
a... | import autocomplete_light
from .models import User
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['username']
def choices_for_request(self, *args, **kwargs):
qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
return qs.only('username')
... | Fix typo in users autocomplete | Fix typo in users autocomplete
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | <REPLACE_OLD> models <REPLACE_NEW> .models <REPLACE_END> <|endoftext|> import autocomplete_light
from .models import User
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['username']
def choices_for_request(self, *args, **kwargs):
qs = super(UserAutocomplete, self).c... | Fix typo in users autocomplete
import autocomplete_light
from models import User
class UserAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['username']
def choices_for_request(self, *args, **kwargs):
qs = super(UserAutocomplete, self).choices_for_request(*args, **kwargs)
... |
100a03003adf3f425d59b69e95078bd0f1e82193 | test/reopen_screen.py | test/reopen_screen.py | #!/usr/bin/env python
# Test for bug reported by Jeremy Hill in which re-opening the screen
# would cause a segfault.
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()
from VisionEgg.Core import Screen, Viewport, swap_buffers
import pygame
from pygame.locals import QUIT,KEYDOWN,MOUSEBU... | Add test script for segfault bug reported by Jeremy Hill. | Add test script for segfault bug reported by Jeremy Hill.
git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@1477 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7
| Python | lgpl-2.1 | visionegg/visionegg,visionegg/visionegg,visionegg/visionegg,visionegg/visionegg,visionegg/visionegg | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
# Test for bug reported by Jeremy Hill in which re-opening the screen
# would cause a segfault.
import VisionEgg
VisionEgg.start_default_logging(); VisionEgg.watch_exceptions()
from VisionEgg.Core import Screen, Viewport, swap_buffers
import pygame
from pygame.local... | Add test script for segfault bug reported by Jeremy Hill.
git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@1477 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7
| |
84338dba126a25a0c37056df8d7fd0c5a13f2a69 | selftest.features/environment.py | selftest.features/environment.py | # -*- coding: UTF-8 -*-
"""
before_step(context, step), after_step(context, step)
These run before and after every step.
The step passed in is an instance of Step.
before_scenario(context, scenario), after_scenario(context, scenario)
These run before and after each scenario is run.
The scenario passed ... | # -*- coding: UTF-8 -*-
"""
before_step(context, step), after_step(context, step)
These run before and after every step.
The step passed in is an instance of Step.
before_scenario(context, scenario), after_scenario(context, scenario)
These run before and after each scenario is run.
The scenario passed ... | Disable after_all() output for now. | Disable after_all() output for now.
| Python | bsd-2-clause | jenisys/behave,jenisys/behave | <INSERT> # TEMPORARILY-DISABLED: <INSERT_END> <REPLACE_OLD> "SUMMARY:"
#def <REPLACE_NEW> "SUMMARY:"
pass
#def <REPLACE_END> <|endoftext|> # -*- coding: UTF-8 -*-
"""
before_step(context, step), after_step(context, step)
These run before and after every step.
The step passed in is an instance of Step.
be... | Disable after_all() output for now.
# -*- coding: UTF-8 -*-
"""
before_step(context, step), after_step(context, step)
These run before and after every step.
The step passed in is an instance of Step.
before_scenario(context, scenario), after_scenario(context, scenario)
These run before and after each scen... |
840dce03718947498e72e561e7ddca22c4174915 | django_olcc/olcc/context_processors.py | django_olcc/olcc/context_processors.py | from olcc.models import ImportRecord
"""
Inject the last import date into the request context.
"""
def last_updated(request):
record = ImportRecord.objects.latest()
if record:
return {
'last_updated': record.created_at
}
| from olcc.models import ImportRecord
"""
Inject the last import date into the request context.
"""
def last_updated(request):
try:
return {
'last_updated': ImportRecord.objects.latest().created_at
}
except ImportRecord.DoesNotExist:
pass
| Fix a DoesNotExist bug in the olcc context processor. | Fix a DoesNotExist bug in the olcc context processor.
| Python | mit | twaddington/django-olcc,twaddington/django-olcc,twaddington/django-olcc | <REPLACE_OLD> record = ImportRecord.objects.latest()
if record:
<REPLACE_NEW> try:
<REPLACE_END> <REPLACE_OLD> record.created_at
<REPLACE_NEW> ImportRecord.objects.latest().created_at
<REPLACE_END> <INSERT> except ImportRecord.DoesNotExist:
pass
<INSERT_END> <|endoftext|> from olcc.models import Imp... | Fix a DoesNotExist bug in the olcc context processor.
from olcc.models import ImportRecord
"""
Inject the last import date into the request context.
"""
def last_updated(request):
record = ImportRecord.objects.latest()
if record:
return {
'last_updated': record.created_at
}
|
1525c25029a2cd93494ebab45377661d606fa7ab | make_mozilla/events/tasks.py | make_mozilla/events/tasks.py | from celery.decorators import task
from make_mozilla.bsd import BSDRegisterConstituent
@task
def register_email_address_as_constituent(email_address, group):
BSDRegisterConstituent.add_email_to_group(email_address, group)
| from celery.task import task
from make_mozilla.bsd import BSDRegisterConstituent
@task
def register_email_address_as_constituent(email_address, group):
BSDRegisterConstituent.add_email_to_group(email_address, group)
| Switch to post Celery 2.2 task decorator syntax. | Switch to post Celery 2.2 task decorator syntax. | Python | bsd-3-clause | mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org,mozilla/make.mozilla.org | <REPLACE_OLD> celery.decorators <REPLACE_NEW> celery.task <REPLACE_END> <|endoftext|> from celery.task import task
from make_mozilla.bsd import BSDRegisterConstituent
@task
def register_email_address_as_constituent(email_address, group):
BSDRegisterConstituent.add_email_to_group(email_address, group)
| Switch to post Celery 2.2 task decorator syntax.
from celery.decorators import task
from make_mozilla.bsd import BSDRegisterConstituent
@task
def register_email_address_as_constituent(email_address, group):
BSDRegisterConstituent.add_email_to_group(email_address, group)
|
2c70c70099cffe88439fa082fb0e7942d8cfed88 | tests/run_tests.py | tests/run_tests.py | #!/bin/env python
"""Run HTCondor-CE unit tests"""
import glob
import unittest
TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
unittest.TextTestRunner(verbosity=2).run(SUITE)
| #!/bin/env python
"""Run HTCondor-CE unit tests"""
import glob
import unittest
import sys
TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
RESULTS = unittest.TextTestRunner(verbosity=2).run(SUITE)
if not RESULTS.wasSuccessful():
sys.exit(1)
| Exit non-zero if unit tests failed | Exit non-zero if unit tests failed
| Python | apache-2.0 | matyasselmeci/htcondor-ce,brianhlin/htcondor-ce,opensciencegrid/htcondor-ce,djw8605/htcondor-ce,brianhlin/htcondor-ce,brianhlin/htcondor-ce,matyasselmeci/htcondor-ce,opensciencegrid/htcondor-ce,bbockelm/htcondor-ce,opensciencegrid/htcondor-ce,matyasselmeci/htcondor-ce,djw8605/htcondor-ce,bbockelm/htcondor-ce,djw8605/ht... | <REPLACE_OLD> unittest
TESTS <REPLACE_NEW> unittest
import sys
TESTS <REPLACE_END> <REPLACE_OLD> unittest.TestLoader().loadTestsFromNames(TESTS)
unittest.TextTestRunner(verbosity=2).run(SUITE)
<REPLACE_NEW> unittest.TestLoader().loadTestsFromNames(TESTS)
RESULTS = unittest.TextTestRunner(verbosity=2).run(SUITE)
... | Exit non-zero if unit tests failed
#!/bin/env python
"""Run HTCondor-CE unit tests"""
import glob
import unittest
TESTS = [test.strip('.py') for test in glob.glob('test*.py')]
SUITE = unittest.TestLoader().loadTestsFromNames(TESTS)
unittest.TextTestRunner(verbosity=2).run(SUITE)
|
ecb3a296b379f4abdc03ce5de447b30ada5f124e | txircd/modules/rfc/cmode_l.py | txircd/modules/rfc/cmode_l.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "Lim... | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData, Mode):
implements(IPlugin, IModuleData, IMode)
name = "Lim... | Return the parameter for channel mode +l as a list | Return the parameter for channel mode +l as a list
This fixes a bug where every digit was handled as a separate parameter, causing
"MODE #channel +l 10" to turn into "MODE #channel +ll 1 0"
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd | <REPLACE_OLD> param
<REPLACE_NEW> [param]
<REPLACE_END> <|endoftext|> from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleData, Mode, ModuleData
from txircd.utils import ModeType
from zope.interface import implements
class LimitMode(ModuleData,... | Return the parameter for channel mode +l as a list
This fixes a bug where every digit was handled as a separate parameter, causing
"MODE #channel +l 10" to turn into "MODE #channel +ll 1 0"
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IMode, IModuleDat... |
0b3f6ae3b21cd51b99bcecf17d5ea1275c04abfd | statirator/project_template/project_name/settings.py | statirator/project_template/project_name/settings.py | # Generated by statirator
import os
# directories setup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')
# languages setup
LANGUAGE_CODE = '{{default_lang}}'
_ = lambda s:s
LANGUAGES ... | # Generated by statirator
import os
# directories setup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')
# languages setup
LANGUAGE_CODE = '{{default_lang}}'
_ = lambda s:s
LANGUAGES ... | Add taggit and statirator.blog to INSTALLED_APPS | Add taggit and statirator.blog to INSTALLED_APPS
| Python | mit | MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator | <REPLACE_OLD> 'django_medusa',
)
MEDUSA_RENDERER_CLASS <REPLACE_NEW> 'django_medusa',
'taggit',
'statirator.blog',
)
MEDUSA_RENDERER_CLASS <REPLACE_END> <|endoftext|> # Generated by statirator
import os
# directories setup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE... | Add taggit and statirator.blog to INSTALLED_APPS
# Generated by statirator
import os
# directories setup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')
# languages setup
LANGUAGE_CO... |
a06e6cc3c0b0440d3adedd1ccce78309d8fae9a9 | feincms/module/page/extensions/navigationgroups.py | feincms/module/page/extensions/navigationgroups.py | """
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import extensions
class Extension(exten... | """
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import extensions
class Extension(exten... | Allow navigationgroup to be blank | Allow navigationgroup to be blank
| Python | bsd-3-clause | joshuajonah/feincms,feincms/feincms,joshuajonah/feincms,joshuajonah/feincms,feincms/feincms,joshuajonah/feincms,feincms/feincms,mjl/feincms,mjl/feincms,mjl/feincms | <INSERT> blank=True,
<INSERT_END> <|endoftext|> """
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_l... | Allow navigationgroup to be blank
"""
Page navigation groups allow assigning pages to differing navigation lists
such as header, footer and what else.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import... |
b23ab20a082e35e6e4c8bf9a535b1bbccd71be26 | docs/examples/tests/pylab_figshow.py | docs/examples/tests/pylab_figshow.py | """Manual test for figure.show() in the inline matplotlib backend.
This script should be loaded for interactive use (via %load) into a qtconsole
or notebook initialized with the pylab inline backend.
Expected behavior: only *one* copy of the figure is shown.
For further details:
https://github.com/ipython/ipython... | Add manual test file as per review by @minrk. | Add manual test file as per review by @minrk.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | <INSERT> """Manual test for figure.show() in the inline matplotlib backend.
This script should be loaded for interactive use (via %load) into a qtconsole
or notebook initialized with the pylab inline backend. <INSERT_END> <INSERT>
Expected behavior: only *one* copy of the figure is shown.
For further details:
http... | Add manual test file as per review by @minrk.
| |
3e5af3f8ba0eacc8f29e51daec43e395eae27ab8 | partner_email_check/models/res_partner.py | partner_email_check/models/res_partner.py | # Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
try:
from validate_email import validate_email
except ImportError:
... | # Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
try:
from validate_email import validate_email
except ImportError:
... | Make debugger record a debug message instead of error when importing validate_email in partner_email_check | [FIX][11.0] Make debugger record a debug message instead of error when importing validate_email in partner_email_check
| Python | agpl-3.0 | Vauxoo/partner-contact,Vauxoo/partner-contact | <REPLACE_OLD> _logger.error('Cannot <REPLACE_NEW> _logger.debug('Cannot <REPLACE_END> <|endoftext|> # Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
from odoo.exceptions import UserError
_logger = logg... | [FIX][11.0] Make debugger record a debug message instead of error when importing validate_email in partner_email_check
# Copyright 2019 Komit <https://komit-consulting.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
import logging
from odoo import api, models, _
from odoo.exceptions import User... |
ff0468f51b6a5cebd00f2cea8d2abd5f74e925d6 | ometa/tube.py | ometa/tube.py | from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@param grammar: The grammar used to parse the incomin... | from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@param grammar: The grammar used to parse the incomin... | Update TrampolinedParser a little for my purposes. | Update TrampolinedParser a little for my purposes.
| Python | mit | rbtcollins/parsley,python-parsley/parsley,python-parsley/parsley,rbtcollins/parsley | <REPLACE_OLD> ruleName='initial', callback=None,
<REPLACE_NEW> ruleName=self.receiver.currentRule,
callback=None, <REPLACE_END> <DELETE> try:
<DELETE_END> <DELETE> except Exception as e:
# maybe we should raise it?
raise e
el... | Update TrampolinedParser a little for my purposes.
from ometa.interp import TrampolinedGrammarInterpreter, _feed_me
class TrampolinedParser:
"""
A parser that incrementally parses incoming data.
"""
def __init__(self, grammar, receiver, bindings):
"""
Initializes the parser.
@... |
4ffb58466820cfb2569cf4d4837c8e48caed2c17 | seven23/api/permissions.py | seven23/api/permissions.py |
from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` a... |
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attri... | Fix issue with imezone on IsPaid Permission | Fix issue with imezone on IsPaid Permission
| Python | mit | sebastienbarbier/723e,sebastienbarbier/723e_server,sebastienbarbier/723e_server,sebastienbarbier/723e | <REPLACE_OLD> django.utils import timezone
from <REPLACE_NEW> datetime import datetime
from <REPLACE_END> <REPLACE_OLD> timezone.now() <REPLACE_NEW> datetime.today() <REPLACE_END> <|endoftext|>
from itertools import chain
from rest_framework import permissions
from datetime import datetime
from seven23 import settings... | Fix issue with imezone on IsPaid Permission
from itertools import chain
from rest_framework import permissions
from django.utils import timezone
from seven23 import settings
class CanWriteAccount(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
... |
0a2dc53cd388f73064bb66e794e3af5f3e48a92f | bot/setup.py | bot/setup.py | from setuptools import setup, find_packages
PACKAGE_NAME = "ReviewBot"
VERSION = "0.1"
setup(name=PACKAGE_NAME,
version=VERSION,
description="ReviewBot, the automated code reviewer",
author="Steven MacLeod",
author_email="steven@smacleod.ca",
packages=find_packages(),
entry_points... | from setuptools import setup, find_packages
PACKAGE_NAME = "ReviewBot"
VERSION = "0.1"
setup(name=PACKAGE_NAME,
version=VERSION,
description="ReviewBot, the automated code reviewer",
author="Steven MacLeod",
author_email="steven@smacleod.ca",
packages=find_packages(),
entry_points... | Update the required version of Celery | Update the required version of Celery
| Python | mit | reviewboard/ReviewBot,reviewboard/ReviewBot,reviewboard/ReviewBot,reviewboard/ReviewBot | <REPLACE_OLD> 'celery>=2.5',
<REPLACE_NEW> 'celery>=3.0',
<REPLACE_END> <|endoftext|> from setuptools import setup, find_packages
PACKAGE_NAME = "ReviewBot"
VERSION = "0.1"
setup(name=PACKAGE_NAME,
version=VERSION,
description="ReviewBot, the automated code reviewer",
author="Steven MacLeod",
... | Update the required version of Celery
from setuptools import setup, find_packages
PACKAGE_NAME = "ReviewBot"
VERSION = "0.1"
setup(name=PACKAGE_NAME,
version=VERSION,
description="ReviewBot, the automated code reviewer",
author="Steven MacLeod",
author_email="steven@smacleod.ca",
packa... |
6814bed9918640346e4a096c8f410a6fc2b5508e | corehq/tests/noseplugins/uniformresult.py | corehq/tests/noseplugins/uniformresult.py | """A plugin to format test names uniformly for easy comparison
Usage:
# collect django tests
COLLECT_ONLY=1 ./manage.py test -v2 --settings=settings 2> tests-django.txt
# collect nose tests
./manage.py test -v2 --collect-only 2> tests-nose.txt
# clean up django test output: s/skipped\ \'.*\'$/ok... | """A plugin to format test names uniformly for easy comparison
Usage:
# collect django tests
COLLECT_ONLY=1 ./manage.py test -v2 --settings=settings 2> tests-django.txt
# collect nose tests
./manage.py test -v2 --collect-only 2> tests-nose.txt
# clean up django test output: s/skipped\ \'.*\'$/ok... | Use a copypastable format for function tests | Use a copypastable format for function tests
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | <REPLACE_OLD> return str(test)
<REPLACE_NEW> descriptor = test.descriptor or test.test
return "%s:%s args %s" % (
descriptor.__module__,
descriptor.__name__,
test.arg,
)
<REPLACE_END> <|endoftext|> """A plugin to format test names uniformly for easy comparison
Usag... | Use a copypastable format for function tests
"""A plugin to format test names uniformly for easy comparison
Usage:
# collect django tests
COLLECT_ONLY=1 ./manage.py test -v2 --settings=settings 2> tests-django.txt
# collect nose tests
./manage.py test -v2 --collect-only 2> tests-nose.txt
# clea... |
ebb0236d7c68883de7a4202df23e74becd943f29 | hooks/pre_gen_project.py | hooks/pre_gen_project.py | project_slug = '{{ cookiecutter.project_slug }}'
print('pre gen')
if hasattr(project_slug, 'isidentifier'):
assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
| project_slug = '{{ cookiecutter.project_slug }}'
if hasattr(project_slug, 'isidentifier'):
assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
| Fix a typo in the pre-generation hooks | Fix a typo in the pre-generation hooks
| Python | bsd-3-clause | valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp | <REPLACE_OLD> }}'
print('pre gen')
if <REPLACE_NEW> }}'
if <REPLACE_END> <|endoftext|> project_slug = '{{ cookiecutter.project_slug }}'
if hasattr(project_slug, 'isidentifier'):
assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
| Fix a typo in the pre-generation hooks
project_slug = '{{ cookiecutter.project_slug }}'
print('pre gen')
if hasattr(project_slug, 'isidentifier'):
assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
|
0d8a9a83fdd896aa5690c1c32db1d1658748a94a | tests/test_schemaorg.py | tests/test_schemaorg.py | import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.... | import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8") as pagedata:
self.schema = SchemaOrg(pagedata.... | Add test coverage for expected nutrient retrieval behaviour | Add test coverage for expected nutrient retrieval behaviour
| Python | mit | hhursev/recipe-scraper | <INSERT> test_nutrient_retrieval(self):
expected_nutrients = {
"calories": "240 calories",
"fatContent": "9 grams fat",
}
self.assertEqual(self.schema.nutrients(), expected_nutrients)
def <INSERT_END> <|endoftext|> import unittest
from recipe_scrapers._exceptions im... | Add test coverage for expected nutrient retrieval behaviour
import unittest
from recipe_scrapers._exceptions import SchemaOrgException
from recipe_scrapers._schemaorg import SchemaOrg
class TestSchemaOrg(unittest.TestCase):
def setUp(self):
with open("tests/test_data/schemaorg.testhtml", encoding="utf-8... |
5d9b4af15b60f5f597179fdfc66f0539acc48798 | phonetics_download.py | phonetics_download.py | '''
Created on 2013-12-20
@author: bn
'''
# -*- coding: gbk -*-
import re
try:
input = raw_input
except NameError:
pass
try:
import urllib.request
#import urllib.parse
except ImportError:
import urllib
urllib.request = __import__('urllib2')
urllib.parse = __import__('urlparse')
urlope... | Add phonetics download from aiciba, can download more things from aiciba in future | Add phonetics download from aiciba, can download more things from aiciba in future
| Python | apache-2.0 | crike/crike,crike/crike,crike/crike,crike/crike | <REPLACE_OLD> <REPLACE_NEW> '''
Created on 2013-12-20
@author: bn
'''
# -*- coding: gbk -*-
import re
try:
input = raw_input
except NameError:
pass
try:
import urllib.request
#import urllib.parse
except ImportError:
import urllib
urllib.request = __import__('urllib2')
urllib.parse = __... | Add phonetics download from aiciba, can download more things from aiciba in future
| |
096424ea7809e5512a932c79eff6676695c1d27e | telethon/network/connection/connection.py | telethon/network/connection/connection.py | import abc
import asyncio
class Connection(abc.ABC):
"""
The `Connection` class is a wrapper around ``asyncio.open_connection``.
Subclasses are meant to communicate with this class through a queue.
This class provides a reliable interface that will stay connected
under any conditions for as long... | Create a new Connection class to work through queues | Create a new Connection class to work through queues
| Python | mit | LonamiWebs/Telethon,expectocode/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon,LonamiWebs/Telethon | <REPLACE_OLD> <REPLACE_NEW> import abc
import asyncio
class Connection(abc.ABC):
"""
The `Connection` class is a wrapper around ``asyncio.open_connection``.
Subclasses are meant to communicate with this class through a queue.
This class provides a reliable interface that will stay connected
und... | Create a new Connection class to work through queues
| |
bbc1d797e8e05ec8b0f7934116bd9ca7a402ba2f | setup.py | setup.py | #from distutils.core import setup
from setuptools import setup
setup(
name='auth_mac',
version='0.1',
description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01",
author='Nicholas Devenish',
author_email='n.devenish@gmail.com',
packages=['auth_mac', 'auth_mac.tests'],
... | #from distutils.core import setup
from setuptools import setup
setup(
name='django-auth_mac',
version='0.1',
description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01",
author='Nicholas Devenish',
author_email='n.devenish@gmail.com',
packages=['auth_mac', 'auth_mac.tes... | Change the "name" to django-auth_mac | Change the "name" to django-auth_mac
| Python | mit | ndevenish/auth_mac | <REPLACE_OLD> name='auth_mac',
<REPLACE_NEW> name='django-auth_mac',
<REPLACE_END> <|endoftext|> #from distutils.core import setup
from setuptools import setup
setup(
name='django-auth_mac',
version='0.1',
description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01",
author='N... | Change the "name" to django-auth_mac
#from distutils.core import setup
from setuptools import setup
setup(
name='auth_mac',
version='0.1',
description="Basic Django implementation of the draft RFC ietf-oauth-v2-http-mac-01",
author='Nicholas Devenish',
author_email='n.devenish@gmail.com',
pack... |
839cb6f1d1a04f420d818406652eb9ce51d290dd | epitran/bin/migraterules.py | epitran/bin/migraterules.py | #!/usr/bin/env Python
# -*- coding: utf-8 -*-
from __future__ import (print_function, unicode_literals, absolute_import)
import glob
import re
import io
import unicodecsv
def build_rule(fields):
try:
a, b, X, Y = fields
b = 0 if not b else b
a = 0 if not a else a
return '{} -> {... | #!/usr/bin/env Python
# -*- coding: utf-8 -*-
from __future__ import (print_function, unicode_literals, absolute_import)
import glob
import re
import io
import unicodecsv
def build_rule(fields):
try:
a, b, X, Y = fields
b = "0" if not b else b
a = "0" if not a else a
return '{} ... | Use strings instead of numerals for "0" in rules | Use strings instead of numerals for "0" in rules
| Python | mit | dmort27/epitran,dmort27/epitran | <REPLACE_OLD> 0 <REPLACE_NEW> "0" <REPLACE_END> <REPLACE_OLD> 0 <REPLACE_NEW> "0" <REPLACE_END> <|endoftext|> #!/usr/bin/env Python
# -*- coding: utf-8 -*-
from __future__ import (print_function, unicode_literals, absolute_import)
import glob
import re
import io
import unicodecsv
def build_rule(fields):
try:
... | Use strings instead of numerals for "0" in rules
#!/usr/bin/env Python
# -*- coding: utf-8 -*-
from __future__ import (print_function, unicode_literals, absolute_import)
import glob
import re
import io
import unicodecsv
def build_rule(fields):
try:
a, b, X, Y = fields
b = 0 if not b else b
... |
18618a56ce674c479a0737dcabd4a47913ae2dde | scripts/compare_dir.py | scripts/compare_dir.py | import os
dropboxFiles = []
localFiles = []
for dirpath, dirnames, filenames in os.walk(
'/media/itto/TOSHIBA EXT/Photos/Dropbox/ITTO/Southeast Asia 2017'):
dropboxFiles += filenames
for dirpath, dirnames, filenames in os.walk(
'/media/itto/TOSHIBA EXT/Photos/Southeast Asia'):
if ('Process' no... | import os
from shutil import copyfile
FOLDER_A = '/media/itto/TOSHIBA EXT/Photos/Southeast Asia'
FOLDER_B = '/media/itto/disk/PRIVATE/AVCHD/BDMV/STREAM'
files_a = []
files_b = []
for dirpath, dirnames, filenames in os.walk(FOLDER_A):
files_a += filenames
for dirpath, dirnames, filenames in os.walk(FOLDER_B):
... | Add functionality to copy any missing files to the other folder | Add functionality to copy any missing files to the other folder
| Python | mit | itko/itko.github.io,itko/itko.github.io,itko/itko.github.io,itko/itko.github.io | <REPLACE_OLD> os
dropboxFiles = []
localFiles <REPLACE_NEW> os
from shutil import copyfile
FOLDER_A = '/media/itto/TOSHIBA EXT/Photos/Southeast Asia'
FOLDER_B = '/media/itto/disk/PRIVATE/AVCHD/BDMV/STREAM'
files_a = []
files_b <REPLACE_END> <REPLACE_OLD> os.walk(
'/media/itto/TOSHIBA EXT/Photos/Dropbox/ITTO/S... | Add functionality to copy any missing files to the other folder
import os
dropboxFiles = []
localFiles = []
for dirpath, dirnames, filenames in os.walk(
'/media/itto/TOSHIBA EXT/Photos/Dropbox/ITTO/Southeast Asia 2017'):
dropboxFiles += filenames
for dirpath, dirnames, filenames in os.walk(
'/me... |
48884e305609e7c17eb3906c22ce509191f0d00e | passeplat.py | passeplat.py | from flask import Flask, request
import requests
app = Flask(__name__)
API_ROOT_URL = "https://api.heroku.com/"
# uses ~./netrc otherwise which might interfere with your requests
requests.defaults.defaults['trust_env'] = False
@app.route("/", methods=['GET', 'POST', 'DELETE', 'PUT'])
@app.route("/<path:path>", method... | from flask import Flask, request, Response
import requests
app = Flask(__name__)
API_ROOT_URL = "https://api.heroku.com/"
# uses ~./netrc otherwise which might interfere with your requests
requests.defaults.defaults['trust_env'] = False
@app.route("/", methods=['GET', 'POST', 'DELETE', 'PUT'])
@app.route("/<path:path... | Add more complete flask.Response object as return object | Add more complete flask.Response object as return object
Also, selects a couple of specific headers to pass along to Requests. To improve in the future :) | Python | mit | Timothee/Passeplat | <REPLACE_OLD> request
import <REPLACE_NEW> request, Response
import <REPLACE_END> <REPLACE_OLD> {}
for k, v <REPLACE_NEW> {}
if 'Authorization' <REPLACE_END> <REPLACE_OLD> request.headers:
clean_headers[k] <REPLACE_NEW> request.headers:
clean_headers['Authorization'] <REPLACE_END> <REPLACE_OLD> v
# <REPLACE_NEW... | Add more complete flask.Response object as return object
Also, selects a couple of specific headers to pass along to Requests. To improve in the future :)
from flask import Flask, request
import requests
app = Flask(__name__)
API_ROOT_URL = "https://api.heroku.com/"
# uses ~./netrc otherwise which might interfere wit... |
fb26c402c433ac3358dbaadfb71762cfaf506a34 | jp2_online/settings/production.py | jp2_online/settings/production.py | # -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST = ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT = os.path.join(BASE_DIR, "../static/") | # -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org']
CORS_ORIGIN_WHITELIST = (
'138.197.197.47',
'junipero.erikiado.com',
'b... | Add subdomain for educacion integral | Add subdomain for educacion integral
| Python | mit | erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online | <REPLACE_OLD> ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST <REPLACE_NEW> [
'138.197.197.47',
'junipero.erikiado.com',
'basededatos.educacionintegral.org']
CORS_ORIGIN_WHITELIST <REPLACE_END> <REPLACE_OLD> ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT <REPLACE_NEW> (
'13... | Add subdomain for educacion integral
# -*- coding: utf-8 -*-
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['138.197.197.47', 'junipero.erikiado.com']
CORS_ORIGIN_WHITELIST = ('138.197.197.47', 'junipero.erikiado.com')
STATIC_ROOT = os.path.join... |
d9486bc6180a2dfe38a953eb84184e0410e1cb66 | enthought/enable/null/quartz.py | enthought/enable/null/quartz.py | #------------------------------------------------------------------------------
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describe... | Add a Quartz backend for the null toolkit | Add a Quartz backend for the null toolkit
| Python | bsd-3-clause | tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable | <REPLACE_OLD> <REPLACE_NEW> #------------------------------------------------------------------------------
# Copyright (c) 2011, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# ... | Add a Quartz backend for the null toolkit
| |
b1bb4154a69a6ae4bb31cbf27f0871069291e1d6 | nist_beacon_constants.py | nist_beacon_constants.py | NIST_KEY_FREQUENCY = 'frequency'
NIST_KEY_OUTPUT_VALUE = 'outputValue'
NIST_KEY_PREVIOUS_OUTPUT_VALUE = 'previousOutputValue'
NIST_KEY_SEED_VALUE = 'seedValue'
NIST_KEY_SIGNATURE_VALUE = 'signatureValue'
NIST_KEY_STATUS_CODE = 'statusCode'
NIST_KEY_TIMESTAMP = 'timeStamp'
NIST_KEY_VERSION = 'version'
| Prepare constants into seperate location | Prepare constants into seperate location
| Python | apache-2.0 | urda/nistbeacon | <REPLACE_OLD> <REPLACE_NEW> NIST_KEY_FREQUENCY = 'frequency'
NIST_KEY_OUTPUT_VALUE = 'outputValue'
NIST_KEY_PREVIOUS_OUTPUT_VALUE = 'previousOutputValue'
NIST_KEY_SEED_VALUE = 'seedValue'
NIST_KEY_SIGNATURE_VALUE = 'signatureValue'
NIST_KEY_STATUS_CODE = 'statusCode'
NIST_KEY_TIMESTAMP = 'timeStamp'
NIST_KEY_VERSION =... | Prepare constants into seperate location
| |
b786ae0b845374ca42db42ac64322d6aa9e894c5 | setup.py | setup.py | from distutils.core import setup
setup(name='TOPKAPI',
version='0.2dev',
description='SAHG TOPKAPI model implementation',
author='Theo Vischel & Scott Sinclair',
author_email='theo.vischel@hmg.inpg.fr; sinclaird@ukzn.ac.za',
packages=['TOPKAPI', 'TOPKAPI.parameter_utils', 'TOPKAPI.results... | from distutils.core import setup
setup(name='TOPKAPI',
version='0.2dev',
description='SAHG TOPKAPI model implementation',
author='Theo Vischel & Scott Sinclair',
author_email='theo.vischel@hmg.inpg.fr; sinclaird@ukzn.ac.za',
packages=['TOPKAPI',
'TOPKAPI.parameter_utils',
... | Reformat to be more pleasing on the eye | STY: Reformat to be more pleasing on the eye
| Python | bsd-3-clause | sahg/PyTOPKAPI,scottza/PyTOPKAPI | <REPLACE_OLD> packages=['TOPKAPI', 'TOPKAPI.parameter_utils', <REPLACE_NEW> packages=['TOPKAPI',
'TOPKAPI.parameter_utils',
<REPLACE_END> <|endoftext|> from distutils.core import setup
setup(name='TOPKAPI',
version='0.2dev',
description='SAHG TOPKAPI model implementation',
... | STY: Reformat to be more pleasing on the eye
from distutils.core import setup
setup(name='TOPKAPI',
version='0.2dev',
description='SAHG TOPKAPI model implementation',
author='Theo Vischel & Scott Sinclair',
author_email='theo.vischel@hmg.inpg.fr; sinclaird@ukzn.ac.za',
packages=['TOPKAPI... |
3152ee5ca2f21708e428faac5eaadbb403d0a1dc | spacy/tests/serialize/test_serialize_tokenizer.py | spacy/tests/serialize/test_serialize_tokenizer.py | # coding: utf-8
from __future__ import unicode_literals
from ..util import make_tempdir
import pytest
@pytest.mark.parametrize('text', ["I can't do this"])
def test_serialize_tokenizer_roundtrip_bytes(en_tokenizer, text):
tokenizer_b = en_tokenizer.to_bytes()
new_tokenizer = en_tokenizer.from_bytes(tokenize... | # coding: utf-8
from __future__ import unicode_literals
from ...util import get_lang_class
from ..util import make_tempdir, assert_packed_msg_equal
import pytest
def load_tokenizer(b):
tok = get_lang_class('en').Defaults.create_tokenizer()
tok.from_bytes(b)
return tok
@pytest.mark.parametrize('text', ... | Update serialization tests for tokenizer | Update serialization tests for tokenizer
| Python | mit | honnibal/spaCy,honnibal/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaC... | <INSERT> ...util import get_lang_class
from <INSERT_END> <REPLACE_OLD> make_tempdir
import pytest
@pytest.mark.parametrize('text', ["I can't do this"])
def <REPLACE_NEW> make_tempdir, assert_packed_msg_equal
import pytest
def load_tokenizer(b):
tok = get_lang_class('en').Defaults.create_tokenizer()
tok.fr... | Update serialization tests for tokenizer
# coding: utf-8
from __future__ import unicode_literals
from ..util import make_tempdir
import pytest
@pytest.mark.parametrize('text', ["I can't do this"])
def test_serialize_tokenizer_roundtrip_bytes(en_tokenizer, text):
tokenizer_b = en_tokenizer.to_bytes()
new_to... |
7d7afb7d92797b48f215505579e0fb872deee0f3 | rst2pdf/utils.py | rst2pdf/utils.py | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of flowables.
Supported (ca... | # -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
from styles import adjustUnits
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of f... | Add unit support for spacers | Add unit support for spacers
| Python | mit | rafaelmartins/rst2pdf,rafaelmartins/rst2pdf | <REPLACE_OLD> *
def <REPLACE_NEW> *
from styles import adjustUnits
def <REPLACE_END> <REPLACE_OLD> elements.append(Spacer(int(tokens[1]), int(tokens[2])))
<REPLACE_NEW> elements.append(Spacer(adjustUnits(tokens[1]),
adjustUnits(tokens[2])))
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 ... | Add unit support for spacers
# -*- coding: utf-8 -*-
# See LICENSE.txt for licensing terms
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import shlex
from reportlab.platypus import Spacer
from flowables import *
def parseRaw(data):
"""Parse and process a simple DSL to handle creation of f... |
d7025f92a240284d130ce455b6975ede42d0228e | chalice/cli/filewatch/eventbased.py | chalice/cli/filewatch/eventbased.py | import threading # noqa
from typing import Callable, Optional # noqa
import watchdog.observers
from watchdog.events import FileSystemEventHandler
from watchdog.events import FileSystemEvent # noqa
from chalice.cli.filewatch import FileWatcher, WorkerProcess
class WatchdogWorkerProcess(WorkerProcess):
"""Work... | import threading # noqa
from typing import Callable, Optional # noqa
import watchdog.observers # pylint: disable=import-error
from watchdog import events # pylint: disable=import-error
from chalice.cli.filewatch import FileWatcher, WorkerProcess
class WatchdogWorkerProcess(WorkerProcess):
"""Worker that run... | Make prcheck pass without needing cond deps | Make prcheck pass without needing cond deps
| Python | apache-2.0 | awslabs/chalice | <REPLACE_OLD> watchdog.observers
from watchdog.events <REPLACE_NEW> watchdog.observers # pylint: disable=import-error
from watchdog <REPLACE_END> <REPLACE_OLD> FileSystemEventHandler
from watchdog.events import FileSystemEvent # noqa
from <REPLACE_NEW> events # pylint: disable=import-error
from <REPLACE_END> <REPL... | Make prcheck pass without needing cond deps
import threading # noqa
from typing import Callable, Optional # noqa
import watchdog.observers
from watchdog.events import FileSystemEventHandler
from watchdog.events import FileSystemEvent # noqa
from chalice.cli.filewatch import FileWatcher, WorkerProcess
class Watc... |
6f2a9cbf9e571855074e898d22480d61277a3eda | django_lightweight_queue/backends/db.py | django_lightweight_queue/backends/db.py | import time
import datetime
from django.db import connection, models, ProgrammingError
from ..job import Job
class DatabaseBackend(object):
TABLE = 'django_lightweight_queue'
FIELDS = (
models.AutoField(name='id', primary_key=True),
models.CharField(name='queue', max_length=255),
mod... | Add experimental polling DB backend. | Add experimental polling DB backend.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| Python | bsd-3-clause | thread/django-lightweight-queue,thread/django-lightweight-queue,lamby/django-lightweight-queue,prophile/django-lightweight-queue,prophile/django-lightweight-queue | <REPLACE_OLD> <REPLACE_NEW> import time
import datetime
from django.db import connection, models, ProgrammingError
from ..job import Job
class DatabaseBackend(object):
TABLE = 'django_lightweight_queue'
FIELDS = (
models.AutoField(name='id', primary_key=True),
models.CharField(name='queue',... | Add experimental polling DB backend.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com>
| |
e8c9c22c7c57ff2de8b9ef9e73ec8f339aa73fd7 | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
if sys.version < '2.7':
print 'Python >= 2.7 required'
sys.exit(1)
from setuptools import setup
long_description = '''
A simple Python package for using Twitter search functionality
that is only available through the Twitter web interface
(such as searching for twee... | #!/usr/bin/env python
import os
import sys
if sys.version < '2.7':
print 'Python >= 2.7 required'
sys.exit(1)
from setuptools import setup
long_description = '''
A simple Python package for using Twitter search functionality
that is only available through the Twitter web interface
(such as searching for twee... | Increase version number to 0.1.1 (breaking API change) | Increase version number to 0.1.1 (breaking API change)
| Python | mit | ShinNoNoir/twitterwebsearch | <REPLACE_OLD> version='0.0.5',
<REPLACE_NEW> version='0.1.1',
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
import os
import sys
if sys.version < '2.7':
print 'Python >= 2.7 required'
sys.exit(1)
from setuptools import setup
long_description = '''
A simple Python package for using Twitter search functi... | Increase version number to 0.1.1 (breaking API change)
#!/usr/bin/env python
import os
import sys
if sys.version < '2.7':
print 'Python >= 2.7 required'
sys.exit(1)
from setuptools import setup
long_description = '''
A simple Python package for using Twitter search functionality
that is only available throu... |
c2792efbb7c3b74c18ffede21b53adc42d887423 | social_website_django_angular/social_website_django_angular/urls.py | social_website_django_angular/social_website_django_angular/urls.py | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home,... | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home,... | Add login endpoint to URLs | Add login endpoint to URLs
| Python | mit | tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular | <REPLACE_OLD> AccountViewSet
router <REPLACE_NEW> AccountViewSet, LoginView
router <REPLACE_END> <INSERT> url(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
<INSERT_END> <|endoftext|> """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more informatio... | Add login endpoint to URLs
"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatte... |
863678a76664879971d50d41d52fba5c35f67913 | RemoveDirectories.py | RemoveDirectories.py | # -*- coding:utf-8 -*-
""" 這個程式能夠刪除所有在同目錄下的指定資料夾名稱(含子資料夾) """
import os
import shutil
FOLDER_NAME = 'PaxHeaders.20420'
def convert_all_files(path):
for dirPath, dirNames, fileNames in os.walk(path):
for dirName in dirNames:
if dirName == FOLDER_NAME:
shutil.rmtree(os.path.join... | Copy from my project remove-all-sub-directory-with-specific-name. | Copy from my project remove-all-sub-directory-with-specific-name.
| Python | mit | YiFanChen99/file-walker-for-windows | <INSERT> # -*- coding:utf-8 -*-
""" 這個程式能夠刪除所有在同目錄下的指定資料夾名稱(含子資料夾) """
import os
import shutil
FOLDER_NAME = 'PaxHeaders.20420'
def convert_all_files(path):
<INSERT_END> <INSERT> for dirPath, dirNames, fileNames in os.walk(path):
for dirName in dirNames:
if dirName == FOLDER_NAME:
... | Copy from my project remove-all-sub-directory-with-specific-name.
| |
08447fa344e21d6d704c6f195ad2b7405fa8f916 | saleor/order/test_order.py | saleor/order/test_order.py | from .models import Order
def test_total_property():
order = Order(total_net=20, total_tax=5)
assert order.total.gross == 25
assert order.total.tax == 5
assert order.total.net == 20
| Add test for total property | Add test for total property
| Python | bsd-3-clause | UITools/saleor,car3oon/saleor,itbabu/saleor,tfroehlich82/saleor,tfroehlich82/saleor,maferelo/saleor,laosunhust/saleor,jreigel/saleor,itbabu/saleor,UITools/saleor,car3oon/saleor,KenMutemi/saleor,maferelo/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,spartonia/saleor,KenMutemi/saleor,laosunhust/saleor,jreigel/saleor,ro... | <INSERT> from .models import Order
def test_total_property():
<INSERT_END> <INSERT> order = Order(total_net=20, total_tax=5)
assert order.total.gross == 25
assert order.total.tax == 5
assert order.total.net == 20
<INSERT_END> <|endoftext|> from .models import Order
def test_total_property():
ord... | Add test for total property
| |
6b5461955e196ee4a12b708fb6f9bef750d468ad | testcontainers/oracle.py | testcontainers/oracle.py | from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer():
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 from dual")... | from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer() as oracle:
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 f... | Add missing _configure to OracleDbContainer | Add missing _configure to OracleDbContainer
Additionally, fix Oracle example.
| Python | apache-2.0 | SergeyPirogov/testcontainers-python | <REPLACE_OLD> OracleDbContainer():
<REPLACE_NEW> OracleDbContainer() as oracle:
<REPLACE_END> <REPLACE_OLD> )
<REPLACE_NEW> )
def _configure(self):
pass
<REPLACE_END> <|endoftext|> from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database co... | Add missing _configure to OracleDbContainer
Additionally, fix Oracle example.
from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer():
e = sqlalchemy.create_engine(o... |
639eb2da0e239d362b3416e9137b9dcee8da1c87 | setup.py | setup.py | # -*- coding: utf8 -*-
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
def _read_long_description():
try:
import pypandoc
return pypandoc.convert('README.md', 'rst')
except ImportError:
return None
setup(
name="django... | # -*- coding: utf8 -*-
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
def _read_long_description():
try:
import pypandoc
return pypandoc.convert('README.md', 'rst', format='markdown')
except Exception:
return None
setup(... | Fix long-description reader, make it fail silently | Fix long-description reader, make it fail silently
| Python | mit | frecar/django-basis | <REPLACE_OLD> 'rst')
<REPLACE_NEW> 'rst', format='markdown')
<REPLACE_END> <REPLACE_OLD> ImportError:
<REPLACE_NEW> Exception:
<REPLACE_END> <|endoftext|> # -*- coding: utf8 -*-
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
def _read_long_descriptio... | Fix long-description reader, make it fail silently
# -*- coding: utf8 -*-
import os
from setuptools import setup, find_packages
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
def _read_long_description():
try:
import pypandoc
return pypandoc.convert('README.md', 'rst')
except Import... |
fe3f7ae8eb9390a4fe3f59e6244d4bbd6af7a9cd | mojo/services/html_viewer/view_url.py | mojo/services/html_viewer/view_url.py | #!/usr/bin/env python
# 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.
import argparse
import os
import subprocess
import sys
root_path = os.path.realpath(
os.path.join(
os.path.dirname(
... | Add script to view URL in HTMLViewer | Add script to view URL in HTMLViewer
This script takes advantage of the fact that Mojo binaries are published in the
cloud to add functionality for viewing a URL in HTMLViewer embedded in the
kiosk window manager.
Review URL: https://codereview.chromium.org/982523004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e... | Python | bsd-3-clause | TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,Just-D/chro... | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
# 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.
import argparse
import os
import subprocess
import sys
root_path = os.path.realpath(
os.path.join(
... | Add script to view URL in HTMLViewer
This script takes advantage of the fact that Mojo binaries are published in the
cloud to add functionality for viewing a URL in HTMLViewer embedded in the
kiosk window manager.
Review URL: https://codereview.chromium.org/982523004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e... | |
3d38af257f55a0252cb41408a404faa66b30d512 | pyconde/speakers/models.py | pyconde/speakers/models.py | from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Speaker(models.Model):
"""
The speaker model acts as user-abstraction for various session and proposal
related objects.
"""
user = models.OneToOneField(User, related_name='sp... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
class Speaker(models.Model):
"""
... | Create a speaker profile for each user that is registered. | Create a speaker profile for each user that is registered.
| Python | bsd-3-clause | pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep,EuroPython/djep,pysv/djep | <REPLACE_OLD> from django.db <REPLACE_NEW> # -*- coding: utf-8 -*-
from __future__ <REPLACE_END> <REPLACE_OLD> models
from <REPLACE_NEW> unicode_literals
from <REPLACE_END> <REPLACE_OLD> reverse
class <REPLACE_NEW> reverse
from django.db import models
from django.db.models.signals import post_save
from django.dispat... | Create a speaker profile for each user that is registered.
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Speaker(models.Model):
"""
The speaker model acts as user-abstraction for various session and proposal
related objects.
... |
d5b744d358e2e2bd3e6f85e0fbae487e2ee64c64 | bot/logger/logger.py | bot/logger/logger.py | import time
from bot.action.util.textformat import FormattedText
from bot.logger.message_sender import MessageSender
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
def log(self, tag, text):
text = self._get_text_to_s... | import time
from bot.action.util.textformat import FormattedText
from bot.logger.message_sender import MessageSender
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
TEXT_SEPARATOR = " | "
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
def log(self, tag, *texts):
t... | Improve Logger to support variable text params | Improve Logger to support variable text params
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | <REPLACE_OLD> {text}"
class <REPLACE_NEW> {text}"
TEXT_SEPARATOR = " | "
class <REPLACE_END> <REPLACE_OLD> text):
<REPLACE_NEW> *texts):
<REPLACE_END> <REPLACE_OLD> text)
<REPLACE_NEW> *texts)
<REPLACE_END> <REPLACE_OLD> text):
<REPLACE_NEW> *texts):
<REPLACE_END> <REPLACE_OLD> text: <REPLACE_NEW> *texts: <RE... | Improve Logger to support variable text params
import time
from bot.action.util.textformat import FormattedText
from bot.logger.message_sender import MessageSender
LOG_ENTRY_FORMAT = "{time} [{tag}] {text}"
class Logger:
def __init__(self, sender: MessageSender):
self.sender = sender
def log(self... |
0751ee8ea1153ca1227fafcfbca1dc00fc148c4b | qual/calendar.py | qual/calendar.py | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __eq__(self, other):
return self.calendar... | Move from_date() into an abstract base class. | Move from_date() into an abstract base class.
| Python | apache-2.0 | jwg4/qual,jwg4/calexicon | <REPLACE_OLD> ProlepticGregorianCalendar(object):
<REPLACE_NEW> Calendar(object):
def from_date(self, date):
return DateWithCalendar(self.__class__, date)
class ProlepticGregorianCalendar(Calendar):
<REPLACE_END> <REPLACE_OLD> self.from_date(d)
def from_date(self, date):
return DateWithCalen... | Move from_date() into an abstract base class.
from datetime import date, timedelta
class DateWithCalendar(object):
def __init__(self, calendar_class, date):
self.calendar = calendar_class
self.date = date
def convert_to(self, calendar):
return calendar.from_date(self.date)
def __... |
f04b85d6536cdfcf3d51e237bde7c2e63a5c2946 | server/server.py | server/server.py | import SimpleHTTPServer
import SocketServer
class KcaaHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_HEAD(self):
# Note: HTTP request handlers are not new-style classes.
# super() cannot be used.
SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD(self)
def do_GE... | import SimpleHTTPServer
import SocketServer
class KcaaHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
CLIENT_PREFIX = '/client/'
def do_HEAD(self):
# Note: HTTP request handlers are not new-style classes.
# super() cannot be used.
if self.rewrite_to_client_path():
... | Handle only /client requests to file serving. | Handle only /client requests to file serving.
| Python | apache-2.0 | kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa | <INSERT> CLIENT_PREFIX = '/client/'
<INSERT_END> <INSERT> if self.rewrite_to_client_path():
<INSERT_END> <REPLACE_OLD> SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def <REPLACE_NEW> if self.rewrite_to_client_path():
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def... | Handle only /client requests to file serving.
import SimpleHTTPServer
import SocketServer
class KcaaHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_HEAD(self):
# Note: HTTP request handlers are not new-style classes.
# super() cannot be used.
SimpleHTTPServer.Simple... |
431ca4f2d44656ef9f97be50718712c6f3a0fa9b | qtawesome/tests/test_qtawesome.py | qtawesome/tests/test_qtawesome.py | r"""
Tests for QtAwesome.
"""
# Standard library imports
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
... | r"""
Tests for QtAwesome.
"""
# Standard library imports
import subprocess
import collections
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import qtawesome '
... | Make the test more comprehensive. | Make the test more comprehensive.
| Python | mit | spyder-ide/qtawesome | <REPLACE_OLD> subprocess
# <REPLACE_NEW> subprocess
import collections
# <REPLACE_END> <REPLACE_OLD> prefixes = list(resource.fontname.keys())
assert prefixes
<REPLACE_NEW> # Check that the fonts were loaded successfully.
<REPLACE_END> <REPLACE_OLD> set(resource.fontname.values())
<REPLACE_NEW> resource.fontn... | Make the test more comprehensive.
r"""
Tests for QtAwesome.
"""
# Standard library imports
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
def test_segfault_import():
output_number = subprocess.call('python -c "import q... |
8e2a42369228f3d19b046a610c93de4bec06d5bf | avocado/core/structures.py | avocado/core/structures.py | try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
class ChoicesDict(OrderedDict):
"OrdereDict that yields the key and value on iteration."
def __iter__(self):
iterator = super(ChoicesDict, self).__iter__()
for key in iterator:
... | try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
REPR_OUTPUT_SIZE = 20
class ChoicesDict(OrderedDict):
"OrdereDict that yields the key and value on iteration."
def __iter__(self):
iterator = super(ChoicesDict, self).__iter__()
for key ... | Add __repr__ to ChoicesDict structure | Add __repr__ to ChoicesDict structure | Python | bsd-2-clause | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado | <REPLACE_OLD> OrderedDict
class <REPLACE_NEW> OrderedDict
REPR_OUTPUT_SIZE = 20
class <REPLACE_END> <REPLACE_OLD> self[key]
<REPLACE_NEW> self[key]
def __repr__(self):
data = list(self[:REPR_OUTPUT_SIZE + 1])
if len(data) > REPR_OUTPUT_SIZE:
data[-1] = '...(remaining elements tr... | Add __repr__ to ChoicesDict structure
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
class ChoicesDict(OrderedDict):
"OrdereDict that yields the key and value on iteration."
def __iter__(self):
iterator = super(ChoicesDict, self).__iter__()
... |
3e147eba049c51c3b1c7c7278f48e40ef5b1263f | paperpass.py | paperpass.py | import json
class PaperPass:
# class var
outline = {}
def __init__(self, outline):
self.outline = outline
def outputjson(self, filename):
fp = open(filename, 'w')
json.dump(self.outline, fp)
if __name__ == "__main__":
import sys
a = PaperPass({3:2,2:1})
a.outpu... | Create PaperPass class. It contains outputjson method. | Create PaperPass class. It contains outputjson method.
| Python | mit | lucaskotw/paperpass | <INSERT> import json
class PaperPass:
<INSERT_END> <INSERT> # class var
outline = {}
def __init__(self, outline):
self.outline = outline
def outputjson(self, filename):
fp = open(filename, 'w')
json.dump(self.outline, fp)
if __name__ == "__main__":
import sys
a = Pa... | Create PaperPass class. It contains outputjson method.
| |
5368e0ad7be4cdf7df2da392fdaabb89c3a4ad55 | test_settings.py | test_settings.py | SECRET_KEY = "lorem ipsum"
INSTALLED_APPS = (
'tango_shared',
)
| SECRET_KEY = "lorem ipsum"
INSTALLED_APPS = (
'tango_shared',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SITE_ID = 1
| Add missing test settings (in-memory sqlite3 db + SITE_ID) | Add missing test settings (in-memory sqlite3 db + SITE_ID)
| Python | mit | tBaxter/tango-shared-core,tBaxter/tango-shared-core,tBaxter/tango-shared-core | <REPLACE_OLD> 'tango_shared',
)
<REPLACE_NEW> 'tango_shared',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
SITE_ID = 1
<REPLACE_END> <|endoftext|> SECRET_KEY = "lorem ipsum"
INSTALLED_APPS = (
'tango_shared',
)
DATABASES = {
'default'... | Add missing test settings (in-memory sqlite3 db + SITE_ID)
SECRET_KEY = "lorem ipsum"
INSTALLED_APPS = (
'tango_shared',
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.