Datasets:

commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
733404ba2eb7218bb4d253cd74fe88107ff75afc
test/test_live_openid_login.py
test/test_live_openid_login.py
import time import pytest from chatexchange.browser import SEChatBrowser, LoginError import live_testing if live_testing.enabled: def test_openid_login(): """ Tests login to the Stack Exchange OpenID provider. """ browser = SEChatBrowser() # avoid hitting the SE servers...
import time import pytest from chatexchange.browser import SEChatBrowser, LoginError import live_testing if live_testing.enabled: def test_openid_login_recognizes_failure(): """ Tests that failed SE OpenID logins raise errors. """ browser = SEChatBrowser() # avoid hitti...
Remove successful OpenID login live test. It's redundant with our message-related live tests.
Remove successful OpenID login live test. It's redundant with our message-related live tests.
Python
apache-2.0
ByteCommander/ChatExchange6,hichris1234/ChatExchange,Charcoal-SE/ChatExchange,hichris1234/ChatExchange,ByteCommander/ChatExchange6,Charcoal-SE/ChatExchange
import time import pytest from chatexchange.browser import SEChatBrowser, LoginError import live_testing if live_testing.enabled: - def test_openid_login(): - """ - Tests login to the Stack Exchange OpenID provider. - """ - browser = SEChatBrowser() - - ...
Remove successful OpenID login live test. It's redundant with our message-related live tests.
## Code Before: import time import pytest from chatexchange.browser import SEChatBrowser, LoginError import live_testing if live_testing.enabled: def test_openid_login(): """ Tests login to the Stack Exchange OpenID provider. """ browser = SEChatBrowser() # avoid hittin...
9c428fbfb69c93ef3da935d0d2ab098fbeb1c317
dsh.py
dsh.py
__author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes -------------------------------------------------------...
__author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes -------------------------------------------------------...
Revert "Testing NoOpDSH() when database commands are executed without a connection being opened."
Revert "Testing NoOpDSH() when database commands are executed without a connection being opened." This reverts commit 57dd36da6f558e9bd5c9b7c97e955600c2fa0b8e.
Python
mit
mcmontero/tinyAPI,mcmontero/tinyAPI
__author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ---------------------------...
Revert "Testing NoOpDSH() when database commands are executed without a connection being opened."
## Code Before: __author__ = 'Michael Montero <mcmontero@gmail.com>' # ----- Imports --------------------------------------------------------------- from tinyAPI.base.data_store.provider import DataStoreProvider import tinyAPI __all__ = [ 'dsh' ] # ----- Private Classes ---------------------------------------...
eced06f6f523fa6fd475987ae688b7ca2b6c3415
checks/system/__init__.py
checks/system/__init__.py
import sys class Platform(object): @staticmethod def is_darwin(name=None): name = name or sys.platform return 'darwin' in name @staticmethod def is_freebsd(name=None): name = name or sys.platform return name.startswith("freebsd") @staticmethod def is_linux(...
import sys class Platform(object): @staticmethod def is_darwin(name=None): name = name or sys.platform return 'darwin' in name @staticmethod def is_freebsd(name=None): name = name or sys.platform return name.startswith("freebsd") @staticmethod def is_linux(...
Add win32 to platform information
Add win32 to platform information
Python
bsd-3-clause
jraede/dd-agent,tebriel/dd-agent,JohnLZeller/dd-agent,a20012251/dd-agent,remh/dd-agent,tebriel/dd-agent,AntoCard/powerdns-recursor_check,tebriel/dd-agent,AniruddhaSAtre/dd-agent,urosgruber/dd-agent,polynomial/dd-agent,JohnLZeller/dd-agent,Mashape/dd-agent,JohnLZeller/dd-agent,eeroniemi/dd-agent,c960657/dd-agent,mderomp...
import sys class Platform(object): @staticmethod def is_darwin(name=None): name = name or sys.platform return 'darwin' in name @staticmethod def is_freebsd(name=None): name = name or sys.platform return name.startswith("freebsd") ...
Add win32 to platform information
## Code Before: import sys class Platform(object): @staticmethod def is_darwin(name=None): name = name or sys.platform return 'darwin' in name @staticmethod def is_freebsd(name=None): name = name or sys.platform return name.startswith("freebsd") @staticmethod ...
b974bbcc7e243fca7c3dc63fbbaf530fe9b69e50
runtests.py
runtests.py
import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", } ...
import os import sys try: sys.path.append('demoproject') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings") from django.conf import settings from django.core.management import call_command settings.DATABASES['default']['NAME'] = ':memory:' settings.INSTALLED_APPS.append('...
Load DB migrations before testing and use verbose=2 and failfast
Load DB migrations before testing and use verbose=2 and failfast Note that we use `manage.py test` instead of `manage.py migrate` and manually running the tests. This lets Django take care of applying migrations before running tests. This works around https://code.djangoproject.com/ticket/22487 which causes a test fai...
Python
bsd-2-clause
pgollakota/django-chartit,pgollakota/django-chartit,pgollakota/django-chartit
+ import os import sys try: + sys.path.append('demoproject') + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings") + from django.conf import settings - from django.test.utils import get_runner + from django.core.management import call_command + settings.DATABASES...
Load DB migrations before testing and use verbose=2 and failfast
## Code Before: import sys try: from django.conf import settings from django.test.utils import get_runner settings.configure( DEBUG=True, USE_TZ=True, DATABASES={ "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", ...
75289980c658e081fec2d7e34651837c4629d4b7
settings.py
settings.py
# Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = 'your-app-id'
# Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = 'your-web-client-id'
Fix the placeholder for better understanding
fix: Fix the placeholder for better understanding
Python
mit
iraquitan/udacity-fsnd-p4-conference-app,iraquitan/udacity-fsnd-p4-conference-app,iraquitan/udacity-fsnd-p4-conference-app
# Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. - WEB_CLIENT_ID = 'your-app-id' + WEB_CLIENT_ID = 'your-web-client-id'
Fix the placeholder for better understanding
## Code Before: # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB_CLIENT_ID = 'your-app-id' ## Instruction: Fix the placeholder for better understanding ## Code After: # Replace the following lines with client IDs obtained from the APIs # Console or Cloud Console. WEB...
68b52fedf5b22891a4fc9cf121417ced38d0ea00
rolepermissions/utils.py
rolepermissions/utils.py
from __future__ import unicode_literals import re import collections def user_is_authenticated(user): if isinstance(user.is_authenticated, collections.Callable): authenticated = user.is_authenticated() else: authenticated = user.is_authenticated return authenticated def camelToSnake(s)...
from __future__ import unicode_literals import re try: from collections.abc import Callable except ImportError: from collections import Callable def user_is_authenticated(user): if isinstance(user.is_authenticated, Callable): authenticated = user.is_authenticated() else: authenticated...
Fix import of Callable for Python 3.9
Fix import of Callable for Python 3.9 Python 3.3 moved Callable to collections.abc and Python 3.9 removes Callable from collections module
Python
mit
vintasoftware/django-role-permissions
from __future__ import unicode_literals import re - import collections + try: + from collections.abc import Callable + except ImportError: + from collections import Callable def user_is_authenticated(user): - if isinstance(user.is_authenticated, collections.Callable): + if isinstance(user...
Fix import of Callable for Python 3.9
## Code Before: from __future__ import unicode_literals import re import collections def user_is_authenticated(user): if isinstance(user.is_authenticated, collections.Callable): authenticated = user.is_authenticated() else: authenticated = user.is_authenticated return authenticated def...
7f7fd4e7547af3a6d7e3cd4da025c2b0ab24508b
widgy/contrib/widgy_mezzanine/migrations/0001_initial.py
widgy/contrib/widgy_mezzanine/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations import widgy.db.fields import django.db.models.deletion import widgy.contrib.widgy_mezzanine.models class Migration(migrations.Migration): dependencies = [ ('pages', '__first__'), ('review_queue', '0001_initial'), ...
from __future__ import unicode_literals from django.db import models, migrations import widgy.db.fields import django.db.models.deletion import widgy.contrib.widgy_mezzanine.models class Migration(migrations.Migration): dependencies = [ ('pages', '__first__'), ('widgy', '0001_initial'), ] ...
Remove dependency for ReviewedVersionTracker in migrations
Remove dependency for ReviewedVersionTracker in migrations The base widgy migrations had references to ReviewedVersionTracker, which is not part of the base widgy install. This commit changes the dependency to VersionTracker instead, which is part of the base widgy install.
Python
apache-2.0
j00bar/django-widgy,j00bar/django-widgy,j00bar/django-widgy
from __future__ import unicode_literals from django.db import models, migrations import widgy.db.fields import django.db.models.deletion import widgy.contrib.widgy_mezzanine.models class Migration(migrations.Migration): dependencies = [ ('pages', '__first__'), - ('review_...
Remove dependency for ReviewedVersionTracker in migrations
## Code Before: from __future__ import unicode_literals from django.db import models, migrations import widgy.db.fields import django.db.models.deletion import widgy.contrib.widgy_mezzanine.models class Migration(migrations.Migration): dependencies = [ ('pages', '__first__'), ('review_queue', '0...
16369ed6a11aaa39e94479b06ed78eb75f5b33e1
src/args.py
src/args.py
from argparse import ArgumentParser from glob import glob from os import path def is_valid_file(f, parser): if path.isfile(f): return f else: return parser.optparser.error("%s does not exist!" % f) def parse_args(): parser = ArgumentParser() parser.add_argument("--non-headless", acti...
from glob import glob from os import path import argparse def is_valid_file(f, parser): if path.isfile(f): return f raise argparse.ArgumentTypeError("%s does not exist!" % f) def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--non-headless", action="store_true", ...
Fix --crx arg error reporting.
Fix --crx arg error reporting.
Python
mpl-2.0
ghostwords/chameleon-crawler,ghostwords/chameleon-crawler,ghostwords/chameleon-crawler
- from argparse import ArgumentParser from glob import glob from os import path + + import argparse def is_valid_file(f, parser): if path.isfile(f): return f + raise argparse.ArgumentTypeError("%s does not exist!" % f) - else: - return parser.optparser.error("%s does not exi...
Fix --crx arg error reporting.
## Code Before: from argparse import ArgumentParser from glob import glob from os import path def is_valid_file(f, parser): if path.isfile(f): return f else: return parser.optparser.error("%s does not exist!" % f) def parse_args(): parser = ArgumentParser() parser.add_argument("--non...
a7be90536618ac52c91f599bb167e05f831cddfb
mangopaysdk/entities/transaction.py
mangopaysdk/entities/transaction.py
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.types.money import Money class Transaction (EntityBase): """Transaction entity. Base class for: PayIn, PayOut, Transfer. """ def __init__(self, id = None): self.AuthorId = None self.CreditedUserId = None #...
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.types.money import Money class Transaction (EntityBase): """Transaction entity. Base class for: PayIn, PayOut, Transfer. """ def __init__(self, id = None): self.AuthorId = None self.CreditedUserId = None #...
Add possibilty to get ResultMessage
Add possibilty to get ResultMessage
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.types.money import Money class Transaction (EntityBase): """Transaction entity. Base class for: PayIn, PayOut, Transfer. """ def __init__(self, id = None): self.AuthorId = None self.Credite...
Add possibilty to get ResultMessage
## Code Before: from mangopaysdk.entities.entitybase import EntityBase from mangopaysdk.types.money import Money class Transaction (EntityBase): """Transaction entity. Base class for: PayIn, PayOut, Transfer. """ def __init__(self, id = None): self.AuthorId = None self.CreditedUserId ...
3cacced39d9cb8bd5d6a2b3db8aa4b5aa1b37f58
jaraco/util/meta.py
jaraco/util/meta.py
from __future__ import unicode_literals class LeafClassesMeta(type): """ A metaclass for classes that keeps track of all of them that aren't base classes. """ _leaf_classes = set() def __init__(cls, name, bases, attrs): if not hasattr(cls, '_leaf_classes'): cls._leaf_classes = set() leaf_classes = geta...
from __future__ import unicode_literals class LeafClassesMeta(type): """ A metaclass for classes that keeps track of all of them that aren't base classes. """ _leaf_classes = set() def __init__(cls, name, bases, attrs): if not hasattr(cls, '_leaf_classes'): cls._leaf_classes = set() leaf_classes = geta...
Allow attribute to be customized in TagRegistered
Allow attribute to be customized in TagRegistered
Python
mit
jaraco/jaraco.classes
from __future__ import unicode_literals class LeafClassesMeta(type): """ A metaclass for classes that keeps track of all of them that aren't base classes. """ _leaf_classes = set() def __init__(cls, name, bases, attrs): if not hasattr(cls, '_leaf_classes'): cls._leaf_classes =...
Allow attribute to be customized in TagRegistered
## Code Before: from __future__ import unicode_literals class LeafClassesMeta(type): """ A metaclass for classes that keeps track of all of them that aren't base classes. """ _leaf_classes = set() def __init__(cls, name, bases, attrs): if not hasattr(cls, '_leaf_classes'): cls._leaf_classes = set() lea...
7b6838ea292e011f96f5212992d00c1009e1f6b2
examples/gitter_example.py
examples/gitter_example.py
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from settings import GITTER # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) chatbot = ChatBot( 'GitterBot', gitter_room=GITTER['ROOM'], gitter_api_t...
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from settings import GITTER # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) ''' To use this example, create a new file called settings.py. In settings.py define...
Add better instructions to the Gitter example
Add better instructions to the Gitter example
Python
bsd-3-clause
gunthercox/ChatterBot,vkosuri/ChatterBot
from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from settings import GITTER # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) + + + ''' + To use this example, create a new file called settings.p...
Add better instructions to the Gitter example
## Code Before: from chatterbot import ChatBot from chatterbot.trainers import ChatterBotCorpusTrainer from settings import GITTER # Uncomment the following lines to enable verbose logging # import logging # logging.basicConfig(level=logging.INFO) chatbot = ChatBot( 'GitterBot', gitter_room=GITTER['ROOM'], ...
260a5601a9b2990374d2f97d92898236e0b9342e
tests/profiling_test_script.py
tests/profiling_test_script.py
from __future__ import ( print_function, division, unicode_literals, absolute_import) import subdir.profiling_test_script2 as script2 @profile def fact(n): result = 1 for i in xrange(2, n + 1): result *= i return result @profile def sum_(n): result = 0 for i in xrange(1, n + 1): ...
from __future__ import ( print_function, division, unicode_literals, absolute_import) import subdir.profiling_test_script2 as script2 @profile def fact(n): result = 1 for i in xrange(2, n // 4): result *= i result = 1 for i in xrange(2, n // 16): result *= i result = 1 f...
Add diversity to test script
Add diversity to test script
Python
mit
jitseniesen/spyder-memory-profiler,jitseniesen/spyder-memory-profiler,Nodd/spyder_line_profiler,spyder-ide/spyder.line_profiler,spyder-ide/spyder.memory_profiler,spyder-ide/spyder.line-profiler,Nodd/spyder.line_profiler
from __future__ import ( print_function, division, unicode_literals, absolute_import) import subdir.profiling_test_script2 as script2 @profile def fact(n): + result = 1 + for i in xrange(2, n // 4): + result *= i + result = 1 + for i in xrange(2, n // 16): + ...
Add diversity to test script
## Code Before: from __future__ import ( print_function, division, unicode_literals, absolute_import) import subdir.profiling_test_script2 as script2 @profile def fact(n): result = 1 for i in xrange(2, n + 1): result *= i return result @profile def sum_(n): result = 0 for i in xr...
97a67e022d094743e806896386bdbe317cb56fb6
gitcloner.py
gitcloner.py
import sys from gitaccount import GitAccount def main(): if len(sys.argv) < 2: print("""Usage: gitcloner.py [OPTION] [NAME] OPTIONS: -u - for user repositories -o - for organization repositories NAME: Username or Organization Name """) sys.exit(1) args =...
import sys import argparse from gitaccount import GitAccount def main(): parser = argparse.ArgumentParser( prog='gitcloner', description='Clone all the repositories from a github user/org\naccount to the current directory') group = parser.add_mutually_exclusive_group() group.add...
Use argparse instead of sys.argv
Use argparse instead of sys.argv
Python
mit
shakib609/gitcloner
import sys + import argparse from gitaccount import GitAccount def main(): - if len(sys.argv) < 2: - print("""Usage: - gitcloner.py [OPTION] [NAME] + parser = argparse.ArgumentParser( + prog='gitcloner', + description='Clone all the repositories from a github us...
Use argparse instead of sys.argv
## Code Before: import sys from gitaccount import GitAccount def main(): if len(sys.argv) < 2: print("""Usage: gitcloner.py [OPTION] [NAME] OPTIONS: -u - for user repositories -o - for organization repositories NAME: Username or Organization Name """) sys.exi...
d42b9da06d5cde89a6116d711fc6ae216256cabc
shell/view/home/IconLayout.py
shell/view/home/IconLayout.py
import random class IconLayout: def __init__(self, width, height): self._icons = [] self._width = width self._height = height def add_icon(self, icon): self._icons.append(icon) self._layout_icon(icon) def remove_icon(self, icon): self._icons.remove(icon) def _is_valid_position(self, icon, x, y): i...
import random class IconLayout: def __init__(self, width, height): self._icons = [] self._width = width self._height = height def add_icon(self, icon): self._icons.append(icon) self._layout_icon(icon) def remove_icon(self, icon): self._icons.remove(icon) def _is_valid_position(self, icon, x, y): i...
Use get/set_property rather than direct accessors
Use get/set_property rather than direct accessors
Python
lgpl-2.1
Daksh/sugar-toolkit-gtk3,manuq/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,quozl/sugar-toolkit-gtk3,tchx84/sugar-toolkit-gtk3,i5o/sugar-toolkit-gtk3,puneetgkaur/backup_sugar_sugartoolkit,quozl/sugar-toolkit-gtk3,godiard/sugar-toolkit-gtk3,tchx84/debian-pkg-sugar-toolkit,tchx84/debian-pkg-sugar-toolkit,ceibal-tatu/suga...
import random class IconLayout: def __init__(self, width, height): self._icons = [] self._width = width self._height = height def add_icon(self, icon): self._icons.append(icon) self._layout_icon(icon) def remove_icon(self, icon): self._icons.remove(icon) def _is_valid...
Use get/set_property rather than direct accessors
## Code Before: import random class IconLayout: def __init__(self, width, height): self._icons = [] self._width = width self._height = height def add_icon(self, icon): self._icons.append(icon) self._layout_icon(icon) def remove_icon(self, icon): self._icons.remove(icon) def _is_valid_position(self, ...
5c61d7f125078cb6b3bd0c5700ae9219baab0078
webapp/tests/test_dashboard.py
webapp/tests/test_dashboard.py
from django.core.urlresolvers import reverse from django.test import TestCase class DashboardTest(TestCase): def test_dashboard(self): url = reverse('graphite.dashboard.views.dashboard') response = self.client.get(url) self.assertEqual(response.status_code, 200)
from django.core.urlresolvers import reverse from django.test import TestCase class DashboardTest(TestCase): def test_dashboard(self): url = reverse('dashboard') response = self.client.get(url) self.assertEqual(response.status_code, 200)
Update reverse call to use named URL
Update reverse call to use named URL
Python
apache-2.0
redice/graphite-web,dbn/graphite-web,Skyscanner/graphite-web,penpen/graphite-web,lyft/graphite-web,esnet/graphite-web,bpaquet/graphite-web,atnak/graphite-web,section-io/graphite-web,kkdk5535/graphite-web,cosm0s/graphite-web,cgvarela/graphite-web,gwaldo/graphite-web,redice/graphite-web,edwardmlyte/graphite-web,atnak/gra...
from django.core.urlresolvers import reverse from django.test import TestCase class DashboardTest(TestCase): def test_dashboard(self): - url = reverse('graphite.dashboard.views.dashboard') + url = reverse('dashboard') response = self.client.get(url) self.assertEqual...
Update reverse call to use named URL
## Code Before: from django.core.urlresolvers import reverse from django.test import TestCase class DashboardTest(TestCase): def test_dashboard(self): url = reverse('graphite.dashboard.views.dashboard') response = self.client.get(url) self.assertEqual(response.status_code, 200) ## Instruc...
4124297475fb7d77bf492e721a74fcfa02547a14
benchmark/bench_logger_level_low.py
benchmark/bench_logger_level_low.py
"""Benchmarks too low logger levels""" from logbook import Logger, ERROR log = Logger('Test logger') log.level = ERROR def run(): for x in xrange(500): log.warning('this is not handled')
"""Benchmarks too low logger levels""" from logbook import Logger, StreamHandler, ERROR from cStringIO import StringIO log = Logger('Test logger') log.level = ERROR def run(): out = StringIO() with StreamHandler(out): for x in xrange(500): log.warning('this is not handled')
Create a stream handler even though it's not used to have the same overhead on both logbook and logging
Create a stream handler even though it's not used to have the same overhead on both logbook and logging
Python
bsd-3-clause
DasIch/logbook,maykinmedia/logbook,alonho/logbook,fayazkhan/logbook,maykinmedia/logbook,Rafiot/logbook,dvarrazzo/logbook,mbr/logbook,mitsuhiko/logbook,dvarrazzo/logbook,RazerM/logbook,FintanH/logbook,omergertel/logbook,dommert/logbook,DasIch/logbook,alex/logbook,alonho/logbook,pombredanne/logbook,alonho/logbook,alex/lo...
"""Benchmarks too low logger levels""" - from logbook import Logger, ERROR + from logbook import Logger, StreamHandler, ERROR + from cStringIO import StringIO log = Logger('Test logger') log.level = ERROR def run(): + out = StringIO() + with StreamHandler(out): - for x in xrange(500): + ...
Create a stream handler even though it's not used to have the same overhead on both logbook and logging
## Code Before: """Benchmarks too low logger levels""" from logbook import Logger, ERROR log = Logger('Test logger') log.level = ERROR def run(): for x in xrange(500): log.warning('this is not handled') ## Instruction: Create a stream handler even though it's not used to have the same overhead on both ...
b71db5eb72fd5529be060d5f90ad744f0ea0870e
library.py
library.py
class Library: """This class represents a simaris target and is initialized with data in JSON format """ def __init__(self, data): self.target = data['CurrentTarget']['EnemyType'] self.scans = data['CurrentTarget']['PersonalScansRequired'] self.progress ...
class Library: """This class represents a simaris target and is initialized with data in JSON format """ def __init__(self, data): if 'CurrentTarget' in data: self.target = data['CurrentTarget']['EnemyType'] self.scans = data['CurrentTarget']['Persona...
Add is_active() method to the Library class
Add is_active() method to the Library class
Python
mit
pabletos/Hubot-Warframe,pabletos/Hubot-Warframe
class Library: """This class represents a simaris target and is initialized with data in JSON format """ def __init__(self, data): + if 'CurrentTarget' in data: - self.target = data['CurrentTarget']['EnemyType'] + self.target = data['CurrentT...
Add is_active() method to the Library class
## Code Before: class Library: """This class represents a simaris target and is initialized with data in JSON format """ def __init__(self, data): self.target = data['CurrentTarget']['EnemyType'] self.scans = data['CurrentTarget']['PersonalScansRequired'] sel...
5c6f277caf3496da5f10b0150abb2c3b856e6584
nagare/services/prg.py
nagare/services/prg.py
from nagare.services import plugin class PRGService(plugin.Plugin): LOAD_PRIORITY = 120 @staticmethod def handle_request(chain, request, response, session_id, previous_state_id, **params): if (request.method == 'POST') and not request.is_xhr: response = request.create_redirect_respon...
from nagare.services import plugin class PRGService(plugin.Plugin): LOAD_PRIORITY = 120 @staticmethod def handle_request(chain, request, response, session_id, state_id, **params): if (request.method == 'POST') and not request.is_xhr: response = request.create_redirect_response( ...
Store in the current state, not the previous one
Store in the current state, not the previous one
Python
bsd-3-clause
nagareproject/core,nagareproject/core
from nagare.services import plugin class PRGService(plugin.Plugin): LOAD_PRIORITY = 120 @staticmethod - def handle_request(chain, request, response, session_id, previous_state_id, **params): + def handle_request(chain, request, response, session_id, state_id, **params): if ...
Store in the current state, not the previous one
## Code Before: from nagare.services import plugin class PRGService(plugin.Plugin): LOAD_PRIORITY = 120 @staticmethod def handle_request(chain, request, response, session_id, previous_state_id, **params): if (request.method == 'POST') and not request.is_xhr: response = request.create...
313aee17c8e2e1c86b96b40017ac4618c66df463
__init__.py
__init__.py
ENTITIES_INDEX = ['men', 'foy'] # Some variables needed by the test case plugins CURRENCY = u"DT" # Some variables needed by the test case graph widget # REVENUES_CATEGORIES XAXIS_PROPERTIES = { 'sali': { 'name' : 'sal', 'typ_tot' : {'salsuperbrut' : 'Sal...
ENTITIES_INDEX = ['men', 'foy'] # Some variables needed by the test case plugins CURRENCY = u"DT" # Some variables needed by the test case graph widget REVENUES_CATEGORIES = {'imposable' : ['sal',]} XAXIS_PROPERTIES = { 'sali': { 'name' : 'sal', 'typ_to...
Generalize graph and some new example scripts
Generalize graph and some new example scripts
Python
agpl-3.0
openfisca/openfisca-tunisia,openfisca/openfisca-tunisia
ENTITIES_INDEX = ['men', 'foy'] # Some variables needed by the test case plugins CURRENCY = u"DT" # Some variables needed by the test case graph widget - # REVENUES_CATEGORIES + + + REVENUES_CATEGORIES = {'imposable' : ['sal',]} + XAXIS_PROPERTIES = { 'sali': { ...
Generalize graph and some new example scripts
## Code Before: ENTITIES_INDEX = ['men', 'foy'] # Some variables needed by the test case plugins CURRENCY = u"DT" # Some variables needed by the test case graph widget # REVENUES_CATEGORIES XAXIS_PROPERTIES = { 'sali': { 'name' : 'sal', 'typ_tot' : {'sals...
09fc3d53b2814f940bcaf7d6136ed2ce0595fb2f
hyperion/importers/tests/test_sph.py
hyperion/importers/tests/test_sph.py
import os import h5py import numpy as np from ..sph import construct_octree DATA = os.path.join(os.path.dirname(__file__), 'data') def test_construct_octree(): np.random.seed(0) N = 5000 px = np.random.uniform(-10., 10., N) py = np.random.uniform(-10., 10., N) pz = np.random.uniform(-10., 10....
import os import h5py import numpy as np from numpy.testing import assert_allclose from ..sph import construct_octree DATA = os.path.join(os.path.dirname(__file__), 'data') def test_construct_octree(): np.random.seed(0) N = 5000 px = np.random.uniform(-10., 10., N) py = np.random.uniform(-10., 10...
Use assert_allclose for comparison of octree densities
Use assert_allclose for comparison of octree densities
Python
bsd-2-clause
hyperion-rt/hyperion,bluescarni/hyperion,hyperion-rt/hyperion,hyperion-rt/hyperion,bluescarni/hyperion
import os import h5py import numpy as np + from numpy.testing import assert_allclose from ..sph import construct_octree DATA = os.path.join(os.path.dirname(__file__), 'data') def test_construct_octree(): np.random.seed(0) N = 5000 px = np.random.uniform(-10., 10., N) ...
Use assert_allclose for comparison of octree densities
## Code Before: import os import h5py import numpy as np from ..sph import construct_octree DATA = os.path.join(os.path.dirname(__file__), 'data') def test_construct_octree(): np.random.seed(0) N = 5000 px = np.random.uniform(-10., 10., N) py = np.random.uniform(-10., 10., N) pz = np.random.u...
fd96170fd15ccbe0b42463fe8d4ac78f511d10c7
example/testtags/admin.py
example/testtags/admin.py
from django.contrib import admin from models import TestName class TestNameAdmin(admin.ModelAdmin): model = TestName alphabet_filter = 'sorted_name' admin.site.register(TestName, TestNameAdmin)
from django.contrib import admin from models import TestName class TestNameAdmin(admin.ModelAdmin): model = TestName alphabet_filter = 'sorted_name' ## Testing a custom Default Alphabet #DEFAULT_ALPHABET = 'ABC' ## Testing a blank alphabet-- only shows the characters in the database #...
Put in some testing code to test the new overrides
Put in some testing code to test the new overrides
Python
apache-2.0
bltravis/django-alphabetfilter,affan2/django-alphabetfilter,affan2/django-alphabetfilter,affan2/django-alphabetfilter,bltravis/django-alphabetfilter,bltravis/django-alphabetfilter
from django.contrib import admin from models import TestName class TestNameAdmin(admin.ModelAdmin): model = TestName alphabet_filter = 'sorted_name' + + ## Testing a custom Default Alphabet + #DEFAULT_ALPHABET = 'ABC' + + ## Testing a blank alphabet-- only shows the characters...
Put in some testing code to test the new overrides
## Code Before: from django.contrib import admin from models import TestName class TestNameAdmin(admin.ModelAdmin): model = TestName alphabet_filter = 'sorted_name' admin.site.register(TestName, TestNameAdmin) ## Instruction: Put in some testing code to test the new overrides ## Code After: from django.contri...
731e48b1b81e9249fc8bdd0f826c6e009559fcc3
mempoke.py
mempoke.py
import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): ...
import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address, value): ...
Add mechanism for defining MCU control structures
Add mechanism for defining MCU control structures
Python
mit
fmfi-svt-deadlock/hw-testing,fmfi-svt-deadlock/hw-testing
import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(...
Add mechanism for defining MCU control structures
## Code Before: import gdb import struct class DeviceMemory: def __init__(self): self.inferior = gdb.selected_inferior() def __del__(self): del self.inferior def read(self, address): return struct.unpack('I', self.inferior.read_memory(address, 4))[0] def write(self, address,...
afa3cd7c6e4c82f94eef7edd4bc8db609943226c
api/urls.py
api/urls.py
from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from . import views urlpatterns = [ url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'), ]
from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from . import views urlpatterns = [ url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'), url(r'^signup/$', views.SignupView.as_vie...
Add URL for signup api endpoint
Add URL for signup api endpoint
Python
mit
p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles,p2pu/learning-circles
from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from . import views urlpatterns = [ url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'), + url(r'^signup/$', views...
Add URL for signup api endpoint
## Code Before: from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.auth.decorators import login_required from . import views urlpatterns = [ url(r'^learningcircles/$', views.LearningCircleListView.as_view(), name='api_learningcircles'), ] ## Instruction: Add URL f...
f59ac3cc752698ce1755d8953c8771dc978ae6b7
opendebates/urls.py
opendebates/urls.py
from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^healthcheck.html$', 'opendebates.views.health_check', name='health_check'), url(r'^(?P<prefix>[-\w]+)/', include('opendebates.prefixed_urls')), ]
from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = [ url(r'^$', RedirectView.as_view(url='https://opendebatecoalition.com', permanent=False)), url(r'^admin/', include(admin.site.urls)), url(r'^healthcheck.html$', 'ope...
Add a (temporary) redirect to opendebatecoalition.com from /
Add a (temporary) redirect to opendebatecoalition.com from / Temporary because permanent is really hard to take back, if you decide later that you wanted something else.
Python
apache-2.0
caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates,caktus/django-opendebates
from django.conf.urls import include, url from django.contrib import admin + from django.views.generic.base import RedirectView urlpatterns = [ + url(r'^$', RedirectView.as_view(url='https://opendebatecoalition.com', permanent=False)), url(r'^admin/', include(admin.site.urls)), url(r'^health...
Add a (temporary) redirect to opendebatecoalition.com from /
## Code Before: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^healthcheck.html$', 'opendebates.views.health_check', name='health_check'), url(r'^(?P<prefix>[-\w]+)/', include('opendebates.prefixed_urls')), ] ##...
aa0b61b44e631c3a12a16025e93d7e962de23c2f
fabix/system/crontab.py
fabix/system/crontab.py
import fabric.api as fab import cuisine def install(filename, user="root", append=False): """ Installs crontab from a given cronfile """ new_crontab = fab.run("mktemp fabixcron.XXXX") cuisine.file_upload(new_crontab, filename) if append is True: sorted_crontab = fab.run("mktemp fabixcr...
import fabric.api as fab import cuisine def install(filename, user="root", append=False): """ Installs crontab from a given cronfile """ new_crontab = fab.run("mktemp fabixcron.XXXX") cuisine.file_upload(new_crontab, filename) if append is True: # When user have no crontab, then cronta...
Remove duplicate lines from cron file without sorting
Remove duplicate lines from cron file without sorting
Python
mit
vmalavolta/fabix
import fabric.api as fab import cuisine def install(filename, user="root", append=False): """ Installs crontab from a given cronfile """ new_crontab = fab.run("mktemp fabixcron.XXXX") cuisine.file_upload(new_crontab, filename) if append is True: - sorted_crontab =...
Remove duplicate lines from cron file without sorting
## Code Before: import fabric.api as fab import cuisine def install(filename, user="root", append=False): """ Installs crontab from a given cronfile """ new_crontab = fab.run("mktemp fabixcron.XXXX") cuisine.file_upload(new_crontab, filename) if append is True: sorted_crontab = fab.run...
02da417b238256878cfab7c0adef8f86f5532b01
tamper/randomcomments.py
tamper/randomcomments.py
import re from lib.core.common import randomRange from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def tamper(payload, **kwargs): """ Add random comments to SQL keywords >>> import random >>> random.seed(0) >>> tamper('INSERT') 'I/**/N/**/SERT' ...
import re from lib.core.common import randomRange from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def tamper(payload, **kwargs): """ Add random comments to SQL keywords >>> import random >>> random.seed(0) >>> tamper('INSERT') 'I/**/N/**/SERT' ...
Fix for a tamper script (in some cases comments were not inserted)
Fix for a tamper script (in some cases comments were not inserted)
Python
mit
dtrip/.ubuntu,RexGene/monsu-server,RexGene/monsu-server,dtrip/.ubuntu
import re from lib.core.common import randomRange from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def tamper(payload, **kwargs): """ Add random comments to SQL keywords >>> import random >>> random.seed(0) >>> tamper('...
Fix for a tamper script (in some cases comments were not inserted)
## Code Before: import re from lib.core.common import randomRange from lib.core.data import kb from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def tamper(payload, **kwargs): """ Add random comments to SQL keywords >>> import random >>> random.seed(0) >>> tamper('INSERT') 'I/...
2b758185e0de0d41c5ecc9a5511308ee36c60c91
Python_Data/smpl4.py
Python_Data/smpl4.py
''' 2.1 - Numpy Array library ''' #!/usr/bin/env import numpy as np def main(): '''' # 1) Create two vectors 'a' and 'b', and sum them. # Standart n = 3 a = [x**2 for x in range(1, n + 1)] b = [x**3 for x in range(1, n + 1)] v = plainVectorAddition(a, b) # Numpy n = 3 a = np.ara...
''' 2.1 - Numpy Array library - Sum of two vectors - Usage: python smpl4.py n Where 'n' specifies the size of the vector. The program make performance comparisons and print the results. ''' #!/usr/bin/env import numpy as np import sys from datetime import datetime def main(): size = int(sys.argv[1]) s...
Add file with linear algebra numpy operations
Add file with linear algebra numpy operations
Python
unlicense
robotenique/RandomAccessMemory,robotenique/RandomAccessMemory,robotenique/RandomAccessMemory
''' 2.1 - Numpy Array library + - Sum of two vectors - + + Usage: python smpl4.py n + + Where 'n' specifies the size of the vector. + The program make performance comparisons and print the results. + ''' #!/usr/bin/env import numpy as np + import sys + from datetime import datetime def main(): +...
Add file with linear algebra numpy operations
## Code Before: ''' 2.1 - Numpy Array library ''' #!/usr/bin/env import numpy as np def main(): '''' # 1) Create two vectors 'a' and 'b', and sum them. # Standart n = 3 a = [x**2 for x in range(1, n + 1)] b = [x**3 for x in range(1, n + 1)] v = plainVectorAddition(a, b) # Numpy n = ...
8b7aef341aadefb859790684f41453f561813083
tmi/views/__init__.py
tmi/views/__init__.py
from flask import g from flask.ext.login import current_user from tmi.core import app from tmi.assets import assets # noqa from tmi.views.ui import ui # noqa from tmi.views.auth import login, logout # noqa from tmi.views.admin import admin # noqa from tmi.views.cards_api import blueprint as cards_api @app.before_req...
from flask import g, request from flask.ext.login import current_user from werkzeug.exceptions import HTTPException from tmi.core import app from tmi.forms import Invalid from tmi.util import jsonify from tmi.assets import assets # noqa from tmi.views.ui import ui # noqa from tmi.views.auth import login, logout # noqa...
Handle errors with JSON messages.
Handle errors with JSON messages.
Python
mit
pudo/storyweb,pudo/storyweb
- from flask import g + from flask import g, request from flask.ext.login import current_user + from werkzeug.exceptions import HTTPException from tmi.core import app + from tmi.forms import Invalid + from tmi.util import jsonify from tmi.assets import assets # noqa from tmi.views.ui import ui # noqa from ...
Handle errors with JSON messages.
## Code Before: from flask import g from flask.ext.login import current_user from tmi.core import app from tmi.assets import assets # noqa from tmi.views.ui import ui # noqa from tmi.views.auth import login, logout # noqa from tmi.views.admin import admin # noqa from tmi.views.cards_api import blueprint as cards_api ...
f5f728074b257aac371fc59af8de02e440e57819
furikura/desktop/unity.py
furikura/desktop/unity.py
import gi gi.require_version('Unity', '7.0') from gi.repository import Unity, Dbusmenu launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop") def update_counter(count): launcher.set_property("count", count) launcher.set_property("count_visible", True) def add_quicklist_item(item): quick_l...
import gi from threading import Timer gi.require_version('Unity', '7.0') from gi.repository import Unity, Dbusmenu launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop") def update_counter(count): launcher.set_property("count", count) launcher.set_property("count_visible", True) if count...
Apply "Urgent" icon animation on new message
Apply "Urgent" icon animation on new message
Python
mit
benjamindean/furi-kura,benjamindean/furi-kura
import gi + from threading import Timer gi.require_version('Unity', '7.0') from gi.repository import Unity, Dbusmenu + launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop") def update_counter(count): launcher.set_property("count", count) launcher.set_property("count_visib...
Apply "Urgent" icon animation on new message
## Code Before: import gi gi.require_version('Unity', '7.0') from gi.repository import Unity, Dbusmenu launcher = Unity.LauncherEntry.get_for_desktop_id("furikura.desktop") def update_counter(count): launcher.set_property("count", count) launcher.set_property("count_visible", True) def add_quicklist_item(it...
3b5ad132f3670d1c1210190ecd7b41a379fbd10e
trakt/core/helpers.py
trakt/core/helpers.py
import arrow def to_datetime(value): if value is None: return None # Parse ISO8601 datetime dt = arrow.get(value) # Return python datetime object return dt.datetime
import arrow def to_datetime(value): if value is None: return None # Parse ISO8601 datetime dt = arrow.get(value) # Convert to UTC dt = dt.to('UTC') # Return naive datetime object return dt.naive
Convert all datetime properties to UTC
Convert all datetime properties to UTC
Python
mit
shad7/trakt.py,fuzeman/trakt.py
import arrow def to_datetime(value): if value is None: return None # Parse ISO8601 datetime dt = arrow.get(value) - # Return python datetime object - return dt.datetime + # Convert to UTC + dt = dt.to('UTC') + # Return naive datetime object + return...
Convert all datetime properties to UTC
## Code Before: import arrow def to_datetime(value): if value is None: return None # Parse ISO8601 datetime dt = arrow.get(value) # Return python datetime object return dt.datetime ## Instruction: Convert all datetime properties to UTC ## Code After: import arrow def to_datetime(value...
5e3b712c4c2eac7227d6e894ce05db6f1ede074a
hgtools/tests/conftest.py
hgtools/tests/conftest.py
import os import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def hg_repo(tmpdir): tmpdir.chdir() mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch('bar/baz') mgr...
import os import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def tmpdir_as_cwd(tmpdir): with tmpdir.as_cwd(): yield tmpdir @pytest.fixture def hg_repo(tmpdir_as_cwd): mgr = managers.MercurialManager() _ensure_present...
Fix test failures by restoring working directory in fixtures.
Fix test failures by restoring working directory in fixtures.
Python
mit
jaraco/hgtools
import os import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture + def tmpdir_as_cwd(tmpdir): + with tmpdir.as_cwd(): + yield tmpdir + + + @pytest.fixture - def hg_repo(tmpdir): + def hg_repo(...
Fix test failures by restoring working directory in fixtures.
## Code Before: import os import pytest from hgtools import managers def _ensure_present(mgr): try: mgr.version() except Exception: pytest.skip() @pytest.fixture def hg_repo(tmpdir): tmpdir.chdir() mgr = managers.MercurialManager() _ensure_present(mgr) mgr._invoke('init', '.') os.makedirs('bar') touch...
c2eccb4ce1259830dd641d19624358af83c09549
webcomix/comic_spider.py
webcomix/comic_spider.py
from urllib.parse import urljoin import scrapy class ComicSpider(scrapy.Spider): name = "My spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('next_page_selector', None) self.comic_image_selector = kwarg...
from urllib.parse import urljoin import click import scrapy class ComicSpider(scrapy.Spider): name = "Comic Spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('next_page_selector', None) self.comic_image_...
Copy logging from previous version and only yield item to pipeline if a comic image was found
Copy logging from previous version and only yield item to pipeline if a comic image was found
Python
mit
J-CPelletier/webcomix,J-CPelletier/webcomix,J-CPelletier/WebComicToCBZ
from urllib.parse import urljoin + import click import scrapy class ComicSpider(scrapy.Spider): - name = "My spider" + name = "Comic Spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('nex...
Copy logging from previous version and only yield item to pipeline if a comic image was found
## Code Before: from urllib.parse import urljoin import scrapy class ComicSpider(scrapy.Spider): name = "My spider" def __init__(self, *args, **kwargs): self.start_urls = kwargs.get('start_urls') or [] self.next_page_selector = kwargs.get('next_page_selector', None) self.comic_image_...
1a6344ea1fac51a8024e1803a0391662d4ab81e0
pyeda/boolalg/vexpr.py
pyeda/boolalg/vexpr.py
from pyeda.boolalg import expr from pyeda.boolalg import bfarray def bitvec(name, *dims): """Return a new array of given dimensions, filled with Expressions. Parameters ---------- name : str dims : (int or (int, int)) An int N means a slice from [0:N] A tuple (M, N) means a slice ...
from warnings import warn from pyeda.boolalg import expr from pyeda.boolalg import bfarray def bitvec(name, *dims): """Return a new array of given dimensions, filled with Expressions. Parameters ---------- name : str dims : (int or (int, int)) An int N means a slice from [0:N] A ...
Add deprecation warning to bitvec function
Add deprecation warning to bitvec function
Python
bsd-2-clause
pombredanne/pyeda,GtTmy/pyeda,karissa/pyeda,sschnug/pyeda,sschnug/pyeda,cjdrake/pyeda,sschnug/pyeda,cjdrake/pyeda,GtTmy/pyeda,GtTmy/pyeda,karissa/pyeda,pombredanne/pyeda,karissa/pyeda,cjdrake/pyeda,pombredanne/pyeda
+ + from warnings import warn from pyeda.boolalg import expr from pyeda.boolalg import bfarray def bitvec(name, *dims): """Return a new array of given dimensions, filled with Expressions. Parameters ---------- name : str dims : (int or (int, int)) An int N means a...
Add deprecation warning to bitvec function
## Code Before: from pyeda.boolalg import expr from pyeda.boolalg import bfarray def bitvec(name, *dims): """Return a new array of given dimensions, filled with Expressions. Parameters ---------- name : str dims : (int or (int, int)) An int N means a slice from [0:N] A tuple (M, N...
cd621061773b7eafcea9358c9b762663a070ccc5
cc/license/jurisdiction.py
cc/license/jurisdiction.py
import RDF import zope.interface import interfaces import rdf_helper class Jurisdiction(object): zope.interface.implements(interfaces.IJurisdiction) def __init__(self, short_name): '''@param short_name can be e.g. mx''' model = rdf_helper.init_model( rdf_helper.JURI_RDF_PATH) ...
import RDF import zope.interface import interfaces import rdf_helper class Jurisdiction(object): zope.interface.implements(interfaces.IJurisdiction) def __init__(self, short_name): """Creates an object representing a jurisdiction. short_name is a (usually) two-letter code representing ...
Add documentation and make Jurisdiction calls not fail when some of the values aren't found.
Add documentation and make Jurisdiction calls not fail when some of the values aren't found.
Python
mit
creativecommons/cc.license,creativecommons/cc.license
import RDF import zope.interface import interfaces import rdf_helper class Jurisdiction(object): zope.interface.implements(interfaces.IJurisdiction) def __init__(self, short_name): - '''@param short_name can be e.g. mx''' + """Creates an object representing a jurisdiction. + ...
Add documentation and make Jurisdiction calls not fail when some of the values aren't found.
## Code Before: import RDF import zope.interface import interfaces import rdf_helper class Jurisdiction(object): zope.interface.implements(interfaces.IJurisdiction) def __init__(self, short_name): '''@param short_name can be e.g. mx''' model = rdf_helper.init_model( rdf_helper.JURI...
9c39105f2dcb296590e895aaf35de5d4c3105ddb
ephypype/commands/tests/test_cli.py
ephypype/commands/tests/test_cli.py
"""Test neuropycon command line interface""" # Authors: Dmitrii Altukhov <daltuhov@hse.ru> # # License: BSD (3-clause) import os import os.path as op from ephypype.commands import neuropycon from click.testing import CliRunner def test_input_linear(): """Test input node with Linear plugin (serial workflow execu...
"""Test neuropycon command line interface""" # Authors: Dmitrii Altukhov <daltuhov@hse.ru> # # License: BSD (3-clause) import matplotlib # noqa matplotlib.use('Agg') # noqa; for testing don't use X server import os import os.path as op from ephypype.commands import neuropycon from click.testing import CliRunner d...
FIX matplotlib backend problem in cli tests
FIX matplotlib backend problem in cli tests
Python
bsd-3-clause
neuropycon/ephypype
"""Test neuropycon command line interface""" # Authors: Dmitrii Altukhov <daltuhov@hse.ru> # # License: BSD (3-clause) + + import matplotlib # noqa + matplotlib.use('Agg') # noqa; for testing don't use X server import os import os.path as op from ephypype.commands import neuropycon from click.te...
FIX matplotlib backend problem in cli tests
## Code Before: """Test neuropycon command line interface""" # Authors: Dmitrii Altukhov <daltuhov@hse.ru> # # License: BSD (3-clause) import os import os.path as op from ephypype.commands import neuropycon from click.testing import CliRunner def test_input_linear(): """Test input node with Linear plugin (seria...
92d25e86620fcdc415e94d5867cc22a95f88ca3a
mint/rest/db/awshandler.py
mint/rest/db/awshandler.py
from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): self.amiPerms.addMemberToProject(userId, projectId) ...
from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): self.amiPerms.deleteMemberFromProject(userId, projectId...
Fix typo when setting up handler.
Fix typo when setting up handler.
Python
apache-2.0
sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint
from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): - self.amiPerms.addMemberToProject(user...
Fix typo when setting up handler.
## Code Before: from mint import amiperms class AWSHandler(object): def __init__(self, cfg, db): self.db = db self.amiPerms = amiperms.AMIPermissionsManager(cfg, db) def notify_UserProductRemoved(self, event, userId, projectId, userlevel = None): self.amiPerms.addMemberToProject(userId...
09b2fe8b248e70300470fcf71f6df0741376c548
misc/disassemble_linear.py
misc/disassemble_linear.py
import sys import time import bracoujl.processor.gb_z80 as proc dis = proc.CPU_CONF['disassembler']() def disassemble(lines): res = '' for line in lines: op = proc.CPU_CONF['parse_line'](line) if op is None: continue res += '{:04X}'.format(op['pc']) + ' - ' + dis.disassembl...
import argparse import sys import time import bracoujl.processor.gb_z80 as proc dis = proc.CPU_CONF['disassembler']() def disassemble(lines, keep_logs=False): res = [] for line in lines: op, gline = proc.CPU_CONF['parse_line'](line), '' if keep_logs: gline += line + (' | DIS: ' if ...
Fix and enhance disassemble miscellaneous script.
Fix and enhance disassemble miscellaneous script.
Python
bsd-3-clause
fmichea/bracoujl
+ import argparse import sys import time import bracoujl.processor.gb_z80 as proc dis = proc.CPU_CONF['disassembler']() - def disassemble(lines): + def disassemble(lines, keep_logs=False): - res = '' + res = [] for line in lines: - op = proc.CPU_CONF['parse_line'](line) + op,...
Fix and enhance disassemble miscellaneous script.
## Code Before: import sys import time import bracoujl.processor.gb_z80 as proc dis = proc.CPU_CONF['disassembler']() def disassemble(lines): res = '' for line in lines: op = proc.CPU_CONF['parse_line'](line) if op is None: continue res += '{:04X}'.format(op['pc']) + ' - ' ...
e0063c0d5604372c1a07a179f5206a0a27570817
package_reviewer/check/repo/check_semver_tags.py
package_reviewer/check/repo/check_semver_tags.py
import re from . import RepoChecker class CheckSemverTags(RepoChecker): def check(self): if not self.semver_tags: msg = "No semantic version tags found. See http://semver.org." for tag in self.tags: if re.search(r"(v|^)\d+\.\d+$", tag.name): m...
import re from . import RepoChecker class CheckSemverTags(RepoChecker): def check(self): if not self.semver_tags: msg = "No semantic version tags found" for tag in self.tags: if re.search(r"(v|^)\d+\.\d+$", tag.name): msg += " (semantic versio...
Change message of semver tag check
Change message of semver tag check
Python
mit
packagecontrol/st_package_reviewer,packagecontrol/package_reviewer
import re from . import RepoChecker class CheckSemverTags(RepoChecker): def check(self): if not self.semver_tags: - msg = "No semantic version tags found. See http://semver.org." + msg = "No semantic version tags found" for tag in self.tags: ...
Change message of semver tag check
## Code Before: import re from . import RepoChecker class CheckSemverTags(RepoChecker): def check(self): if not self.semver_tags: msg = "No semantic version tags found. See http://semver.org." for tag in self.tags: if re.search(r"(v|^)\d+\.\d+$", tag.name): ...
d3163d8a7695da9687f82d9d40c6767322998fc2
python/ql/test/experimental/dataflow/tainttracking/defaultAdditionalTaintStep-py3/test_collections.py
python/ql/test/experimental/dataflow/tainttracking/defaultAdditionalTaintStep-py3/test_collections.py
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__)))) from taintlib import * # This has no runtime impact, but allows autocomplete to work from typing import TYPE_CHECKING if TYPE_CHECKING: from ..taintlib import * # Actual tests def test_access(): tainted_list = TAINTED_LIST ...
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__)))) from taintlib import * # This has no runtime impact, but allows autocomplete to work from typing import TYPE_CHECKING if TYPE_CHECKING: from ..taintlib import * # Actual tests def test_access(): tainted_list = TAINTED_LIST ...
Add iterable-unpacking in for test
Python: Add iterable-unpacking in for test
Python
mit
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__)))) from taintlib import * # This has no runtime impact, but allows autocomplete to work from typing import TYPE_CHECKING if TYPE_CHECKING: from ..taintlib import * # Actual tests def test_access(): taint...
Add iterable-unpacking in for test
## Code Before: import sys; import os; sys.path.append(os.path.dirname(os.path.dirname((__file__)))) from taintlib import * # This has no runtime impact, but allows autocomplete to work from typing import TYPE_CHECKING if TYPE_CHECKING: from ..taintlib import * # Actual tests def test_access(): tainted_list ...
679abfdd2b6a3c4d18170d93bfd42d73c47ff9c5
phasm/typing.py
phasm/typing.py
from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembl...
from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignment]] # Assembl...
Change Node type a bit
Change Node type a bit In a reconstructed assembly graph sometimes the nodes can be str
Python
mit
AbeelLab/phasm,AbeelLab/phasm
from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignm...
Change Node type a bit
## Code Before: from typing import Mapping, Set, Callable, Union, Tuple, Iterable # Pairwise local alignments OrientedDNASegment = 'phasm.alignments.OrientedDNASegment' OrientedRead = 'phasm.alignments.OrientedRead' LocalAlignment = 'phasm.alignments.LocalAlignment' AlignmentsT = Mapping[OrientedRead, Set[LocalAlignm...
fea07e0fe53049963a744b52c38a9abdfeb1c09e
commands.py
commands.py
from os import path import shutil import sublime import sublime_plugin SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..')) COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands') COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH) COMMANDS_SOURCE_FULL_FILEPATH...
from os import path import shutil import sublime import sublime_plugin SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..')) COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands') COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH) COMMANDS_SOURCE_FULL_FILEPATH...
Revert "Started exploring using argument but realizing this is a rabbit hole"
Revert "Started exploring using argument but realizing this is a rabbit hole" This reverts commit b899d5613c0f4425aa4cc69bac9561b503ba83d4.
Python
unlicense
twolfson/sublime-edit-command-palette,twolfson/sublime-edit-command-palette,twolfson/sublime-edit-command-palette
from os import path import shutil import sublime import sublime_plugin SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..')) COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands') COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH) COMMANDS_...
Revert "Started exploring using argument but realizing this is a rabbit hole"
## Code Before: from os import path import shutil import sublime import sublime_plugin SUBLIME_ROOT = path.normpath(path.join(sublime.packages_path(), '..')) COMMANDS_FILEPATH = path.join('Packages', 'User', 'Commands.sublime-commands') COMMANDS_FULL_FILEPATH = path.join(SUBLIME_ROOT, COMMANDS_FILEPATH) COMMANDS_SOUR...
b21c5a1b0f8d176cdd59c8131a316f142540d9ec
materials.py
materials.py
import color def parse(mat_node): materials = [] for node in mat_node: materials.append(Material(node)) class Material: ''' it’s a material ''' def __init__(self, node): for c in node: if c.tag == 'ambient': self.ambient_color = color.parse(c[0]) ...
import color def parse(mat_node): materials = [] for node in mat_node: materials.append(Material(node)) class Material: ''' it’s a material ''' def __init__(self, node): for c in node: if c.tag == 'ambient': self.ambient_color = color.parse(c[0]) ...
Remove replacement of commas by points
Remove replacement of commas by points
Python
mit
cocreature/pytracer
import color def parse(mat_node): materials = [] for node in mat_node: materials.append(Material(node)) class Material: ''' it’s a material ''' def __init__(self, node): for c in node: if c.tag == 'ambient': self.ambient...
Remove replacement of commas by points
## Code Before: import color def parse(mat_node): materials = [] for node in mat_node: materials.append(Material(node)) class Material: ''' it’s a material ''' def __init__(self, node): for c in node: if c.tag == 'ambient': self.ambient_color = color.p...
2fe72f41b1b62cf770869b8d3ccefeef1096ea11
conftest.py
conftest.py
import behave import pytest @pytest.fixture(autouse=True) def _annotate_environment(request): """Add project-specific information to test-run environment: * behave.version NOTE: autouse: Fixture is automatically used when test-module is imported. """ # -- USEFULL FOR: pytest --html=report.html ....
import behave import pytest @pytest.fixture(autouse=True) def _annotate_environment(request): """Add project-specific information to test-run environment: * behave.version NOTE: autouse: Fixture is automatically used when test-module is imported. """ # -- USEFULL FOR: pytest --html=report.html ....
FIX when pytest-html is not installed.
FIX when pytest-html is not installed.
Python
bsd-2-clause
Abdoctor/behave,Abdoctor/behave,jenisys/behave,jenisys/behave
import behave import pytest @pytest.fixture(autouse=True) def _annotate_environment(request): """Add project-specific information to test-run environment: * behave.version NOTE: autouse: Fixture is automatically used when test-module is imported. """ # -- USEFULL FOR: p...
FIX when pytest-html is not installed.
## Code Before: import behave import pytest @pytest.fixture(autouse=True) def _annotate_environment(request): """Add project-specific information to test-run environment: * behave.version NOTE: autouse: Fixture is automatically used when test-module is imported. """ # -- USEFULL FOR: pytest --ht...
6267fa5d9a3ff2573dc33a23d3456942976b0b7e
cyder/base/models.py
cyder/base/models.py
from django.db import models from django.utils.safestring import mark_safe from cyder.base.utils import classproperty class BaseModel(models.Model): """ Base class for models to abstract some common features. * Adds automatic created and modified fields to the model. """ created = models.DateTim...
from django.db import models from django.utils.safestring import mark_safe from cyder.base.utils import classproperty class BaseModel(models.Model): """ Base class for models to abstract some common features. * Adds automatic created and modified fields to the model. """ created = models.DateTim...
Add help_text to interface 'expire' field
Add help_text to interface 'expire' field
Python
bsd-3-clause
OSU-Net/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,OSU-Net/cyder,murrown/cyder,OSU-Net/cyder,murrown/cyder,murrown/cyder,drkitty/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,murrown/cyder,akeym/cyder,akeym/cyder,drkitty/cyder,zeeman/cyder,zeeman/cyder,akeym/cyder
from django.db import models from django.utils.safestring import mark_safe from cyder.base.utils import classproperty class BaseModel(models.Model): """ Base class for models to abstract some common features. * Adds automatic created and modified fields to the model. """ ...
Add help_text to interface 'expire' field
## Code Before: from django.db import models from django.utils.safestring import mark_safe from cyder.base.utils import classproperty class BaseModel(models.Model): """ Base class for models to abstract some common features. * Adds automatic created and modified fields to the model. """ created ...
f29a6b205a872d7df63e8c45b5829959c98de227
comics/comics/pcweenies.py
comics/comics/pcweenies.py
from comics.aggregator.crawler import CrawlerBase, CrawlerResult from comics.meta.base import MetaBase class Meta(MetaBase): name = 'The PC Weenies' language = 'en' url = 'http://www.pcweenies.com/' start_date = '1998-10-21' rights = 'Krishna M. Sadasivam' class Crawler(CrawlerBase): history_c...
from comics.aggregator.crawler import CrawlerBase, CrawlerResult from comics.meta.base import MetaBase class Meta(MetaBase): name = 'The PC Weenies' language = 'en' url = 'http://www.pcweenies.com/' start_date = '1998-10-21' rights = 'Krishna M. Sadasivam' class Crawler(CrawlerBase): history_c...
Update CSS selector which matched two img elements
Update CSS selector which matched two img elements
Python
agpl-3.0
klette/comics,jodal/comics,jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,klette/comics,klette/comics,datagutten/comics,datagutten/comics
from comics.aggregator.crawler import CrawlerBase, CrawlerResult from comics.meta.base import MetaBase class Meta(MetaBase): name = 'The PC Weenies' language = 'en' url = 'http://www.pcweenies.com/' start_date = '1998-10-21' rights = 'Krishna M. Sadasivam' class Crawler(Crawl...
Update CSS selector which matched two img elements
## Code Before: from comics.aggregator.crawler import CrawlerBase, CrawlerResult from comics.meta.base import MetaBase class Meta(MetaBase): name = 'The PC Weenies' language = 'en' url = 'http://www.pcweenies.com/' start_date = '1998-10-21' rights = 'Krishna M. Sadasivam' class Crawler(CrawlerBase...
6ad647899d044cb46be6172cbea9c93a369ddc78
pymanopt/solvers/theano_functions/comp_diff.py
pymanopt/solvers/theano_functions/comp_diff.py
import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument): g = T.gra...
import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument): g = T.gra...
Use `compile` function for `gradient` function
Use `compile` function for `gradient` function Signed-off-by: Niklas Koep <342d5290239d9c5264c8f98185afedb99596601a@gmail.com>
Python
bsd-3-clause
j-towns/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,tingelst/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,nkoep/pymanopt
import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, ar...
Use `compile` function for `gradient` function
## Code Before: import theano.tensor as T import theano # Compile objective function defined in Theano. def compile(objective, argument): return theano.function([argument], objective) # Compute the gradient of 'objective' with respect to 'argument' and return # compiled function. def gradient(objective, argument...
48e4203bc87fda407d0e5f804c854b53f7bf54fc
lemon/publications/managers.py
lemon/publications/managers.py
from django.db import models from lemon.publications.querysets import PublicationQuerySet class PublicationManager(models.Manager): def expired(self): return self.get_query_set().expired() def future(self): return self.get_query_set().future() def enabled(self): return self...
from django.db import models from lemon.publications.querysets import PublicationQuerySet class PublicationManager(models.Manager): def expired(self): return self.get_query_set().expired() def future(self): return self.get_query_set().future() def enabled(self): return self...
Fix handling of the _db attribute on the PublicationManager in get_query_set
Fix handling of the _db attribute on the PublicationManager in get_query_set
Python
bsd-3-clause
trilan/lemon,trilan/lemon,trilan/lemon
from django.db import models from lemon.publications.querysets import PublicationQuerySet class PublicationManager(models.Manager): def expired(self): return self.get_query_set().expired() def future(self): return self.get_query_set().future() def enable...
Fix handling of the _db attribute on the PublicationManager in get_query_set
## Code Before: from django.db import models from lemon.publications.querysets import PublicationQuerySet class PublicationManager(models.Manager): def expired(self): return self.get_query_set().expired() def future(self): return self.get_query_set().future() def enabled(self): ...
3c4565dcf6222af0e3b7cabf5c52f9ab18488be2
tests/test_main.py
tests/test_main.py
from cookiecutter.main import is_repo_url, expand_abbreviations def test_is_repo_url(): """Verify is_repo_url works.""" assert is_repo_url('gitolite@server:team/repo') is True assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True assert is_repo_url('https://github.com/audreyr/cookiecut...
import pytest from cookiecutter.main import is_repo_url, expand_abbreviations @pytest.fixture(params=[ 'gitolite@server:team/repo', 'git@github.com:audreyr/cookiecutter.git', 'https://github.com/audreyr/cookiecutter.git', 'https://bitbucket.org/pokoli/cookiecutter.hg', ]) def remote_repo_url(request...
Refactor tests for is_repo_url to be parametrized
Refactor tests for is_repo_url to be parametrized
Python
bsd-3-clause
luzfcb/cookiecutter,terryjbates/cookiecutter,michaeljoseph/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,stevepiercy/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter,Springerle/cookiecutter,dajose/cookiecutter,stevepiercy/cookiecutter,terryjbates/cookiecutter,audreyr/cookiecutter,pjbull/cookiecutter,aud...
+ + import pytest + from cookiecutter.main import is_repo_url, expand_abbreviations - def test_is_repo_url(): + @pytest.fixture(params=[ + 'gitolite@server:team/repo', + 'git@github.com:audreyr/cookiecutter.git', + 'https://github.com/audreyr/cookiecutter.git', + 'https://bitbucket.org/pokoli/...
Refactor tests for is_repo_url to be parametrized
## Code Before: from cookiecutter.main import is_repo_url, expand_abbreviations def test_is_repo_url(): """Verify is_repo_url works.""" assert is_repo_url('gitolite@server:team/repo') is True assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True assert is_repo_url('https://github.com/a...
4b6bb7b7d258a9f130b7d10f390f44dec855cc19
admin/src/gui/NewScoville.py
admin/src/gui/NewScoville.py
import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): def __init__(self): pass
import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): pass
Revert "added constructor (testcommit for new git interface)"
Revert "added constructor (testcommit for new git interface)" This reverts commit d5c0252b75e97103d61c3203e2a8d04a061c8a2f.
Python
agpl-3.0
skarphed/skarphed,skarphed/skarphed
import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): - def __init__(self): - pass + pass
Revert "added constructor (testcommit for new git interface)"
## Code Before: import pygtk pygtk.require("2.0") import gtk builder = gtk.Builder() builder.add_from_file(os.path[0]+"/src/gui/NewScoville.ui") class NewScovilleWindow(object): def __init__(self): pass ## Instruction: Revert "added constructor (testcommit for new git interface)" ## Code After: import pygt...
589598a9fc3871fe534e4dde60b61c9a0a56e224
legistar/ext/pupa/orgs.py
legistar/ext/pupa/orgs.py
import pupa.scrape from legistar.utils.itemgenerator import make_item from legistar.ext.pupa.base import Adapter, Converter class OrgsAdapter(Adapter): '''Converts legistar data into a pupa.scrape.Person instance. Note the make_item methods are popping values out the dict, because the associated keys are...
import pupa.scrape from legistar.utils.itemgenerator import make_item from legistar.ext.pupa.base import Adapter, Converter class OrgsAdapter(Adapter): '''Converts legistar data into a pupa.scrape.Person instance. Note the make_item methods are popping values out the dict, because the associated keys are...
Remove cruft copied from Memberships adapter
Remove cruft copied from Memberships adapter
Python
bsd-3-clause
opencivicdata/python-legistar-scraper,datamade/python-legistar-scraper
import pupa.scrape from legistar.utils.itemgenerator import make_item from legistar.ext.pupa.base import Adapter, Converter class OrgsAdapter(Adapter): '''Converts legistar data into a pupa.scrape.Person instance. Note the make_item methods are popping values out the dict, because the...
Remove cruft copied from Memberships adapter
## Code Before: import pupa.scrape from legistar.utils.itemgenerator import make_item from legistar.ext.pupa.base import Adapter, Converter class OrgsAdapter(Adapter): '''Converts legistar data into a pupa.scrape.Person instance. Note the make_item methods are popping values out the dict, because the ass...
42d06a15dd30e770dfccfccbd20fbf9bba52494d
platforms/m3/programming/goc_gdp_test.py
platforms/m3/programming/goc_gdp_test.py
import code try: import Image except ImportError: from PIL import Image import gdp gdp.gdp_init() gcl_name = gdp.GDP_NAME("edu.umich.eecs.m3.test01") gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA) #j = Image.open('/tmp/capture1060.jpeg') #d = {"data": j.tostring()} #gcl_handle.append(d) record = gcl_handle...
import code try: import Image except ImportError: from PIL import Image import gdp gdp.gdp_init() gcl_name = gdp.GDP_NAME("edu.umich.eecs.m3.test01") gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA) #j = Image.open('/tmp/capture1060.jpeg') #d = {"data": j.tostring()} #gcl_handle.append(d) while True: try: ...
Update gdp test to open random images
Update gdp test to open random images
Python
apache-2.0
lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator,lab11/M-ulator
import code try: import Image except ImportError: from PIL import Image import gdp gdp.gdp_init() gcl_name = gdp.GDP_NAME("edu.umich.eecs.m3.test01") gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA) #j = Image.open('/tmp/capture1060.jpeg') #d = {"data": j.tostring()} #gcl_han...
Update gdp test to open random images
## Code Before: import code try: import Image except ImportError: from PIL import Image import gdp gdp.gdp_init() gcl_name = gdp.GDP_NAME("edu.umich.eecs.m3.test01") gcl_handle = gdp.GDP_GCL(gcl_name, gdp.GDP_MODE_RA) #j = Image.open('/tmp/capture1060.jpeg') #d = {"data": j.tostring()} #gcl_handle.append(d) rec...
e29039cf5b1cd0b40b8227ef73c2d5327450c162
app/core/servicemanager.py
app/core/servicemanager.py
import threading import logging logger = logging.getLogger(__name__) class ServiceManager(threading.Thread): """ Sequentially starts services using service.service_start(). When a new service is activated, view_manager is updated with its view. """ def __init__(self, services, socket_manager): ...
import importlib import logging from collections import namedtuple from app.core.toposort import toposort logger = logging.getLogger(__name__) Module = namedtuple('Module', ["name", "deps", "meta"]) def list_modules(module): res = [] # for name in os.listdir(module.__path__): for name in ["messaging"]:...
Use toposort for sequencing services.
Use toposort for sequencing services.
Python
mit
supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer
- import threading + import importlib import logging + from collections import namedtuple + + from app.core.toposort import toposort + + logger = logging.getLogger(__name__) + Module = namedtuple('Module', ["name", "deps", "meta"]) - logger = logging.getLogger(__name__) + def list_modules(module): + re...
Use toposort for sequencing services.
## Code Before: import threading import logging logger = logging.getLogger(__name__) class ServiceManager(threading.Thread): """ Sequentially starts services using service.service_start(). When a new service is activated, view_manager is updated with its view. """ def __init__(self, services, s...
fc1505865f919764aa066e5e43dcde1bc7e760b2
frappe/patches/v13_0/rename_desk_page_to_workspace.py
frappe/patches/v13_0/rename_desk_page_to_workspace.py
import frappe from frappe.model.rename_doc import rename_doc def execute(): if frappe.db.exists("DocType", "Desk Page"): if frappe.db.exists('DocType', 'Workspace'): # this patch was not added initially, so this page might still exist frappe.delete_doc('DocType', 'Desk Page') else: rename_doc('DocType', ...
import frappe from frappe.model.rename_doc import rename_doc def execute(): if frappe.db.exists("DocType", "Desk Page"): if frappe.db.exists('DocType', 'Workspace'): # this patch was not added initially, so this page might still exist frappe.delete_doc('DocType', 'Desk Page') else: rename_doc('DocType', ...
Rename Desk Link only if it exists
fix(Patch): Rename Desk Link only if it exists
Python
mit
frappe/frappe,StrellaGroup/frappe,StrellaGroup/frappe,saurabh6790/frappe,StrellaGroup/frappe,mhbu50/frappe,almeidapaulopt/frappe,yashodhank/frappe,saurabh6790/frappe,mhbu50/frappe,frappe/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,saurabh6790/frappe,almeidapaulopt/frappe,almeidapaulopt/frappe,yashodhan...
import frappe from frappe.model.rename_doc import rename_doc def execute(): if frappe.db.exists("DocType", "Desk Page"): if frappe.db.exists('DocType', 'Workspace'): # this patch was not added initially, so this page might still exist frappe.delete_doc('DocType', 'Desk Page') else: re...
Rename Desk Link only if it exists
## Code Before: import frappe from frappe.model.rename_doc import rename_doc def execute(): if frappe.db.exists("DocType", "Desk Page"): if frappe.db.exists('DocType', 'Workspace'): # this patch was not added initially, so this page might still exist frappe.delete_doc('DocType', 'Desk Page') else: rename...
828fec30b5b1deddcca79eae8fd1029bd5bd7b54
py/desispec/io/__init__.py
py/desispec/io/__init__.py
# help with 2to3 support from __future__ import absolute_import, division from .meta import findfile, get_exposures, get_files, rawdata_root, specprod_root from .frame import read_frame, write_frame from .sky import read_sky, write_sky from .fiberflat import read_fiberflat, write_fiberflat from .fibermap import read_...
# help with 2to3 support from __future__ import absolute_import, division from .meta import (findfile, get_exposures, get_files, rawdata_root, specprod_root, validate_night) from .frame import read_frame, write_frame from .sky import read_sky, write_sky from .fiberflat import read_fiberflat, write_fiberflat from...
Add validate_night to public API
Add validate_night to public API
Python
bsd-3-clause
desihub/desispec,gdhungana/desispec,timahutchinson/desispec,gdhungana/desispec,desihub/desispec,timahutchinson/desispec
# help with 2to3 support from __future__ import absolute_import, division - from .meta import findfile, get_exposures, get_files, rawdata_root, specprod_root + from .meta import (findfile, get_exposures, get_files, rawdata_root, + specprod_root, validate_night) from .frame import read_frame, write_fram...
Add validate_night to public API
## Code Before: # help with 2to3 support from __future__ import absolute_import, division from .meta import findfile, get_exposures, get_files, rawdata_root, specprod_root from .frame import read_frame, write_frame from .sky import read_sky, write_sky from .fiberflat import read_fiberflat, write_fiberflat from .fiber...
6d2f9bfbe1011c04e014016171d98fef1d12e840
tests/test_samtools_python.py
tests/test_samtools_python.py
import pysam def test_idxstats_parse(): bam_filename = "./pysam_data/ex2.bam" lines = pysam.idxstats(bam_filename) for line in lines: _seqname, _seqlen, nmapped, _nunmapped = line.split() def test_bedcov(): bam_filename = "./pysam_data/ex1.bam" bed_filename = "./pysam_data/ex1.bed" lin...
import pysam def test_idxstats_parse_old_style_output(): bam_filename = "./pysam_data/ex2.bam" lines = pysam.idxstats(bam_filename, old_style_output=True) for line in lines: _seqname, _seqlen, nmapped, _nunmapped = line.split() def test_bedcov_old_style_output(): bam_filename = "./pysam_data/...
Add test for both new and old style output
Add test for both new and old style output
Python
mit
pysam-developers/pysam,kyleabeauchamp/pysam,pysam-developers/pysam,TyberiusPrime/pysam,bioinformed/pysam,TyberiusPrime/pysam,bioinformed/pysam,TyberiusPrime/pysam,pysam-developers/pysam,bioinformed/pysam,kyleabeauchamp/pysam,TyberiusPrime/pysam,kyleabeauchamp/pysam,kyleabeauchamp/pysam,kyleabeauchamp/pysam,pysam-develo...
import pysam + + def test_idxstats_parse_old_style_output(): + bam_filename = "./pysam_data/ex2.bam" + lines = pysam.idxstats(bam_filename, old_style_output=True) + for line in lines: + _seqname, _seqlen, nmapped, _nunmapped = line.split() + + + def test_bedcov_old_style_output(): + bam_fil...
Add test for both new and old style output
## Code Before: import pysam def test_idxstats_parse(): bam_filename = "./pysam_data/ex2.bam" lines = pysam.idxstats(bam_filename) for line in lines: _seqname, _seqlen, nmapped, _nunmapped = line.split() def test_bedcov(): bam_filename = "./pysam_data/ex1.bam" bed_filename = "./pysam_data/...
1ff19fcd0bcbb396b7cb676c5dddf8d3c8652419
live/components/misc.py
live/components/misc.py
from live.helpers import Timer def timed(fun, time, next_fun=None): """A component that runs another component for a fixed length of time. Can optionally be given a follow-up component for chaining. :param callable fun: The component to be run: :param number time: The amount of time to run the component ...
from live.helpers import Timer def timed(fun, time, next_fun=None): """A component that runs another component for a fixed length of time. Can optionally be given a follow-up component for chaining. :param callable fun: The component to be run: :param number time: The amount of time to run the component ...
Update timed_callback to support collision callbacks.
Update timed_callback to support collision callbacks.
Python
lgpl-2.1
GalanCM/BGELive
from live.helpers import Timer def timed(fun, time, next_fun=None): """A component that runs another component for a fixed length of time. Can optionally be given a follow-up component for chaining. :param callable fun: The component to be run: :param number time: The amount of time to run the ...
Update timed_callback to support collision callbacks.
## Code Before: from live.helpers import Timer def timed(fun, time, next_fun=None): """A component that runs another component for a fixed length of time. Can optionally be given a follow-up component for chaining. :param callable fun: The component to be run: :param number time: The amount of time to run th...
28ac2b259d89c168f1e822fe087c66f2f618321a
setup.py
setup.py
from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='trobitaille@cfa.harvard.edu', packages=...
from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='trobitaille@cfa.harvard.edu', packages=...
Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError)
Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError)
Python
bsd-2-clause
astrofrog/sedfitter
from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='trobitaille@cfa.harvard.e...
Add sedfitter.source to list of sub-packages to install (otherwise results in ImportError)
## Code Before: from distutils.core import setup scripts = ['sed_fit', 'sed_plot', 'sed_filter_output', 'sed_fitinfo2data', 'sed_fitinfo2ascii'] setup(name='sedfitter', version='0.1.1', description='SED Fitter in python', author='Thomas Robitaille', author_email='trobitaille@cfa.harvard.edu',...
d2cc077bfce9bef654a8ef742996e5aca8858fc7
setup.py
setup.py
from distutils.core import setup setup(name='Pyranha', description='Elegant IRC client', version='0.1', author='John Reese', author_email='john@noswap.com', url='https://github.com/jreese/pyranha', classifiers=['License :: OSI Approved :: MIT License', 'Topic :: C...
from distutils.core import setup setup(name='Pyranha', description='Elegant IRC client', version='0.1', author='John Reese', author_email='john@noswap.com', url='https://github.com/jreese/pyranha', classifiers=['License :: OSI Approved :: MIT License', 'Topic :: C...
Install default dotfiles with package
Install default dotfiles with package
Python
mit
jreese/pyranha
from distutils.core import setup setup(name='Pyranha', description='Elegant IRC client', version='0.1', author='John Reese', author_email='john@noswap.com', url='https://github.com/jreese/pyranha', classifiers=['License :: OSI Approved :: MIT License', ...
Install default dotfiles with package
## Code Before: from distutils.core import setup setup(name='Pyranha', description='Elegant IRC client', version='0.1', author='John Reese', author_email='john@noswap.com', url='https://github.com/jreese/pyranha', classifiers=['License :: OSI Approved :: MIT License', ...
f56d8b35aa7d1d2c06d5c98ef49696e829459042
log_request_id/tests.py
log_request_id/tests.py
import logging from django.test import TestCase, RequestFactory from log_request_id.middleware import RequestIDMiddleware from testproject.views import test_view class RequestIDLoggingTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.handler = logging.getLogger('testprojec...
import logging from django.test import TestCase, RequestFactory from log_request_id.middleware import RequestIDMiddleware from testproject.views import test_view class RequestIDLoggingTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.handler = logging.getLogger('testprojec...
Add test for externally-generated request IDs
Add test for externally-generated request IDs
Python
bsd-2-clause
dabapps/django-log-request-id
import logging from django.test import TestCase, RequestFactory from log_request_id.middleware import RequestIDMiddleware from testproject.views import test_view class RequestIDLoggingTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.handler = logging...
Add test for externally-generated request IDs
## Code Before: import logging from django.test import TestCase, RequestFactory from log_request_id.middleware import RequestIDMiddleware from testproject.views import test_view class RequestIDLoggingTestCase(TestCase): def setUp(self): self.factory = RequestFactory() self.handler = logging.getLo...
1002f40dc0ca118308144d3a51b696815501519f
account_direct_debit/wizard/payment_order_create.py
account_direct_debit/wizard/payment_order_create.py
from openerp import models, api class PaymentOrderCreate(models.TransientModel): _inherit = 'payment.order.create' @api.multi def extend_payment_order_domain(self, payment_order, domain): super(PaymentOrderCreate, self).extend_payment_order_domain( payment_order, domain) if p...
from openerp import models, api class PaymentOrderCreate(models.TransientModel): _inherit = 'payment.order.create' @api.multi def extend_payment_order_domain(self, payment_order, domain): super(PaymentOrderCreate, self).extend_payment_order_domain( payment_order, domain) if p...
Fix move lines domain for direct debits
[FIX] account_direct_debit: Fix move lines domain for direct debits
Python
agpl-3.0
acsone/bank-payment,diagramsoftware/bank-payment,CompassionCH/bank-payment,CompassionCH/bank-payment,open-synergy/bank-payment,hbrunn/bank-payment
from openerp import models, api class PaymentOrderCreate(models.TransientModel): _inherit = 'payment.order.create' @api.multi def extend_payment_order_domain(self, payment_order, domain): super(PaymentOrderCreate, self).extend_payment_order_domain( payment_order...
Fix move lines domain for direct debits
## Code Before: from openerp import models, api class PaymentOrderCreate(models.TransientModel): _inherit = 'payment.order.create' @api.multi def extend_payment_order_domain(self, payment_order, domain): super(PaymentOrderCreate, self).extend_payment_order_domain( payment_order, doma...
989ff44354d624906d72f20aac933a9243214cf8
corehq/dbaccessors/couchapps/cases_by_server_date/by_owner_server_modified_on.py
corehq/dbaccessors/couchapps/cases_by_server_date/by_owner_server_modified_on.py
from __future__ import absolute_import from __future__ import unicode_literals from casexml.apps.case.models import CommCareCase from dimagi.utils.parsing import json_format_datetime def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date): """ Gets all cases with a specified owner ID that...
from __future__ import absolute_import from __future__ import unicode_literals from casexml.apps.case.models import CommCareCase from dimagi.utils.parsing import json_format_datetime def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date, until_date=None): """ Gets all cases with a specif...
Make get_case_ids_modified_with_owner_since accept an end date as well
Make get_case_ids_modified_with_owner_since accept an end date as well
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from __future__ import absolute_import from __future__ import unicode_literals from casexml.apps.case.models import CommCareCase from dimagi.utils.parsing import json_format_datetime - def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date): + def get_case_ids_modified_with_owner_sinc...
Make get_case_ids_modified_with_owner_since accept an end date as well
## Code Before: from __future__ import absolute_import from __future__ import unicode_literals from casexml.apps.case.models import CommCareCase from dimagi.utils.parsing import json_format_datetime def get_case_ids_modified_with_owner_since(domain, owner_id, reference_date): """ Gets all cases with a specifi...
16d65c211b00871ac7384baa3934d88410e2c977
tests/test_planetary_test_data_2.py
tests/test_planetary_test_data_2.py
from planetary_test_data import PlanetaryTestDataProducts import os def test_planetary_test_data_object(): """Tests simple PlanetaryTestDataProducts attributes.""" data = PlanetaryTestDataProducts() assert data.tags == ['core'] assert data.all_products is None # handle running this test individua...
from planetary_test_data import PlanetaryTestDataProducts import os def test_planetary_test_data_object(): """Tests simple PlanetaryTestDataProducts attributes.""" data = PlanetaryTestDataProducts() assert data.tags == ['core'] assert data.all_products is None # handle running this test individua...
Update test to account for more core products
Update test to account for more core products
Python
bsd-3-clause
pbvarga1/planetary_test_data,planetarypy/planetary_test_data
from planetary_test_data import PlanetaryTestDataProducts import os def test_planetary_test_data_object(): """Tests simple PlanetaryTestDataProducts attributes.""" data = PlanetaryTestDataProducts() assert data.tags == ['core'] assert data.all_products is None # handle runni...
Update test to account for more core products
## Code Before: from planetary_test_data import PlanetaryTestDataProducts import os def test_planetary_test_data_object(): """Tests simple PlanetaryTestDataProducts attributes.""" data = PlanetaryTestDataProducts() assert data.tags == ['core'] assert data.all_products is None # handle running thi...
1ee414611fa6e01516d545bb284695a62bd69f0a
rtrss/daemon.py
rtrss/daemon.py
import sys import os import logging import atexit from rtrss.basedaemon import BaseDaemon _logger = logging.getLogger(__name__) class WorkerDaemon(BaseDaemon): def run(self): _logger.info('Daemon started ith pid %d', os.getpid()) from rtrss.worker import app_init, worker_action w...
import os import logging from rtrss.basedaemon import BaseDaemon _logger = logging.getLogger(__name__) class WorkerDaemon(BaseDaemon): def run(self): _logger.info('Daemon started ith pid %d', os.getpid()) from rtrss.worker import worker_action worker_action('run') _logger.info...
Change debug action to production
Change debug action to production
Python
apache-2.0
notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss
- import sys import os import logging - import atexit + from rtrss.basedaemon import BaseDaemon + _logger = logging.getLogger(__name__) class WorkerDaemon(BaseDaemon): def run(self): _logger.info('Daemon started ith pid %d', os.getpid()) - + - from rtrss.worker imp...
Change debug action to production
## Code Before: import sys import os import logging import atexit from rtrss.basedaemon import BaseDaemon _logger = logging.getLogger(__name__) class WorkerDaemon(BaseDaemon): def run(self): _logger.info('Daemon started ith pid %d', os.getpid()) from rtrss.worker import app_init, worker_...
acdf380a5463ae8bd9c6dc76ce02069371b6f5fd
backend/restapp/restapp/urls.py
backend/restapp/restapp/urls.py
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]
from django.conf.urls import url, include from django.contrib import admin from books.models import Author, Book from rest_framework import routers, serializers, viewsets class AuthorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Author fields = ('first_name', 'last_name'...
Add simple serializers for books and authors
Add simple serializers for books and authors
Python
mit
TomaszGabrysiak/django-rest-angular-seed,TomaszGabrysiak/django-rest-angular-seed,TomaszGabrysiak/django-rest-angular-seed
from django.conf.urls import url, include from django.contrib import admin + from books.models import Author, Book + from rest_framework import routers, serializers, viewsets + + + class AuthorSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Author + fields = ('fi...
Add simple serializers for books and authors
## Code Before: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ] ## Instruction: Add simple serializers for books and authors ## Code After: from django...
a7908d39e24384881c30042e1b4c7e93e85eb38e
test/TestTaskIncludes.py
test/TestTaskIncludes.py
import os import unittest from ansiblelint import Runner, RulesCollection class TestTaskIncludes(unittest.TestCase): def setUp(self): rulesdir = os.path.join('lib', 'ansiblelint', 'rules') self.rules = RulesCollection.create_from_directory(rulesdir) def test_block_included_tasks(self): ...
import os import unittest from ansiblelint import Runner, RulesCollection class TestTaskIncludes(unittest.TestCase): def setUp(self): rulesdir = os.path.join('lib', 'ansiblelint', 'rules') self.rules = RulesCollection.create_from_directory(rulesdir) def test_block_included_tasks(self): ...
Add test that exercises block includes
Add test that exercises block includes
Python
mit
MatrixCrawler/ansible-lint,dataxu/ansible-lint,willthames/ansible-lint
import os import unittest from ansiblelint import Runner, RulesCollection class TestTaskIncludes(unittest.TestCase): def setUp(self): rulesdir = os.path.join('lib', 'ansiblelint', 'rules') self.rules = RulesCollection.create_from_directory(rulesdir) def test_block_inc...
Add test that exercises block includes
## Code Before: import os import unittest from ansiblelint import Runner, RulesCollection class TestTaskIncludes(unittest.TestCase): def setUp(self): rulesdir = os.path.join('lib', 'ansiblelint', 'rules') self.rules = RulesCollection.create_from_directory(rulesdir) def test_block_included_ta...
0ba063edc4aec690efca5c5ba9faf64042bb7707
demo/demo/urls.py
demo/demo/urls.py
from __future__ import unicode_literals from django.conf.urls import patterns, url from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \ DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView urlpatterns = [ url(r'^$', HomePageView.as_view(),...
from __future__ import unicode_literals from django.conf.urls import url from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \ DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='hom...
Remove obsolete import (removed in Django 1.10)
Remove obsolete import (removed in Django 1.10)
Python
bsd-3-clause
dyve/django-bootstrap3,dyve/django-bootstrap3,zostera/django-bootstrap4,zostera/django-bootstrap4
from __future__ import unicode_literals - from django.conf.urls import patterns, url + from django.conf.urls import url from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \ DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView url...
Remove obsolete import (removed in Django 1.10)
## Code Before: from __future__ import unicode_literals from django.conf.urls import patterns, url from .views import HomePageView, FormHorizontalView, FormInlineView, PaginationView, FormWithFilesView, \ DefaultFormView, MiscView, DefaultFormsetView, DefaultFormByFieldView urlpatterns = [ url(r'^$', HomePag...
faa67c81ad2ebb8ba8cb407982cbced72d1fa899
tests/test_config_tree.py
tests/test_config_tree.py
import pytest from pyhocon.config_tree import ConfigTree from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException class TestConfigParser(object): def test_config_tree_quoted_string(self): config_tree = ConfigTree() config_tree.put("a.b.c", "value") assert config_tre...
import pytest from pyhocon.config_tree import ConfigTree from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException class TestConfigParser(object): def test_config_tree_quoted_string(self): config_tree = ConfigTree() config_tree.put("a.b.c", "value") assert config_tre...
Add failing tests for iteration and logging config
Add failing tests for iteration and logging config
Python
apache-2.0
acx2015/pyhocon,chimpler/pyhocon,vamega/pyhocon,peoplepattern/pyhocon
import pytest from pyhocon.config_tree import ConfigTree from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException class TestConfigParser(object): def test_config_tree_quoted_string(self): config_tree = ConfigTree() config_tree.put("a.b.c", "value") ...
Add failing tests for iteration and logging config
## Code Before: import pytest from pyhocon.config_tree import ConfigTree from pyhocon.exceptions import ConfigMissingException, ConfigWrongTypeException class TestConfigParser(object): def test_config_tree_quoted_string(self): config_tree = ConfigTree() config_tree.put("a.b.c", "value") a...
d07a7ad25f69a18c57c50d6c32df212e1f987bd4
www/tests/test_collections.py
www/tests/test_collections.py
import collections _d=collections.defaultdict(int) _d['a']+=1 _d['a']+=2 _d['b']+=4 assert _d['a'] == 3 assert _d['b'] == 4 s = 'mississippi' for k in s: _d[k] += 1 _values=list(_d.values()) _values.sort() assert _values == [1, 2, 3, 4, 4, 4] _keys=list(_d.keys()) _keys.sort() assert _keys == ['a', 'b', 'i', ...
import collections _d=collections.defaultdict(int) _d['a']+=1 _d['a']+=2 _d['b']+=4 assert _d['a'] == 3 assert _d['b'] == 4 s = 'mississippi' for k in s: _d[k] += 1 _values=list(_d.values()) _values.sort() assert _values == [1, 2, 3, 4, 4, 4] _keys=list(_d.keys()) _keys.sort() assert _keys == ['a', 'b', 'i', ...
Add a test on namedtuple
Add a test on namedtuple
Python
bsd-3-clause
kikocorreoso/brython,Mozhuowen/brython,Hasimir/brython,Isendir/brython,Isendir/brython,amrdraz/brython,jonathanverner/brython,kevinmel2000/brython,brython-dev/brython,Mozhuowen/brython,jonathanverner/brython,Hasimir/brython,rubyinhell/brython,Hasimir/brython,molebot/brython,Isendir/brython,JohnDenker/brython,olemis/bry...
import collections _d=collections.defaultdict(int) _d['a']+=1 _d['a']+=2 _d['b']+=4 assert _d['a'] == 3 assert _d['b'] == 4 s = 'mississippi' for k in s: _d[k] += 1 _values=list(_d.values()) _values.sort() assert _values == [1, 2, 3, 4, 4, 4] _keys=list(_d.keys()) _ke...
Add a test on namedtuple
## Code Before: import collections _d=collections.defaultdict(int) _d['a']+=1 _d['a']+=2 _d['b']+=4 assert _d['a'] == 3 assert _d['b'] == 4 s = 'mississippi' for k in s: _d[k] += 1 _values=list(_d.values()) _values.sort() assert _values == [1, 2, 3, 4, 4, 4] _keys=list(_d.keys()) _keys.sort() assert _keys == ...
888584a49e697551c4f680cc8651be2fe80fc65d
configgen/generators/ppsspp/ppssppGenerator.py
configgen/generators/ppsspp/ppssppGenerator.py
import Command #~ import reicastControllers import recalboxFiles from generators.Generator import Generator import ppssppControllers import shutil import os.path import ConfigParser class PPSSPPGenerator(Generator): # Main entry of the module # Configure fba and return a command def generate(self, system,...
import Command #~ import reicastControllers import recalboxFiles from generators.Generator import Generator import ppssppControllers import shutil import os.path import ConfigParser class PPSSPPGenerator(Generator): # Main entry of the module # Configure fba and return a command def generate(self, system,...
Remove a bad typo from reicast
Remove a bad typo from reicast
Python
mit
nadenislamarre/recalbox-configgen,recalbox/recalbox-configgen,digitalLumberjack/recalbox-configgen
import Command #~ import reicastControllers import recalboxFiles from generators.Generator import Generator import ppssppControllers import shutil import os.path import ConfigParser class PPSSPPGenerator(Generator): # Main entry of the module # Configure fba and return a command ...
Remove a bad typo from reicast
## Code Before: import Command #~ import reicastControllers import recalboxFiles from generators.Generator import Generator import ppssppControllers import shutil import os.path import ConfigParser class PPSSPPGenerator(Generator): # Main entry of the module # Configure fba and return a command def genera...
cbdfc1b1cb4162256538576cabe2b6832aa83bca
django_mysqlpool/__init__.py
django_mysqlpool/__init__.py
from functools import wraps from django.db import connection def auto_close_db(f): "Ensures the database connection is closed when the function returns." @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() return wr...
from functools import wraps def auto_close_db(f): "Ensures the database connection is closed when the function returns." from django.db import connection @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close() retur...
Fix circular import when used with other add-ons that import django.db
Fix circular import when used with other add-ons that import django.db eg sorl_thumbnail: Traceback (most recent call last): File "/home/rpatterson/src/work/retrans/src/ReTransDjango/bin/manage", line 40, in <module> sys.exit(manage.main()) File "/home/rpatterson/src/work/retrans/src/ReTransDjango/retrans/mana...
Python
mit
smartfile/django-mysqlpool
from functools import wraps - from django.db import connection def auto_close_db(f): "Ensures the database connection is closed when the function returns." + from django.db import connection @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) ...
Fix circular import when used with other add-ons that import django.db
## Code Before: from functools import wraps from django.db import connection def auto_close_db(f): "Ensures the database connection is closed when the function returns." @wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) finally: connection.close...
0f7816676eceb42f13786408f1d1a09527919a1e
Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py
Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py
import numpy as np from msi.io.reader import Reader from msi.msi import Msi class SpectrometerReader(Reader): def __init__(self): pass def read(self, file_to_read): # our spectrometer like to follow german standards in files, we need # to switch to english ones transformed="...
import numpy as np from msi.io.reader import Reader from msi.msi import Msi class SpectrometerReader(Reader): def __init__(self): pass def read(self, file_to_read): # our spectrometer like to follow german standards in files, we need # to switch to english ones transformed="...
Change SpectrometerReader a little so it can handle more data formats.
Change SpectrometerReader a little so it can handle more data formats.
Python
bsd-3-clause
MITK/MITK,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,iwegner/MITK,fmilano/mitk,fmilano/mitk,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,MITK/MITK,RabadanLab/MITKats,RabadanLab/MITKats,fmilano/mitk,fmilano/mitk,iwegner/MITK,fmilano/mitk,MITK/MITK,iwegner/MITK,iwegner/MITK,MITK/MITK,MITK/MITK,...
import numpy as np from msi.io.reader import Reader from msi.msi import Msi class SpectrometerReader(Reader): def __init__(self): pass def read(self, file_to_read): # our spectrometer like to follow german standards in files, we need # to switch to englis...
Change SpectrometerReader a little so it can handle more data formats.
## Code Before: import numpy as np from msi.io.reader import Reader from msi.msi import Msi class SpectrometerReader(Reader): def __init__(self): pass def read(self, file_to_read): # our spectrometer like to follow german standards in files, we need # to switch to english ones ...
33a3ebacabda376826f0470129e8583e4974fd9d
examples/markdown/build.py
examples/markdown/build.py
import os import jinja2 # Markdown to HTML library # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): with open(template.filename) as f: markdown_content = f.read() return {'post_content...
import os # Markdown to HTML library # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): with open(template.filename) as f: markdown_content = f.read() return {'post_content_html': markdo...
Remove unneeded jinja2 import in markdown example
Remove unneeded jinja2 import in markdown example
Python
mit
Ceasar/staticjinja,Ceasar/staticjinja
import os - import jinja2 # Markdown to HTML library # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): with open(template.filename) as f: markdown_content = f.read() ...
Remove unneeded jinja2 import in markdown example
## Code Before: import os import jinja2 # Markdown to HTML library # https://pypi.org/project/Markdown/ import markdown from staticjinja import Site markdowner = markdown.Markdown(output_format="html5") def md_context(template): with open(template.filename) as f: markdown_content = f.read() retur...
c9735ce9ea330737cf47474ef420303c56a32873
apps/demos/admin.py
apps/demos/admin.py
from django.contrib import admin from .models import Submission class SubmissionAdmin(admin.ModelAdmin): list_display = ( 'title', 'creator', 'featured', 'hidden', 'tags', 'modified', ) admin.site.register(Submission, SubmissionAdmin)
from django.contrib import admin from .models import Submission class SubmissionAdmin(admin.ModelAdmin): list_display = ( 'title', 'creator', 'featured', 'hidden', 'tags', 'modified', ) list_editable = ( 'featured', 'hidden' ) admin.site.register(Submission, SubmissionAdmin)
Make featured and hidden flags editable from demo listing
Make featured and hidden flags editable from demo listing
Python
mpl-2.0
bluemini/kuma,openjck/kuma,hoosteeno/kuma,Elchi3/kuma,davehunt/kuma,anaran/kuma,robhudson/kuma,davidyezsetz/kuma,darkwing/kuma,anaran/kuma,chirilo/kuma,jezdez/kuma,yfdyh000/kuma,nhenezi/kuma,Elchi3/kuma,ronakkhunt/kuma,a2sheppy/kuma,groovecoder/kuma,SphinxKnight/kuma,escattone/kuma,jezdez/kuma,tximikel/kuma,a2sheppy/ku...
from django.contrib import admin from .models import Submission class SubmissionAdmin(admin.ModelAdmin): list_display = ( 'title', 'creator', 'featured', 'hidden', 'tags', 'modified', ) + list_editable = ( 'featured', 'hidden' ) admin.site.register(Submission, SubmissionAdmin)
Make featured and hidden flags editable from demo listing
## Code Before: from django.contrib import admin from .models import Submission class SubmissionAdmin(admin.ModelAdmin): list_display = ( 'title', 'creator', 'featured', 'hidden', 'tags', 'modified', ) admin.site.register(Submission, SubmissionAdmin) ## Instruction: Make featured and hidden flags editable fro...
b43e06dd5a80814e15ce20f50d683f0daaa19a93
addons/hr/models/hr_employee_base.py
addons/hr/models/hr_employee_base.py
from odoo import fields, models class HrEmployeeBase(models.AbstractModel): _name = "hr.employee.base" _description = "Basic Employee" _order = 'name' name = fields.Char() active = fields.Boolean("Active") department_id = fields.Many2one('hr.department', 'Department') job_id = fields.Man...
from odoo import fields, models class HrEmployeeBase(models.AbstractModel): _name = "hr.employee.base" _description = "Basic Employee" _order = 'name' name = fields.Char() active = fields.Boolean("Active") color = fields.Integer('Color Index', default=0) department_id = fields.Many2one('...
Add the color field to public employee
[FIX] hr: Add the color field to public employee The color field is necessary to be able to display some fields (many2many_tags) and used in the kanban views closes odoo/odoo#35216 Signed-off-by: Yannick Tivisse (yti) <yti@odoo.com> closes odoo/odoo#35462 Signed-off-by: Romain Libert (rli) <d3a53ea3f0d6ebbbf1eb843...
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
from odoo import fields, models class HrEmployeeBase(models.AbstractModel): _name = "hr.employee.base" _description = "Basic Employee" _order = 'name' name = fields.Char() active = fields.Boolean("Active") + color = fields.Integer('Color Index', default=0) departm...
Add the color field to public employee
## Code Before: from odoo import fields, models class HrEmployeeBase(models.AbstractModel): _name = "hr.employee.base" _description = "Basic Employee" _order = 'name' name = fields.Char() active = fields.Boolean("Active") department_id = fields.Many2one('hr.department', 'Department') job...
81a03d81ece17487f7b7296f524339a052d45a0d
src/gcf.py
src/gcf.py
def gcf(a, b): while b: a, b = b, a % b return a def xgcf(a, b): s1, s2 = 1, 0 t1, t2 = 0, 1 while b: q, r = divmod(a, b) a, b = b, r s2, s1 = s1 - q * s2, s2 t2, t1 = t1 - q * t2, t2 return a, s1, t1
def gcf(a, b): while b: a, b = b, a % b return a def xgcf(a, b): s1, s2 = 1, 0 t1, t2 = 0, 1 while b: q, r = divmod(a, b) a, b = b, r s2, s1 = s1 - q * s2, s2 t2, t1 = t1 - q * t2, t2 # Bézout's identity says: s1 * a + t1 * b == gcd(a, b) return a...
Add Bézout's identity into comments
Add Bézout's identity into comments
Python
mit
all3fox/algos-py
def gcf(a, b): while b: a, b = b, a % b return a def xgcf(a, b): s1, s2 = 1, 0 t1, t2 = 0, 1 while b: q, r = divmod(a, b) a, b = b, r s2, s1 = s1 - q * s2, s2 t2, t1 = t1 - q * t2, t2 + # Bézout's identity says: s1 * ...
Add Bézout's identity into comments
## Code Before: def gcf(a, b): while b: a, b = b, a % b return a def xgcf(a, b): s1, s2 = 1, 0 t1, t2 = 0, 1 while b: q, r = divmod(a, b) a, b = b, r s2, s1 = s1 - q * s2, s2 t2, t1 = t1 - q * t2, t2 return a, s1, t1 ## Instruction: Add Bézout's iden...
04df5c189d6d1760c692d1985faf558058e56eb2
flask_pagedown/__init__.py
flask_pagedown/__init__.py
from jinja2 import Markup from flask import current_app, request class _pagedown(object): def include_pagedown(self): if request.is_secure: protocol = 'https' else: protocol = 'http' return Markup(''' <script type="text/javascript" src="{0}://cdnjs.cloudflare.com/aja...
from jinja2 import Markup from flask import current_app, request class _pagedown(object): def include_pagedown(self): return Markup(''' <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Converter.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudfla...
Fix support for SSL for proxied sites, or otherwise uncertain situations
Fix support for SSL for proxied sites, or otherwise uncertain situations My particular situation is deployed through ElasticBeanstalk, proxying HTTPS to HTTP on the actual endpoints. This makes flask think that it is only running with http, not https
Python
mit
miguelgrinberg/Flask-PageDown,miguelgrinberg/Flask-PageDown
from jinja2 import Markup from flask import current_app, request class _pagedown(object): def include_pagedown(self): - if request.is_secure: - protocol = 'https' - else: - protocol = 'http' return Markup(''' - <script type="text/javascript" src="{0}://cd...
Fix support for SSL for proxied sites, or otherwise uncertain situations
## Code Before: from jinja2 import Markup from flask import current_app, request class _pagedown(object): def include_pagedown(self): if request.is_secure: protocol = 'https' else: protocol = 'http' return Markup(''' <script type="text/javascript" src="{0}://cdnjs.cl...
fc9fdd2115b46c71c36ba7d86f14395ac4cf1e3e
genome_designer/scripts/generate_coverage_data.py
genome_designer/scripts/generate_coverage_data.py
import os import subprocess from django.conf import settings from main.models import get_dataset_with_type from main.models import AlignmentGroup from main.models import Dataset from utils import generate_safe_filename_prefix_from_label def analyze_coverage(sample_alignment, output_dir): ref_genome_fasta_locat...
import os import subprocess from django.conf import settings from main.models import get_dataset_with_type from main.models import AlignmentGroup from main.models import Dataset from utils import generate_safe_filename_prefix_from_label def analyze_coverage(sample_alignment, output_dir): ref_genome_fasta_locat...
Update coverage script to only output the first 4 cols which shows coverage.
Update coverage script to only output the first 4 cols which shows coverage.
Python
mit
woodymit/millstone,woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,churchlab/millstone,woodymit/millstone,churchlab/millstone,churchlab/millstone,churchlab/millstone
import os import subprocess from django.conf import settings from main.models import get_dataset_with_type from main.models import AlignmentGroup from main.models import Dataset from utils import generate_safe_filename_prefix_from_label def analyze_coverage(sample_alignment, output_dir): ...
Update coverage script to only output the first 4 cols which shows coverage.
## Code Before: import os import subprocess from django.conf import settings from main.models import get_dataset_with_type from main.models import AlignmentGroup from main.models import Dataset from utils import generate_safe_filename_prefix_from_label def analyze_coverage(sample_alignment, output_dir): ref_ge...
e7bda027780da26183f84f7af5c50cd37649c76b
functional_tests/remote.py
functional_tests/remote.py
from unipath import Path import subprocess THIS_FOLDER = Path(__file__).parent def reset_database(host): subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host)], cwd=THIS_FOLDER) def create_user(host, user, email, password): subprocess.check_call(['fab', 'create_user:user={},passwo...
from unipath import Path import subprocess THIS_FOLDER = Path(__file__).parent def reset_database(host): subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host), '--hide=everything,status'], cwd=THIS_FOLDER) def create_user(host, user, email, password): subprocess.check_call...
Make running FTs against staging a bit less verbose
Make running FTs against staging a bit less verbose
Python
mit
XeryusTC/projman,XeryusTC/projman,XeryusTC/projman
from unipath import Path import subprocess THIS_FOLDER = Path(__file__).parent def reset_database(host): - subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host)], + subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host), + '--hide=everything,status']...
Make running FTs against staging a bit less verbose
## Code Before: from unipath import Path import subprocess THIS_FOLDER = Path(__file__).parent def reset_database(host): subprocess.check_call(['fab', 'reset_database', '--host={}'.format(host)], cwd=THIS_FOLDER) def create_user(host, user, email, password): subprocess.check_call(['fab', 'create_use...
4daefdb0a4def961572fc22d0fe01a394b11fad9
tests/test_httpclient.py
tests/test_httpclient.py
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on loc...
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be available on loc...
Test creation of HTTP credentials
tests.http: Test creation of HTTP credentials
Python
bsd-3-clause
ranjithlav/pyrabbit,bkjones/pyrabbit,NeCTAR-RC/pyrabbit,chaos95/pyrabbit,switchtower/pyrabbit
try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ managem...
Test creation of HTTP credentials
## Code Before: try: import unittest2 as unittest except ImportError: import unittest import sys sys.path.append('..') from pyrabbit import http class TestHTTPClient(unittest.TestCase): """ Except for the init test, these are largely functional tests that require a RabbitMQ management API to be ...
dbbd29a1cdfcd3f11a968c0aeb38bd54ef7014e3
gfusion/tests/test_main.py
gfusion/tests/test_main.py
"""Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_similarities = 3 delta = 0.3 similarities = np.random.random((n_simila...
"""Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from numpy.testing import assert_array_almost_equal from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_similarities = 3 delta...
Add a more semantic test
Add a more semantic test
Python
mit
mvdoc/gfusion
"""Tests for main.py""" from ..main import _solve_weight_vector import numpy as np + from numpy.testing import assert_array_almost_equal from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_si...
Add a more semantic test
## Code Before: """Tests for main.py""" from ..main import _solve_weight_vector import numpy as np from nose.tools import assert_raises, assert_equal, assert_true def test_solve_weight_vector(): # smoke test n_nodes = 4 n_communities = 2 n_similarities = 3 delta = 0.3 similarities = np.random....
55b7b07986590c4ab519fcda3c973c87ad23596b
flask_admin/model/typefmt.py
flask_admin/model/typefmt.py
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: ...
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :param value: ...
Add extra type formatter for `list` type
Add extra type formatter for `list` type
Python
bsd-3-clause
mrjoes/flask-admin,janusnic/flask-admin,Kha/flask-admin,wuxiangfeng/flask-admin,litnimax/flask-admin,HermasT/flask-admin,quokkaproject/flask-admin,Kha/flask-admin,flabe81/flask-admin,porduna/flask-admin,Junnplus/flask-admin,ibushong/test-repo,janusnic/flask-admin,jschneier/flask-admin,closeio/flask-admin,chase-seibert/...
from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` valu...
Add extra type formatter for `list` type
## Code Before: from jinja2 import Markup def null_formatter(value): """ Return `NULL` as the string for `None` value :param value: Value to check """ return Markup('<i>NULL</i>') def empty_formatter(value): """ Return empty string for `None` value :para...
ad757857b7878904c6d842e115074c4fac24bed7
tweetar.py
tweetar.py
import twitter import urllib2 NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT" def retrieve_and_post(conf): post = False pull_url = NOAA_URL.replace('*station_id*', conf['station']) request = urllib2.Request(pull_url, None) response = urllib2.urlopen(request)...
import twitter import urllib2 NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT" def retrieve_and_post(conf): post = False pull_url = NOAA_URL.replace('*station_id*', conf['station']) request = urllib2.Request(pull_url, None) response = urllib2.urlopen(request)...
Use .get instead of getattr, dummy.
Use .get instead of getattr, dummy.
Python
bsd-3-clause
adamfast/python-tweetar
import twitter import urllib2 NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT" def retrieve_and_post(conf): post = False pull_url = NOAA_URL.replace('*station_id*', conf['station']) request = urllib2.Request(pull_url, None) response = ur...
Use .get instead of getattr, dummy.
## Code Before: import twitter import urllib2 NOAA_URL = "http://weather.noaa.gov/pub/data/observations/metar/stations/*station_id*.TXT" def retrieve_and_post(conf): post = False pull_url = NOAA_URL.replace('*station_id*', conf['station']) request = urllib2.Request(pull_url, None) response = urllib2....
0461fad1a3d81aa2d937a1734f1ebb07b3e81d79
undercloud_heat_plugins/server_update_allowed.py
undercloud_heat_plugins/server_update_allowed.py
from heat.engine.resources.openstack.nova import server class ServerUpdateAllowed(server.Server): '''Prevent any properties changes from replacing an existing server. ''' update_allowed_properties = server.Server.properties_schema.keys() def resource_mapping(): return {'OS::Nova::Server': ServerU...
from heat.engine.resources.openstack.nova import server class ServerUpdateAllowed(server.Server): '''Prevent any properties changes from replacing an existing server. ''' update_allowed_properties = server.Server.properties_schema.keys() def needs_replace_with_prop_diff(self, changed_properties_se...
Fix no-replace-server to accurately preview update
Fix no-replace-server to accurately preview update This override of OS::Nova::Server needs to reflect the fact that it never replaces on update or the update --dry-run output ends up being wrong. Closes-Bug: 1561076 Change-Id: I9256872b877fbe7f91befb52995c62de006210ef
Python
apache-2.0
openstack/tripleo-common,openstack/tripleo-common
from heat.engine.resources.openstack.nova import server class ServerUpdateAllowed(server.Server): '''Prevent any properties changes from replacing an existing server. ''' update_allowed_properties = server.Server.properties_schema.keys() + def needs_replace_with_prop_diff(sel...
Fix no-replace-server to accurately preview update
## Code Before: from heat.engine.resources.openstack.nova import server class ServerUpdateAllowed(server.Server): '''Prevent any properties changes from replacing an existing server. ''' update_allowed_properties = server.Server.properties_schema.keys() def resource_mapping(): return {'OS::Nova::...
84a2aa1187cf7a9ec7593920d9ad0708b7d28f55
sqlobject/tests/test_pickle.py
sqlobject/tests/test_pickle.py
import pickle from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Pickle instances ######################################## class TestPickle(SQLObject): question = StringCol() answer = IntCol() test_question = 'The Ulimate Question of Life, the Universe an...
import pickle from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Pickle instances ######################################## class TestPickle(SQLObject): question = StringCol() answer = IntCol() test_question = 'The Ulimate Question of Life, the Universe an...
Fix flake8 E113 unexpected indentation
Fix flake8 E113 unexpected indentation
Python
lgpl-2.1
drnlm/sqlobject,sqlobject/sqlobject,sqlobject/sqlobject,drnlm/sqlobject
import pickle from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Pickle instances ######################################## class TestPickle(SQLObject): question = StringCol() answer = IntCol() test_question = 'The Ulimate Questio...
Fix flake8 E113 unexpected indentation
## Code Before: import pickle from sqlobject import * from sqlobject.tests.dbtest import * ######################################## ## Pickle instances ######################################## class TestPickle(SQLObject): question = StringCol() answer = IntCol() test_question = 'The Ulimate Question of Life,...
2e9a6a2babb16f4ed9c3367b21ee28514d1988a8
srm/__main__.py
srm/__main__.py
import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) if __name__ == '__main__': cli()
import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) cli(prog_name='srm')
Set correct program name in 'help' output
Set correct program name in 'help' output
Python
mit
cmcginty/simple-rom-manager,cmcginty/simple-rom-manager
import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) + cli(prog_name='srm') - if __name__ == '__main__': - cli() -
Set correct program name in 'help' output
## Code Before: import click from . import __version__, status @click.group() @click.version_option(__version__) def cli() -> None: """Main command-line entry method.""" cli.add_command(status.cli) if __name__ == '__main__': cli() ## Instruction: Set correct program name in 'help' output ## Code After: ...
e54d753a3fb58032936cbf5e137bb5ef67e2813c
task_15.py
task_15.py
"""Provides variables for string and integer conversion.""" NOT_THE_QUESTION = 'The answer to life, the universe, and everything? It\'s ' ANSWER = 42
"""Provides variables for string and integer conversion.""" NOT_THE_QUESTION = 'The answer to life, the universe, and everything? It\'s ' ANSWER = 42 THANKS_FOR_THE_FISH = str(NOT_THE_QUESTION) + str(ANSWER)
Change the string to concatenate it by using str() and then make new variable equal the first str() to the second str()
Change the string to concatenate it by using str() and then make new variable equal the first str() to the second str()
Python
mpl-2.0
gracehyemin/is210-week-03-warmup,gracehyemin/is210-week-03-warmup
"""Provides variables for string and integer conversion.""" NOT_THE_QUESTION = 'The answer to life, the universe, and everything? It\'s ' ANSWER = 42 + THANKS_FOR_THE_FISH = str(NOT_THE_QUESTION) + str(ANSWER)
Change the string to concatenate it by using str() and then make new variable equal the first str() to the second str()
## Code Before: """Provides variables for string and integer conversion.""" NOT_THE_QUESTION = 'The answer to life, the universe, and everything? It\'s ' ANSWER = 42 ## Instruction: Change the string to concatenate it by using str() and then make new variable equal the first str() to the second str() ## Code After: ...
6c2dae9bad86bf3f40d892eba50853d704f696b7
pombola/settings/tests.py
pombola/settings/tests.py
from .base import * COUNTRY_APP = None INSTALLED_APPS = INSTALLED_APPS + \ ('pombola.hansard', 'pombola.projects', 'pombola.place_data', 'pombola.votematch', 'speeches', 'pombola.spinner' ) + \ ...
from .base import * COUNTRY_APP = None INSTALLED_APPS = INSTALLED_APPS + \ ('pombola.hansard', 'pombola.projects', 'pombola.place_data', 'pombola.votematch', 'speeches', 'pombola.spinner', 'pom...
Make sure that the interests_register tables are created
Make sure that the interests_register tables are created Nose tries to run the interests_register tests, but they will fail unless the interest_register app is added to INSTALLED_APPS, because its tables won't be created in the test database.
Python
agpl-3.0
patricmutwiri/pombola,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,hzj123/56th,patricmutwiri/pombola,hzj123/56th,ken-muturi/pombola,ken-muturi/pombola,geoffkilpin/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombo...
from .base import * COUNTRY_APP = None INSTALLED_APPS = INSTALLED_APPS + \ ('pombola.hansard', 'pombola.projects', 'pombola.place_data', 'pombola.votematch', 'speeches', - 'pombola.spinner' )...
Make sure that the interests_register tables are created
## Code Before: from .base import * COUNTRY_APP = None INSTALLED_APPS = INSTALLED_APPS + \ ('pombola.hansard', 'pombola.projects', 'pombola.place_data', 'pombola.votematch', 'speeches', 'pombola.spinner' ) + \ ...
a5ce35c44938d37aa9727d37c0cbe0232b8e92d3
socializr/management/commands/socializr_update.py
socializr/management/commands/socializr_update.py
''' Main command which is meant to be run daily to get the information from various social networks into the local db. ''' import traceback from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ImproperlyConfigured from socializr.base import get_socializr_configs clas...
''' Main command which is meant to be run daily to get the information from various social networks into the local db. ''' import traceback from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ImproperlyConfigured from socializr.base import get_socializr_configs clas...
Remove output expect when there is an error.
Remove output expect when there is an error.
Python
mit
CIGIHub/django-socializr,albertoconnor/django-socializr
''' Main command which is meant to be run daily to get the information from various social networks into the local db. ''' import traceback from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ImproperlyConfigured from socializr.base import get_so...
Remove output expect when there is an error.
## Code Before: ''' Main command which is meant to be run daily to get the information from various social networks into the local db. ''' import traceback from django.core.management.base import BaseCommand, CommandError from django.core.exceptions import ImproperlyConfigured from socializr.base import get_socializ...
c8a41bbf11538dbc17de12e32ba5af5e93fd0b2c
src/utils/plugins.py
src/utils/plugins.py
from utils import models class Plugin: plugin_name = None display_name = None description = None author = None short_name = None stage = None manager_url = None version = None janeway_version = None is_workflow_plugin = False jump_url = None handshake_url = None ...
from utils import models class Plugin: plugin_name = None display_name = None description = None author = None short_name = None stage = None manager_url = None version = None janeway_version = None is_workflow_plugin = False jump_url = None handshake_url = None ...
Add get_self and change get_or_create to avoid mis-creation.
Add get_self and change get_or_create to avoid mis-creation.
Python
agpl-3.0
BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway,BirkbeckCTP/janeway
from utils import models class Plugin: plugin_name = None display_name = None description = None author = None short_name = None stage = None manager_url = None version = None janeway_version = None is_workflow_plugin = False jump_url ...
Add get_self and change get_or_create to avoid mis-creation.
## Code Before: from utils import models class Plugin: plugin_name = None display_name = None description = None author = None short_name = None stage = None manager_url = None version = None janeway_version = None is_workflow_plugin = False jump_url = None handshake...
c5671ab2e5115ce9c022a97a088300dc408e2aa4
opendc/util/path_parser.py
opendc/util/path_parser.py
import json import sys import re def parse(version, endpoint_path): """Map an HTTP call to an API path""" with open('opendc/api/{}/paths.json'.format(version)) as paths_file: paths = json.load(paths_file) endpoint_path_parts = endpoint_path.split('/') paths_parts = [x.split('/') for x in ...
import json import sys import re def parse(version, endpoint_path): """Map an HTTP endpoint path to an API path""" with open('opendc/api/{}/paths.json'.format(version)) as paths_file: paths = json.load(paths_file) endpoint_path_parts = endpoint_path.strip('/').split('/') paths_parts = [x....
Make path parser robust to trailing /
Make path parser robust to trailing /
Python
mit
atlarge-research/opendc-web-server,atlarge-research/opendc-web-server
import json import sys import re def parse(version, endpoint_path): - """Map an HTTP call to an API path""" + """Map an HTTP endpoint path to an API path""" with open('opendc/api/{}/paths.json'.format(version)) as paths_file: paths = json.load(paths_file) - endpoint_path...
Make path parser robust to trailing /
## Code Before: import json import sys import re def parse(version, endpoint_path): """Map an HTTP call to an API path""" with open('opendc/api/{}/paths.json'.format(version)) as paths_file: paths = json.load(paths_file) endpoint_path_parts = endpoint_path.split('/') paths_parts = [x.spli...
87844a776c2d409bdf7eaa99da06d07d77d7098e
tests/test_gingerit.py
tests/test_gingerit.py
import pytest from gingerit.gingerit import GingerIt @pytest.mark.parametrize("text,expected", [ ( "The smelt of fliwers bring back memories.", "The smell of flowers brings back memories." ), ( "Edwards will be sck yesterday", "Edwards was sick yesterday" ), ( ...
import pytest from gingerit.gingerit import GingerIt @pytest.mark.parametrize("text,expected,corrections", [ ( "The smelt of fliwers bring back memories.", "The smell of flowers brings back memories.", [ {'start': 21, 'definition': None, 'correct': u'brings', 'text': 'bring'},...
Extend test to cover corrections output
Extend test to cover corrections output
Python
mit
Azd325/gingerit
import pytest from gingerit.gingerit import GingerIt - @pytest.mark.parametrize("text,expected", [ + @pytest.mark.parametrize("text,expected,corrections", [ ( "The smelt of fliwers bring back memories.", - "The smell of flowers brings back memories." + "The smell of flowers ...
Extend test to cover corrections output
## Code Before: import pytest from gingerit.gingerit import GingerIt @pytest.mark.parametrize("text,expected", [ ( "The smelt of fliwers bring back memories.", "The smell of flowers brings back memories." ), ( "Edwards will be sck yesterday", "Edwards was sick yesterday" ...
c823a476b265b46d27b221831be952a811fe3468
ANN.py
ANN.py
class Neuron: pass class NeuronNetwork: neurons = []
class Neuron: pass class NeuronNetwork: neurons = [] def __init__(self, rows, columns): self.neurons = [] for row in xrange(rows): self.neurons.append([]) for column in xrange(columns): self.neurons[row].append(Neuron())
Create 2D list of Neurons in NeuronNetwork's init
Create 2D list of Neurons in NeuronNetwork's init
Python
mit
tysonzero/py-ann
class Neuron: pass class NeuronNetwork: neurons = [] + def __init__(self, rows, columns): + self.neurons = [] + for row in xrange(rows): + self.neurons.append([]) + for column in xrange(columns): + self.neurons[row].append(Neuron()) +
Create 2D list of Neurons in NeuronNetwork's init
## Code Before: class Neuron: pass class NeuronNetwork: neurons = [] ## Instruction: Create 2D list of Neurons in NeuronNetwork's init ## Code After: class Neuron: pass class NeuronNetwork: neurons = [] def __init__(self, rows, columns): self.neurons = [] for row in xrange(rows):...
168937c586b228c05ada2da79a55c9416c3180d3
antifuzz.py
antifuzz.py
''' File: antifuzz.py Authors: Kaitlin Keenan and Ryan Frank ''' import sys from shutil import copy2 import subprocess import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html def main(): # Take in file ogFile = sys.argv[1] # Make copy of file newFile = sys.argv[2] # Mess with the giv...
''' File: antifuzz.py Authors: Kaitlin Keenan and Ryan Frank ''' import sys from shutil import copy2 import subprocess import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument("originalFile", help="File to a...
Add help, make output more user friendly
Add help, make output more user friendly
Python
mit
ForensicTools/antifuzzyhashing-475-2161_Keenan_Frank
''' File: antifuzz.py Authors: Kaitlin Keenan and Ryan Frank ''' import sys from shutil import copy2 import subprocess import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html + import argparse def main(): + parser = argparse.ArgumentParser() + parser.add_argume...
Add help, make output more user friendly
## Code Before: ''' File: antifuzz.py Authors: Kaitlin Keenan and Ryan Frank ''' import sys from shutil import copy2 import subprocess import ssdeep #http://python-ssdeep.readthedocs.io/en/latest/installation.html def main(): # Take in file ogFile = sys.argv[1] # Make copy of file newFile = sys.argv[2] # M...
ee81d8966a5ef68edd6bb4459fc015234d6e0814
setup.py
setup.py
"""Open-ovf installer""" import os from distutils.core import setup CODE_BASE_DIR = 'py' SCRIPTS_DIR = 'py/scripts/' def list_scripts(): """List all scripts that should go to /usr/bin""" file_list = os.listdir(SCRIPTS_DIR) return [os.path.join(SCRIPTS_DIR, f) for f in file_list] setup(name='open-ovf', ...
"""Open-ovf installer""" import os from distutils.core import setup CODE_BASE_DIR = 'py' SCRIPTS_DIR = 'py/scripts/' def list_scripts(): """List all scripts that should go to /usr/bin""" file_list = os.listdir(SCRIPTS_DIR) return [os.path.join(SCRIPTS_DIR, f) for f in file_list] setup(name='open-ovf', ...
Add env subdirectory to package list
Add env subdirectory to package list Hi, This patch adds the ovf/env subdirectory to the package list so that setup.py installs it properly. Signed-off-by: David L. Leskovec <376f07f909b7d4aee248a1433ee4548cc2bf1d1b@linux.vnet.ibm.com> Signed-off-by: Scott Moser <f411aed5b71f5ab75e7f202cdde1f0f4410975aa@linux.vnet.i...
Python
epl-1.0
Awingu/open-ovf,Awingu/open-ovf,Awingu/open-ovf,Awingu/open-ovf
"""Open-ovf installer""" import os from distutils.core import setup CODE_BASE_DIR = 'py' SCRIPTS_DIR = 'py/scripts/' def list_scripts(): """List all scripts that should go to /usr/bin""" file_list = os.listdir(SCRIPTS_DIR) return [os.path.join(SCRIPTS_DIR, f) for f in file_list...
Add env subdirectory to package list
## Code Before: """Open-ovf installer""" import os from distutils.core import setup CODE_BASE_DIR = 'py' SCRIPTS_DIR = 'py/scripts/' def list_scripts(): """List all scripts that should go to /usr/bin""" file_list = os.listdir(SCRIPTS_DIR) return [os.path.join(SCRIPTS_DIR, f) for f in file_list] setup(n...
20764887bc338c2cd366ad11fb41d8932c2326a2
bot.py
bot.py
import json import discord from handlers.message_handler import MessageHandler with open("config.json", "r") as f: config = json.load(f) client = discord.Client() message_handler = MessageHandler(config, client) @client.event async def on_ready(): print("Logged in as", client.user.name) @client.event async def ...
import argparse import json import discord from handlers.message_handler import MessageHandler def main(): p = argparse.ArgumentParser() p.add_argument("--config", required=True, help="Path to configuration file") args = p.parse_args() with open(args.config, "r") as f: config = json.load(f) client = discord...
Add --config argument as a path to the config file
Add --config argument as a path to the config file
Python
mit
azeier/hearthbot
+ + import argparse import json import discord from handlers.message_handler import MessageHandler + def main(): + p = argparse.ArgumentParser() + p.add_argument("--config", required=True, help="Path to configuration file") + args = p.parse_args() + - with open("config.json", "r") as f: + with open(ar...
Add --config argument as a path to the config file
## Code Before: import json import discord from handlers.message_handler import MessageHandler with open("config.json", "r") as f: config = json.load(f) client = discord.Client() message_handler = MessageHandler(config, client) @client.event async def on_ready(): print("Logged in as", client.user.name) @client....
a2fb1efc918e18bb0ecebce4604192b03af662b2
fib.py
fib.py
def fibrepr(n): fibs = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] def fib_iter(n, fibs, l): for i, f in enumerate(fibs): if f == n: yield '1' + i*'0' + l elif n > f: for fib in fib_iter(n - f, fibs[i+1:], '1' + i*'0' + l): yield fib ...
class Fibonacci(object): _cache = {0: 1, 1: 2} def __init__(self, n): self.n = n def get(self, n): if not n in Fibonacci._cache: Fibonacci._cache[n] = self.get(n-1) + self.get(n-2) return Fibonacci._cache[n] def next(self): return Fibonacci(self.n + 1) ...
Add Fibonacci class and use it in representation
Add Fibonacci class and use it in representation
Python
mit
kynan/CodeDojo30
+ class Fibonacci(object): + _cache = {0: 1, 1: 2} + + def __init__(self, n): + self.n = n + + def get(self, n): + if not n in Fibonacci._cache: + Fibonacci._cache[n] = self.get(n-1) + self.get(n-2) + return Fibonacci._cache[n] + + def next(self): + return ...
Add Fibonacci class and use it in representation
## Code Before: def fibrepr(n): fibs = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] def fib_iter(n, fibs, l): for i, f in enumerate(fibs): if f == n: yield '1' + i*'0' + l elif n > f: for fib in fib_iter(n - f, fibs[i+1:], '1' + i*'0' + l): ...
57f3bec127148c80a9304194e5c3c8a3d3f3bae2
tests/scoring_engine/web/views/test_scoreboard.py
tests/scoring_engine/web/views/test_scoreboard.py
from tests.scoring_engine.web.web_test import WebTest class TestScoreboard(WebTest): def test_home(self): # todo fix this up!!!! # resp = self.client.get('/scoreboard') # assert resp.status_code == 200 # lazy AF assert 1 == 1
from tests.scoring_engine.web.web_test import WebTest from tests.scoring_engine.helpers import populate_sample_data class TestScoreboard(WebTest): def test_scoreboard(self): populate_sample_data(self.session) resp = self.client.get('/scoreboard') assert resp.status_code == 200 ass...
Add tests for scoreboard view
Add tests for scoreboard view
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
from tests.scoring_engine.web.web_test import WebTest + from tests.scoring_engine.helpers import populate_sample_data class TestScoreboard(WebTest): - def test_home(self): + def test_scoreboard(self): - # todo fix this up!!!! + populate_sample_data(self.session) - # resp = s...
Add tests for scoreboard view
## Code Before: from tests.scoring_engine.web.web_test import WebTest class TestScoreboard(WebTest): def test_home(self): # todo fix this up!!!! # resp = self.client.get('/scoreboard') # assert resp.status_code == 200 # lazy AF assert 1 == 1 ## Instruction: Add tests for ...
ebac72a3753205d3e45041c6db636a378187e3cf
pylua/tests/test_compiled.py
pylua/tests/test_compiled.py
import os import subprocess from pylua.tests.helpers import test_file class TestCompiled(object): """ Tests compiled binary """ def test_addition(self, capsys): f = test_file(src=""" -- short add x = 10 y = 5 z = y + y + x print(z) ...
import os import subprocess from pylua.tests.helpers import test_file class TestCompiled(object): """ Tests compiled binary """ PYLUA_BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), ('../../bin/pylua')) def test_addition(self, capsys): f = test_file(src=""" --...
Use absolute path for lua binary in tests
Use absolute path for lua binary in tests
Python
bsd-3-clause
fhahn/luna,fhahn/luna
import os import subprocess from pylua.tests.helpers import test_file class TestCompiled(object): """ Tests compiled binary """ + + PYLUA_BIN = os.path.join(os.path.dirname(os.path.abspath(__file__)), ('../../bin/pylua')) def test_addition(self, capsys): f = te...
Use absolute path for lua binary in tests
## Code Before: import os import subprocess from pylua.tests.helpers import test_file class TestCompiled(object): """ Tests compiled binary """ def test_addition(self, capsys): f = test_file(src=""" -- short add x = 10 y = 5 z = y + y + x ...
5577b2a20a98aa232f5591a46269e5ee6c88070d
MyMoment.py
MyMoment.py
import datetime #Humanize time in milliseconds #Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time def HTM(aa): a = int(aa) b = int(datetime.datetime.now().strftime("%s")) c = b - a days = c // 86400 hours = c // 3600 % 24 minu...
import datetime from time import gmtime, strftime import pytz #Humanize time in milliseconds #Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time #http://www.epochconverter.com/ #1/6/2015, 8:19:34 AM PST -> 23 hours ago #print HTM(1420561174000/1000) ...
Add functions to generate timestamp for logfiles & filenames; use localtimezone
Add functions to generate timestamp for logfiles & filenames; use localtimezone
Python
mit
harishvc/githubanalytics,harishvc/githubanalytics,harishvc/githubanalytics
import datetime + from time import gmtime, strftime + import pytz #Humanize time in milliseconds #Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time + #http://www.epochconverter.com/ + #1/6/2015, 8:19:34 AM PST -> 23 hours ago + #print HTM(14...
Add functions to generate timestamp for logfiles & filenames; use localtimezone
## Code Before: import datetime #Humanize time in milliseconds #Reference: http://stackoverflow.com/questions/26276906/python-convert-seconds-from-epoch-time-into-human-readable-time def HTM(aa): a = int(aa) b = int(datetime.datetime.now().strftime("%s")) c = b - a days = c // 86400 hours = c // 36...
5cf17b6a46a3d4bbf4cecb65e4b9ef43066869d9
feincms/templatetags/applicationcontent_tags.py
feincms/templatetags/applicationcontent_tags.py
from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_region_appcontent(pa...
from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_region_appcontent(pa...
Use all_of_type instead of isinstance check in feincms_render_region_appcontent
Use all_of_type instead of isinstance check in feincms_render_region_appcontent
Python
bsd-3-clause
feincms/feincms,joshuajonah/feincms,feincms/feincms,matthiask/feincms2-content,matthiask/django-content-editor,michaelkuty/feincms,mjl/feincms,matthiask/feincms2-content,mjl/feincms,matthiask/django-content-editor,matthiask/django-content-editor,michaelkuty/feincms,nickburlett/feincms,matthiask/django-content-editor,jo...
from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms...
Use all_of_type instead of isinstance check in feincms_render_region_appcontent
## Code Before: from django import template # backwards compatibility import from feincms.templatetags.fragment_tags import fragment, get_fragment, has_fragment register = template.Library() register.tag(fragment) register.tag(get_fragment) register.filter(has_fragment) @register.simple_tag def feincms_render_regi...