commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
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 | ---
+++
@@ -9,6 +9,7 @@
def setUp(self):
self.factory = RequestFactory()
self.handler = logging.getLogger('testproject').handlers[0]
+ self.handler.messages = []
def test_id_generation(self):
request = self.factory.get('/')
@@ -17,3 +18,13 @@
self.assertTrue(hasa... |
1002f40dc0ca118308144d3a51b696815501519f | account_direct_debit/wizard/payment_order_create.py | account_direct_debit/wizard/payment_order_create.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 Therp BV (<http://therp.nl>).
#
# All other contributions are (C) by their respective contributors
#
# All Rights Reserved
#
# This program is free software: you can redistribute it ... | # -*- coding: utf-8 -*-
# © 2013 Therp BV (<http://therp.nl>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, api
class PaymentOrderCreate(models.TransientModel):
_inherit = 'payment.order.create'
@api.multi
def extend_payment_order_domain(self, payment_o... | 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 | ---
+++
@@ -1,26 +1,6 @@
# -*- coding: utf-8 -*-
-##############################################################################
-#
-# Copyright (C) 2013 Therp BV (<http://therp.nl>).
-#
-# All other contributions are (C) by their respective contributors
-#
-# All Rights Reserved
-#
-# This program is fr... |
45f0cd033938a5c28907e84fcbc8f5f8e93d0c65 | st2actions/st2actions/cmd/history.py | st2actions/st2actions/cmd/history.py | import eventlet
import os
import sys
from oslo.config import cfg
from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2actions import config
from st2actions import history
LOG = logging.getLogger(__name__)
eventlet.monkey_patch(
os=Tr... | import eventlet
import os
import sys
from oslo.config import cfg
from st2common import log as logging
from st2common.models.db import db_setup
from st2common.models.db import db_teardown
from st2actions import config
from st2actions import history
LOG = logging.getLogger(__name__)
eventlet.monkey_patch(
os=Tr... | Move code from _run_worker into main | Move code from _run_worker into main
| Python | apache-2.0 | dennybaa/st2,grengojbo/st2,pinterb/st2,alfasin/st2,jtopjian/st2,peak6/st2,nzlosh/st2,punalpatel/st2,armab/st2,StackStorm/st2,nzlosh/st2,peak6/st2,alfasin/st2,Plexxi/st2,StackStorm/st2,emedvedev/st2,nzlosh/st2,pixelrebel/st2,Plexxi/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,tonybaloney/st2,pixelrebel/st2,StackStorm/st2,d... | ---
+++
@@ -33,17 +33,6 @@
db_setup(cfg.CONF.database.db_name, cfg.CONF.database.host, cfg.CONF.database.port)
-def _run_worker():
- LOG.info('(PID=%s) History worker started.', os.getpid())
- try:
- history.work()
- except (KeyboardInterrupt, SystemExit):
- LOG.info('(PID=%s) History ... |
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 | ---
+++
@@ -4,7 +4,7 @@
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_since(domain, owner_id, reference_date, until_date=None):
"""
Gets all cases with a specified owner ID that ... |
16d65c211b00871ac7384baa3934d88410e2c977 | tests/test_planetary_test_data_2.py | tests/test_planetary_test_data_2.py | # -*- coding: utf-8 -*-
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 run... | # -*- coding: utf-8 -*-
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 run... | 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 | ---
+++
@@ -23,6 +23,10 @@
assert data.tags == ['core']
assert u'2p129641989eth0361p2600r8m1.img' in data.products
assert u'1p190678905erp64kcp2600l8c1.img' in data.products
+ assert u'0047MH0000110010100214C00_DRCL.IMG' in data.products
+ assert u'1p134482118erp0902p2600r8m1.img' in data.product... |
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 | ---
+++
@@ -1,8 +1,8 @@
-import sys
import os
import logging
-import atexit
+
from rtrss.basedaemon import BaseDaemon
+
_logger = logging.getLogger(__name__)
@@ -10,10 +10,10 @@
class WorkerDaemon(BaseDaemon):
def run(self):
_logger.info('Daemon started ith pid %d', os.getpid())
-
- ... |
7ab9f281bf891e00d97278e3dba73eaeffe3799a | kaggle/titanic/categorical_and_scaler_prediction.py | kaggle/titanic/categorical_and_scaler_prediction.py | import pandas
def main():
train_all = pandas.DataFrame.from_csv('train.csv')
train = train_all[['Survived', 'Sex', 'Fare']]
print(train)
if __name__ == '__main__':
main()
| import pandas
from sklearn.naive_bayes import MultinomialNB
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelEncoder
def main():
train_all = pandas.DataFrame.from_csv('train.csv')
train = train_all[['Survived', 'Sex', 'Fare']][:20]
gender_label = LabelEncoder()... | Make predictions with gender and ticket price | Make predictions with gender and ticket price
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit | ---
+++
@@ -1,10 +1,25 @@
import pandas
+from sklearn.naive_bayes import MultinomialNB
+from sklearn.cross_validation import train_test_split
+from sklearn.preprocessing import LabelEncoder
def main():
train_all = pandas.DataFrame.from_csv('train.csv')
- train = train_all[['Survived', 'Sex', 'Fare']]
- ... |
9a4d608471b31550038d8ce43f6515bbb330e68a | tests.py | tests.py | import tcpstat | #!/usr/bin/python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2014 Ivan Cai
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limit... | Fix build failed on scrutinizer-ci | Fix build failed on scrutinizer-ci
| Python | mit | caizixian/tcpstat,caizixian/tcpstat | ---
+++
@@ -1 +1,26 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+# The MIT License (MIT)
+
+# Copyright (c) 2014 Ivan Cai
+
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without r... |
4d9ae9a8041d56b0494fd94d7a14fead82a2e536 | templated_email/utils.py | templated_email/utils.py |
# From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
from django.template import Context
from django.template.loader_tags import BlockNode, ExtendsNode
class BlockNotFound(Exception):
pass
def _iter_nodes(template, context, name, block_lookups):
for node in templat... |
# From http://stackoverflow.com/questions/2687173/django-how-can-i-get-a-block-from-a-template
from django.template import Context
from django.template.loader_tags import BlockNode, ExtendsNode
class BlockNotFound(Exception):
pass
def _iter_nodes(template, context, name, block_lookups):
for node in templat... | Change xrange for range for py3 | Change xrange for range for py3
| Python | mit | mypebble/django-templated-email,mypebble/django-templated-email | ---
+++
@@ -12,7 +12,7 @@
for node in template.template.nodelist:
if isinstance(node, BlockNode) and node.name == name:
# Rudimentary handling of extended templates, for issue #3
- for i in xrange(len(node.nodelist)):
+ for i in range(len(node.nodelist)):
... |
72125d84bf91201e15a93acb60fbc8f59af9aae8 | plugins/PerObjectSettingsTool/PerObjectSettingsTool.py | plugins/PerObjectSettingsTool/PerObjectSettingsTool.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super()._... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
from UM.Qt.ListModel import ListModel
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
... | Fix problem with casting to QVariant | Fix problem with casting to QVariant
This is a magical fix that Nallath and I found for a problem that shouldn't exist in the first place and sometimes doesn't exist at all and in the same time is a superposition of existing and not existing and it's all very complicated and an extremely weird hack. Casting this objec... | Python | agpl-3.0 | hmflash/Cura,senttech/Cura,senttech/Cura,ynotstartups/Wanhao,ynotstartups/Wanhao,fieldOfView/Cura,fieldOfView/Cura,totalretribution/Cura,totalretribution/Cura,Curahelper/Cura,Curahelper/Cura,hmflash/Cura | ---
+++
@@ -4,12 +4,14 @@
from UM.Tool import Tool
from UM.Scene.Selection import Selection
from UM.Application import Application
+from UM.Qt.ListModel import ListModel
from . import PerObjectSettingsModel
class PerObjectSettingsTool(Tool):
def __init__(self):
super().__init__()
+ self.... |
acdf380a5463ae8bd9c6dc76ce02069371b6f5fd | backend/restapp/restapp/urls.py | backend/restapp/restapp/urls.py | """restapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | """restapp URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | 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 | ---
+++
@@ -16,7 +16,40 @@
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
+ ... |
a42bc9cfc862fd91a498b2738caabf7ca945168b | Pig-Latin/pig_latin.py | Pig-Latin/pig_latin.py | class Pig_latin(object):
vowels = ["a", "e" , "i", "o", "u"]
def __init__(self, sentence):
self.sentence = sentence
def convert_sentence(self):
new_sentence = self.sentence.split(" ")
for word in new_sentence:
counter = 0
if word[0] in self.vowels:
continue
for letter in w... | Add initial setup for solution | Add initial setup for solution
| Python | mit | Bigless27/Python-Projects | ---
+++
@@ -0,0 +1,24 @@
+class Pig_latin(object):
+ vowels = ["a", "e" , "i", "o", "u"]
+
+
+ def __init__(self, sentence):
+ self.sentence = sentence
+
+ def convert_sentence(self):
+ new_sentence = self.sentence.split(" ")
+ for word in new_sentence:
+ counter = 0
+ if word[0] in self.vowels:... | |
90265098d21fa900a4a2d86719efc95c352812f4 | mopidy_somafm/__init__.py | mopidy_somafm/__init__.py | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.3.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-SomaFM'
ext_name = 'somafm'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'e... | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '0.3.0'
class Extension(ext.Extension):
dist_name = 'Mopidy-SomaFM'
ext_name = 'somafm'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.dirname(__file__), 'e... | Use new extension setup() API | Use new extension setup() API
| Python | mit | AlexandrePTJ/mopidy-somafm | ---
+++
@@ -21,6 +21,6 @@
schema = super(Extension, self).get_config_schema()
return schema
- def get_backend_classes(self):
+ def setup(self, registry):
from .actor import SomaFMBackend
- return [SomaFMBackend]
+ registry.add('backend', SomaFMBackend) |
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 | ---
+++
@@ -26,3 +26,9 @@
runner = Runner(self.rules, filename, [], [], [])
runner.run()
self.assertEqual(len(runner.playbooks), 4)
+
+ def test_include_tasks_with_block_include(self):
+ filename = 'test/include-in-block.yml'
+ runner = Runner(self.rules, filename, [], [], ... |
770328ea42182edc216d5abe4430e3ffd51a7793 | djmoney/__init__.py | djmoney/__init__.py | from django.db import models
from django.utils.encoding import smart_unicode
from django.utils import formats
from django.utils import timezone
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.admin.util import lookup_field
from django.utils.safestring import mark_safe
from django.utils.html i... | Allow django-money to be specified as read-only in a model | Allow django-money to be specified as read-only in a model
Monkey patch the Django admin so that we can display django-money fields
read-only. In order to do this, we simply catch the exception that
results from trying to convert a money object (e.g. '10 USD') into a
floating field.
And then we call just ask for the ... | Python | bsd-3-clause | rescale/django-money,iXioN/django-money,tsouvarev/django-money,tsouvarev/django-money,recklessromeo/django-money,iXioN/django-money,AlexRiina/django-money,recklessromeo/django-money | ---
+++
@@ -0,0 +1,70 @@
+from django.db import models
+from django.utils.encoding import smart_unicode
+from django.utils import formats
+from django.utils import timezone
+
+from django.core.exceptions import ObjectDoesNotExist
+from django.contrib.admin.util import lookup_field
+from django.utils.safestring import... | |
0ba063edc4aec690efca5c5ba9faf64042bb7707 | demo/demo/urls.py | demo/demo/urls.py | # -*- coding: utf-8 -*-
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'^$',... | # -*- coding: utf-8 -*-
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'^$', HomePageV... | 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 | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
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, Default... |
5e9fda28089a11863dcc4610f5953dbe942165db | numpy/_array_api/_constants.py | numpy/_array_api/_constants.py | from ._array_object import ndarray
from ._dtypes import float64
import numpy as np
e = ndarray._new(np.array(np.e, dtype=float64))
inf = ndarray._new(np.array(np.inf, dtype=float64))
nan = ndarray._new(np.array(np.nan, dtype=float64))
pi = ndarray._new(np.array(np.pi, dtype=float64))
| import numpy as np
e = np.e
inf = np.inf
nan = np.nan
pi = np.pi
| Make the array API constants Python floats | Make the array API constants Python floats
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | ---
+++
@@ -1,9 +1,6 @@
-from ._array_object import ndarray
-from ._dtypes import float64
-
import numpy as np
-e = ndarray._new(np.array(np.e, dtype=float64))
-inf = ndarray._new(np.array(np.inf, dtype=float64))
-nan = ndarray._new(np.array(np.nan, dtype=float64))
-pi = ndarray._new(np.array(np.pi, dtype=float64)... |
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 | ---
+++
@@ -23,3 +23,18 @@
config_tree = ConfigTree()
config_tree.put("a.b.c", 5)
assert config_tree.get("a.b.c") == 5
+
+ def test_config_tree_iterator(self):
+ config_tree = ConfigTree()
+ config_tree.put("a.b.c", 5)
+ for k in config_tree:
+ assert k == ... |
07dcdb9de47ac88a2e0f3ecec257397a0272f112 | extended_choices/__init__.py | extended_choices/__init__.py | """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1"
| """Little helper application to improve django choices (for fields)"""
from __future__ import unicode_literals
from .choices import Choices, OrderedChoices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com"
__homepage__ = "https://pypi.python.org/pypi/django-extended-choices"
__version__ = "1.1"... | Make OrderedChoices available at the package root | Make OrderedChoices available at the package root
| Python | bsd-3-clause | twidi/django-extended-choices | ---
+++
@@ -2,7 +2,7 @@
from __future__ import unicode_literals
-from .choices import Choices
+from .choices import Choices, OrderedChoices
__author__ = 'Stephane "Twidi" Ange;'
__contact__ = "s.angel@twidi.com" |
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... | ---
+++
@@ -29,3 +29,9 @@
assert _listdict['not called'] == []
assert _listdict['mylist'] == [0,1,2,3,4,5,6,7,8,9]
+
+# namedtuple
+a = collections.namedtuple("foo", "bar bash bing")(1, 2, 3)
+assert a.bar == 1
+assert a.bash == 2
+assert repr(a) == 'foo(bar=1, bash=2, bing=3)' |
888584a49e697551c4f680cc8651be2fe80fc65d | configgen/generators/ppsspp/ppssppGenerator.py | configgen/generators/ppsspp/ppssppGenerator.py | #!/usr/bin/env python
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 ... | #!/usr/bin/env python
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 ... | Remove a bad typo from reicast | Remove a bad typo from reicast
| Python | mit | nadenislamarre/recalbox-configgen,recalbox/recalbox-configgen,digitalLumberjack/recalbox-configgen | ---
+++
@@ -14,19 +14,16 @@
# Configure fba and return a command
def generate(self, system, rom, playersControllers):
if not system.config['configfile']:
- # Write emu.cfg to map joysticks, init with the default emu.cfg
- Config = ConfigParser.ConfigParser()
- Confi... |
d2d50e93911693c326b057a4c48f0a47d520f0a1 | skimage/future/__init__.py | skimage/future/__init__.py | """Functionality with an experimental API. Although you can count on the
functions in this package being around in the future, the API may change with
any version update **and will not follow the skimage two-version deprecation
path**. Therefore, use the functions herein with care, and do not use them in
production cod... | Add package docstring for skimage.future | Add package docstring for skimage.future
| Python | bsd-3-clause | ClinicalGraphics/scikit-image,ClinicalGraphics/scikit-image,newville/scikit-image,michaelaye/scikit-image,WarrenWeckesser/scikits-image,Hiyorimi/scikit-image,rjeli/scikit-image,chriscrosscutler/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,dpshelio/scikit-image,juliusbierk/scikit-image,newville/sciki... | ---
+++
@@ -0,0 +1,6 @@
+"""Functionality with an experimental API. Although you can count on the
+functions in this package being around in the future, the API may change with
+any version update **and will not follow the skimage two-version deprecation
+path**. Therefore, use the functions herein with care, and do ... | |
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 | ---
+++
@@ -1,9 +1,9 @@
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: |
0f7816676eceb42f13786408f1d1a09527919a1e | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py | Modules/Biophotonics/python/iMC/msi/io/spectrometerreader.py | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
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... | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 7 12:04:18 2015
@author: wirkert
"""
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... | 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,... | ---
+++
@@ -27,9 +27,14 @@
transformed = "\n".join([transformed, line])
for num, line in enumerate(transformed.splitlines(), 1):
- if ">>>>>Begin Spectral Data<<<<<" in line:
+ if ">>>>>Begin" in line:
break
- string_only_spectrum = "\n".join(t... |
33a3ebacabda376826f0470129e8583e4974fd9d | examples/markdown/build.py | examples/markdown/build.py | # build.py
#!/usr/bin/env python3
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.re... | # build.py
#!/usr/bin/env python3
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()
r... | Remove unneeded jinja2 import in markdown example | Remove unneeded jinja2 import in markdown example
| Python | mit | Ceasar/staticjinja,Ceasar/staticjinja | ---
+++
@@ -1,7 +1,6 @@
# build.py
#!/usr/bin/env python3
import os
-import jinja2
# Markdown to HTML library
# https://pypi.org/project/Markdown/ |
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... | ---
+++
@@ -5,6 +5,7 @@
class SubmissionAdmin(admin.ModelAdmin):
list_display = ( 'title', 'creator', 'featured', 'hidden', 'tags', 'modified', )
+ list_editable = ( 'featured', 'hidden' )
admin.site.register(Submission, SubmissionAdmin)
|
2fe02384ba4d5a8dee493d8fa76a3d0a6c440c01 | lib/python/webtest/site.py | lib/python/webtest/site.py | #!/usr/bin/env python
from twisted.web.server import Site
from webtest.session import RedisSessionFactory
from webtest.request import RedisRequest
from webtest import log
logger = log.get_logger()
class RedisSite(Site):
sessionFactory = RedisSessionFactory
requestFactory = RedisRequest
def makeSession(s... | #!/usr/bin/env python
from twisted.web.server import Site
from webtest.session_factory import RedisSessionFactory
from webtest.request import RedisRequest
from webtest import log
logger = log.get_logger()
class RedisSite(Site):
sessionFactory = RedisSessionFactory
requestFactory = RedisRequest
def makeS... | Move RedisSessionFactory into its own module | Move RedisSessionFactory into its own module
| Python | mit | donalm/webtest,donalm/webtest | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
from twisted.web.server import Site
-from webtest.session import RedisSessionFactory
+from webtest.session_factory import RedisSessionFactory
from webtest.request import RedisRequest
from webtest import log
|
108b0374d07ca33e90d963692f51e8a66e6d805c | common/middleware/local_node.py | common/middleware/local_node.py | class LocalNodeMiddleware(object):
"""
Ensures a Node that represents the local server always exists.
No other suitable hook for code that's run once and can access the server's host name
was found. A migration was not suitable for the second reason.
"""
def __init__(self):
self.local_n... | class LocalNodeMiddleware(object):
"""
Ensures a Node that represents the local server always exists.
No other suitable hook for code that's run once and can access the server's host name
was found. A migration was not suitable for the second reason.
"""
def __init__(self):
self.local_n... | Add TODO to fix bug at later date | Add TODO to fix bug at later date
| Python | apache-2.0 | TeamAADGT/CMPUT404-project-socialdistribution,TeamAADGT/CMPUT404-project-socialdistribution,TeamAADGT/CMPUT404-project-socialdistribution | ---
+++
@@ -26,6 +26,7 @@
node = nodes[0]
node.host = host
node.service = service
+ # TODO: Fix bug that prevents this from actually saving
node.save()
else:
raise RuntimeError("More than one local node fo... |
8d471b5b7a8f57214afe79783f09afa97c5d2bfc | entropy/__init__.py | entropy/__init__.py | import entropy._entropy as _entropy
def entropy(data):
"""Compute the Shannon entropy of the given string.
Returns a floating point value indicating how many bits of entropy
there are per octet in the string."""
return _entropy.shannon_entropy(data)
if __name__ == '__main__':
print entropy('\n'.join(file(__file... | import entropy._entropy as _entropy
def entropy(data):
"""Compute the Shannon entropy of the given string.
Returns a floating point value indicating how many bits of entropy
there are per octet in the string."""
return _entropy.shannon_entropy(data)
def absolute_entropy(data):
"""Compute the "absolute" entropy ... | Add absolute and relative entropy functions. | Add absolute and relative entropy functions.
| Python | bsd-3-clause | chachalaca/py-entropy,billthebrute/py-entropy,chachalaca/py-entropy,billthebrute/py-entropy | ---
+++
@@ -7,5 +7,26 @@
there are per octet in the string."""
return _entropy.shannon_entropy(data)
+def absolute_entropy(data):
+ """Compute the "absolute" entropy of the given string.
+
+ The absolute entropy of a string is how many bits of information,
+ total, are in the entire string. This is the same as ... |
b43e06dd5a80814e15ce20f50d683f0daaa19a93 | addons/hr/models/hr_employee_base.py | addons/hr/models/hr_employee_base.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrEmployeeBase(models.AbstractModel):
_name = "hr.employee.base"
_description = "Basic Employee"
_order = 'name'
name = fields.Char()
active = fields.Boolean("... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
class HrEmployeeBase(models.AbstractModel):
_name = "hr.employee.base"
_description = "Basic Employee"
_order = 'name'
name = fields.Char()
active = fields.Boolean("... | 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 | ---
+++
@@ -11,6 +11,7 @@
name = fields.Char()
active = fields.Boolean("Active")
+ color = fields.Integer('Color Index', default=0)
department_id = fields.Many2one('hr.department', 'Department')
job_id = fields.Many2one('hr.job', 'Job Position')
job_title = fields.Char("Job Title") |
96e3d70a7bd824b8265e8e67adc3996c4522dd57 | historia.py | historia.py | from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run()
| from eve import Eve
app = Eve()
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
| Use port 80 to serve the API | Use port 80 to serve the API
| Python | mit | waoliveros/historia | ---
+++
@@ -3,4 +3,4 @@
app = Eve()
if __name__ == '__main__':
- app.run()
+ app.run(host='0.0.0.0', port=80) |
be41ae0d987cd1408cb2db649a2eccd73bc272f3 | apps/innovate/views.py | apps/innovate/views.py | import random
import jingo
from users.models import Profile
from projects.models import Project
from events.models import Event
from feeds.models import Entry
def splash(request):
"""Display splash page. With featured project, event, person, blog post."""
def get_random(cls, **kwargs):
choices = cls... | import random
import jingo
from users.models import Profile
from projects.models import Project
from events.models import Event
from feeds.models import Entry
def splash(request):
"""Display splash page. With featured project, event, person, blog post."""
def get_random(cls, **kwargs):
choices = cls... | Add status codes to the 404/500 error handlers. | Add status codes to the 404/500 error handlers.
| Python | bsd-3-clause | mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm | ---
+++
@@ -30,9 +30,9 @@
def handle404(request):
"""Handle 404 responses."""
- return jingo.render(request, 'handlers/404.html')
+ return jingo.render(request, 'handlers/404.html', status=404)
def handle500(request):
"""Handle server errors."""
- return jingo.render(request, 'handlers/500.... |
60837893bf12bc5476b050cdc689260e9695a297 | fileupload/models.py | fileupload/models.py | # encoding: utf-8
from django.db import models
import uuid
import os
def unique_file_name(instance, filename):
path = 'benchmarkLogs/'
name = str(uuid.uuid4()) + '.log'
return os.path.join(path, name)
class Picture(models.Model):
"""This is a small demo using just two fields. The slug field is really... | # encoding: utf-8
from django.db import models
import uuid
import os
def unique_file_name(instance, filename):
path = 'benchmarkLogs/'
name = str(uuid.uuid4().hex) + '.log'
return os.path.join(path, name)
class Picture(models.Model):
"""This is a small demo using just two fields. The slug field is re... | Make sure the filename is alphanumeric | Make sure the filename is alphanumeric
| Python | bsd-2-clause | ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark,ankeshanand/benchmark | ---
+++
@@ -6,7 +6,7 @@
def unique_file_name(instance, filename):
path = 'benchmarkLogs/'
- name = str(uuid.uuid4()) + '.log'
+ name = str(uuid.uuid4().hex) + '.log'
return os.path.join(path, name)
class Picture(models.Model): |
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 | ---
+++
@@ -15,4 +15,5 @@
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, s1, t1 |
85809e34f1d8ad3d8736e141f3cb2e6045260938 | neuroimaging/externals/pynifti/nifti/__init__.py | neuroimaging/externals/pynifti/nifti/__init__.py |
from niftiimage import NiftiImage
| """
Nifti
=====
Python bindings for the nifticlibs. Access through the NiftiImage class.
See help for pyniftiio.nifti.NiftiImage
"""
from niftiimage import NiftiImage
| Add doc for pynifti package. | DOC: Add doc for pynifti package. | Python | bsd-3-clause | alexis-roche/nipy,alexis-roche/register,nipy/nireg,alexis-roche/register,nipy/nipy-labs,nipy/nipy-labs,alexis-roche/nipy,alexis-roche/niseg,arokem/nipy,arokem/nipy,alexis-roche/nipy,nipy/nireg,bthirion/nipy,alexis-roche/nireg,alexis-roche/niseg,bthirion/nipy,bthirion/nipy,bthirion/nipy,alexis-roche/nireg,arokem/nipy,al... | ---
+++
@@ -1,2 +1,11 @@
+"""
+Nifti
+=====
+
+ Python bindings for the nifticlibs. Access through the NiftiImage class.
+
+ See help for pyniftiio.nifti.NiftiImage
+
+"""
from niftiimage import NiftiImage |
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 | ---
+++
@@ -3,14 +3,10 @@
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/ajax/libs/pagedown/1.0/Markdown... |
365411abd73275a529dc5ca7ec403b994c513aae | registries/serializers.py | registries/serializers.py | from rest_framework import serializers
from registries.models import Organization
from gwells.models import ProvinceState
class DrillerListSerializer(serializers.ModelSerializer):
province_state = serializers.ReadOnlyField()
class Meta:
model = Organization
# Using all fields for now
... | from rest_framework import serializers
from registries.models import Organization
from gwells.models import ProvinceState
class DrillerListSerializer(serializers.ModelSerializer):
"""
Serializer for Driller model "list" view.
"""
province_state = serializers.ReadOnlyField(source="province_state.code"... | Add fields to driller list serializer | Add fields to driller list serializer
| Python | apache-2.0 | bcgov/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,rstens/gwells,rstens/gwells,bcgov/gwells | ---
+++
@@ -2,8 +2,13 @@
from registries.models import Organization
from gwells.models import ProvinceState
+
class DrillerListSerializer(serializers.ModelSerializer):
- province_state = serializers.ReadOnlyField()
+ """
+ Serializer for Driller model "list" view.
+ """
+
+ province_state = serial... |
a2eb2ad96562f5b740338d9acb68dc72f72031a2 | astroquery/conftest.py | astroquery/conftest.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
import os
# This is to figure out the astroquery version, rather than using Astropy's
from . import version
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conf... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
import os
# This is to figure out the astroquery version, rather than using Astropy's
from . import version
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conf... | Fix packagename spelling for testing header | Fix packagename spelling for testing header
| Python | bsd-3-clause | ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery,imbasimba/astroquery | ---
+++
@@ -24,7 +24,7 @@
try:
PYTEST_HEADER_MODULES['Astropy'] = 'astropy'
- PYTEST_HEADER_MODULES['APLpy'] = 'APLpy'
+ PYTEST_HEADER_MODULES['APLpy'] = 'aplpy'
PYTEST_HEADER_MODULES['pyregion'] = 'pyregion'
del PYTEST_HEADER_MODULES['h5py']
del PYTEST_HEADER_MODULES['Scipy'] |
bfdfb47049c3b560f49bb917ea56e85f85c80e91 | project_template/project_name/context_processors.py | project_template/project_name/context_processors.py | from django.conf import settings
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
}
}
| from django.conf import settings
def add_settings( request ):
"""Add some selected settings values to the context"""
return {
'settings': {
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
'DEBUG': settings.DEBUG,
}
}
| Make settings.DEBUG available to templates It's used in the default base.html template so makes sense for it to actually appear in the context. | Make settings.DEBUG available to templates
It's used in the default base.html template so makes sense for it to actually appear in the context.
| Python | agpl-3.0 | mysociety/django-jumpstart,mysociety/django-jumpstart | ---
+++
@@ -5,5 +5,6 @@
return {
'settings': {
'GOOGLE_ANALYTICS_ACCOUNT': settings.GOOGLE_ANALYTICS_ACCOUNT,
+ 'DEBUG': settings.DEBUG,
}
} |
fc9fdd2115b46c71c36ba7d86f14395ac4cf1e3e | genome_designer/scripts/generate_coverage_data.py | genome_designer/scripts/generate_coverage_data.py | """Script to generate coverage data.
"""
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... | """Script to generate coverage data.
"""
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... | 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 | ---
+++
@@ -26,9 +26,15 @@
output_path = os.path.join(output_dir, output_filename)
with open(output_path, 'w') as fh:
- subprocess.check_call([
+ p_mpileup = subprocess.Popen([
'%s/samtools/samtools' % settings.TOOLS_DIR,
'mpileup',
'-f', re... |
79d3f7476ef35ce120190badad63d460d7fa092b | rootio/telephony/forms.py | rootio/telephony/forms.py | # from wtforms import Form
from flask.ext.babel import gettext as _
from flask.ext.wtf import Form
from wtforms import SubmitField, RadioField, StringField
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.validators import AnyOf, Required
from .constants import PHONE_NUMBER_TYPE
from .models import Phone... | # from wtforms import Form
from flask.ext.babel import gettext as _
from flask.ext.wtf import Form
from wtforms import SubmitField, RadioField, StringField
from wtforms.ext.sqlalchemy.orm import model_form
from wtforms.validators import AnyOf, Required
from .constants import PHONE_NUMBER_TYPE
from .models import Phone... | Fix inline phone number form | Fix inline phone number form
| Python | agpl-3.0 | rootio/rootio_web,rootio/rootio_web,rootio/rootio_web,rootio/rootio_web | ---
+++
@@ -24,7 +24,7 @@
class PhoneNumberForm(PhoneNumberFormBase):
- number = StringField(_('Phone Number'), [Required], default=" ")
+ number = StringField(_('Phone Number'), [Required()], default=" ")
number_type = RadioField(_("Type"),
[AnyOf([str(val) for val in PH... |
e7bda027780da26183f84f7af5c50cd37649c76b | functional_tests/remote.py | functional_tests/remote.py | # -*- coding: utf-8 -*-
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', 'cr... | # -*- coding: utf-8 -*-
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):
... | 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 | ---
+++
@@ -6,12 +6,14 @@
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'],
cwd=THIS_FOLDER)
... |
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 | ---
+++
@@ -22,6 +22,12 @@
c = http.HTTPClient('localhost:55672', 'guest', 'guest')
self.assertIsInstance(c, http.HTTPClient)
+ def test_client_init_sets_credentials(self):
+ domain = ''
+ expected_credentials = [(domain, 'guest', 'guest')]
+ self.assertEqual(
+ ... |
4853e42c080bcb065da16e1d613a73a835afbaf6 | infcommon/postgres/factory.py | infcommon/postgres/factory.py | # -*- coding: utf-8 -*-
import os
from infcommon import Factory
from infcommon.postgres.postgres import PostgresClient
def postgres_client_from_connection_parameters(user, password, host, port, db_name):
connection_uri = 'postgresql://{user}:{password}@{host}:{port}/{db_name}'.format(user=user, password=password... | # -*- coding: utf-8 -*-
import os
from infcommon.factory import Factory
from infcommon.postgres.postgres import PostgresClient
def postgres_client_from_connection_parameters(user, password, host, port, db_name):
connection_uri = 'postgresql://{user}:{password}@{host}:{port}/{db_name}'.format(user=user, password=... | Use Factory class from module instead of from __init__ | [HOUSEKEEPING] Use Factory class from module instead of from __init__
| Python | mit | aleasoluciones/infcommon,aleasoluciones/infcommon | ---
+++
@@ -2,7 +2,7 @@
import os
-from infcommon import Factory
+from infcommon.factory import Factory
from infcommon.postgres.postgres import PostgresClient
def postgres_client_from_connection_parameters(user, password, host, port, db_name): |
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 | ---
+++
@@ -1,6 +1,7 @@
"""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
@@ -27,3 +28,16 @@
assert_raises(ValueError,
_solve_weight_vec... |
ca28ffbc6d4f981e952709af77139f7a8666319d | client/gettransactions.py | client/gettransactions.py | #!/usr/bin/python
import os
import sys
import api
import json
import getpass
# Banks
banks = {}
import bankofamerica
banks["bankofamerica"] = bankofamerica
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpass()
if not api.callapi("login",{"username": username, "passwor... | #!/usr/bin/python
import os
import sys
import api
import json
import getpass
sys.path.append("../")
import config
# Banks
banks = {}
for bank in config.banks:
exec "import %s" % (bank)
banks[bank] = eval(bank)
print "Login"
print "Username: ",
username = sys.stdin.readline().strip()
password = getpass.getpa... | Read bank list from config file. | Read bank list from config file.
| Python | agpl-3.0 | vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash | ---
+++
@@ -5,10 +5,15 @@
import json
import getpass
+sys.path.append("../")
+
+import config
+
# Banks
banks = {}
-import bankofamerica
-banks["bankofamerica"] = bankofamerica
+for bank in config.banks:
+ exec "import %s" % (bank)
+ banks[bank] = eval(bank)
print "Login"
print "Username: ", |
eebae9eb9b941a4e595775434a05df29d55a34f2 | tools/conan/conanfile.py | tools/conan/conanfile.py | from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration li... | from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration li... | Build with PIC by default. | Build with PIC by default.
| Python | lgpl-2.1 | worldforge/varconf,worldforge/varconf,worldforge/varconf,worldforge/varconf | ---
+++
@@ -11,8 +11,8 @@
description = "Configuration library for the Worldforge system."
topics = ("mmorpg", "worldforge")
settings = "os", "compiler", "build_type", "arch"
- options = {"shared": [False, True]}
- default_options = {"shared": False}
+ options = {"shared": [False, True], "fPIC... |
5b2e74cdc50a6c3814879f470d8992267fa06a62 | heufybot/utils/__init__.py | heufybot/utils/__init__.py | # Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... | # Taken from txircd:
# https://github.com/ElementalAlchemist/txircd/blob/8832098149b7c5f9b0708efe5c836c8160b0c7e6/txircd/utils.py#L9
def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(LIST=0, PARAM_SET=1, PARAM_UNSET=2, NO_PARAM=3)
ModuleLoadType = _enum(LOAD=0, UNLOAD=1, ENABLE=2, DISABLE=3)
def... | Fix the handling of missing prefixes | Fix the handling of missing prefixes
Twisted defaults to an empty string, while IRCBase defaults to None.
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | ---
+++
@@ -14,6 +14,9 @@
return False
def parseUserPrefix(prefix):
+ if prefix is None:
+ prefix = ""
+
if "!" in prefix:
nick = prefix[:prefix.find("!")]
ident = prefix[prefix.find("!") + 1:prefix.find("@")] |
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/... | ---
+++
@@ -31,7 +31,18 @@
return Markup('<i class="icon-ok"></i>' if value else '')
+def list_formatter(values):
+ """
+ Return string with comma separated values
+
+ :param values:
+ Value to check
+ """
+ return u', '.join(values)
+
+
DEFAULT_FORMATTERS = {
type(Non... |
e9eb8e0c4e77525d31c904e7f401a0d388a3fbf6 | app/utils.py | app/utils.py | from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
... | from flask import url_for
def register_template_utils(app):
"""Register Jinja 2 helpers (called from __init__.py)."""
@app.template_test()
def equalto(value, other):
return value == other
@app.template_global()
def is_hidden_field(field):
from wtforms.fields import HiddenField
... | Fix index_for_role function to use index field in Role class. | Fix index_for_role function to use index field in Role class.
| Python | mit | hack4impact/women-veterans-rock,hack4impact/women-veterans-rock,hack4impact/women-veterans-rock | ---
+++
@@ -17,4 +17,4 @@
def index_for_role(role):
- return url_for(role.name + '.index')
+ return url_for(role.index) |
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 | ---
+++
@@ -11,7 +11,7 @@
response = urllib2.urlopen(request)
metar = response.read().split('\n')[1] # NOAA includes a "real" timestamp as the first line of the response
- if getattr(conf, 'hashtag', False):
+ if conf.get('hashtag', False):
metar = '%s #%s' % (metar, conf['hashtag'])
... |
19b7946dd57b79e49d1d54d980d295435793e465 | slackminion/__main__.py | slackminion/__main__.py | import logging
from config import *
from slackminion.bot import Bot
def main():
level = logging.DEBUG if DEBUG else logging.INFO
logging.basicConfig(level=level, format='%(asctime)s %(name)s %(levelname)s: %(message)s')
bot = Bot(SLACK_TOKEN)
bot.start()
bot.run()
bot.stop()
if __name__ == ... | import logging
import sys
sys.path.append('.')
from config import *
from slackminion.bot import Bot
def main():
level = logging.DEBUG if DEBUG else logging.INFO
logging.basicConfig(level=level, format='%(asctime)s %(name)s %(levelname)s: %(message)s')
bot = Bot(SLACK_TOKEN)
bot.start()
bot.run()... | Allow importing of config from current directory | Allow importing of config from current directory
| Python | mit | arcticfoxnv/slackminion,arcticfoxnv/slackminion | ---
+++
@@ -1,4 +1,6 @@
import logging
+import sys
+sys.path.append('.')
from config import *
from slackminion.bot import Bot |
0461fad1a3d81aa2d937a1734f1ebb07b3e81d79 | undercloud_heat_plugins/server_update_allowed.py | undercloud_heat_plugins/server_update_allowed.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | 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 | ---
+++
@@ -21,6 +21,10 @@
update_allowed_properties = server.Server.properties_schema.keys()
+ def needs_replace_with_prop_diff(self, changed_properties_set,
+ after_props, before_props):
+ return False
+
def resource_mapping():
return {'OS::Nova::Server... |
1514da45e5d89a2ab426ed62f807d137e9c318e9 | labonneboite/common/pdf.py | labonneboite/common/pdf.py | # coding: utf8
import errno
import logging
import os
from slugify import slugify
from labonneboite.conf import settings
logger = logging.getLogger('main')
def get_file_path(office):
file_path = "pdf/%s/%s/%s/%s.pdf" % (office.departement, office.naf, slugify(office.name.strip()[0]), office.siret)
full_path... | # coding: utf8
import errno
import logging
import os
from slugify import slugify
from labonneboite.conf import settings
logger = logging.getLogger('main')
def get_file_path(office):
file_path = "pdf/%s/%s/%s/%s.pdf" % (office.departement, office.naf, slugify(office.name.strip()[0]), office.siret)
full_path... | Add FIXME for delete PDF | Add FIXME for delete PDF
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite | ---
+++
@@ -32,6 +32,7 @@
def delete_file(office):
+ # FIXME : Works only on one front-end...
filename = get_file_path(office)
if os.path.exists(filename):
os.remove(filename) |
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 | ---
+++
@@ -30,7 +30,8 @@
if (connection.dbName == 'sqlite') and connection._memory:
return # The following test requires a different connection
- test = TestPickle.get(test.id,
- connection=getConnection(registry='')) # to make a different DB URI
- ... |
75e7008e65cb731cc2a7a24dfa86f02049032b44 | src/settings.py | src/settings.py | # -*- coding: utf-8 -*-
import os
HERE = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE... | # -*- coding: utf-8 -*-
import os
HERE = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(HERE, os.pardir))
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key')
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE... | Set production databse to test database | Set production databse to test database
| Python | mit | zhoux10/pdfhook,zhoux10/pdfhook,zhoux10/pdfhook | ---
+++
@@ -8,7 +8,7 @@
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'secret-key')
SQLALCHEMY_TRACK_MODIFICATIONS = False
- SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL')
+ SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL', 'postgresql://localhost/')
SERVER_NAME = os.e... |
8c0f87858b1dc58d23006cd581cfa74d23096a44 | trex/serializers.py | trex/serializers.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import HyperlinkedModelSerializer
from trex.models.project import Project
class ProjectSerializer(HyperlinkedModelSerializer):
class Meta:
... | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from rest_framework.serializers import HyperlinkedModelSerializer
from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
class... | Add a ProjectDetailSerializer and EntryDetailSerializer | Add a ProjectDetailSerializer and EntryDetailSerializer
| Python | mit | bjoernricks/trex,bjoernricks/trex | ---
+++
@@ -7,7 +7,7 @@
from rest_framework.serializers import HyperlinkedModelSerializer
-from trex.models.project import Project
+from trex.models.project import Project, Entry
class ProjectSerializer(HyperlinkedModelSerializer):
@@ -15,3 +15,17 @@
class Meta:
model = Project
fields... |
2e9a6a2babb16f4ed9c3367b21ee28514d1988a8 | srm/__main__.py | srm/__main__.py | """
The default module run when imported from the command line and also the main entry point defined in
setup.py. Ex:
python3 -m srm
"""
import click
from . import __version__, status
@click.group()
@click.version_option(__version__)
def cli() -> None:
"""Main command-line entry method."""
cli.add_comma... | """
The default module run when imported from the command line and also the main entry point defined in
setup.py. Ex:
python3 -m srm
"""
import click
from . import __version__, status
@click.group()
@click.version_option(__version__)
def cli() -> None:
"""Main command-line entry method."""
cli.add_comma... | Set correct program name in 'help' output | Set correct program name in 'help' output
| Python | mit | cmcginty/simple-rom-manager,cmcginty/simple-rom-manager | ---
+++
@@ -17,6 +17,4 @@
cli.add_command(status.cli)
-
-if __name__ == '__main__':
- cli()
+cli(prog_name='srm') |
e54d753a3fb58032936cbf5e137bb5ef67e2813c | task_15.py | task_15.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provides variables for string and integer conversion."""
NOT_THE_QUESTION = 'The answer to life, the universe, and everything? It\'s '
ANSWER = 42
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""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 | ---
+++
@@ -5,3 +5,4 @@
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) |
26df58ea40651ac20845ed4a4a84642e61cdf84a | deployer/__init__.py | deployer/__init__.py | from __future__ import absolute_import
import deployer.logger
from celery.signals import setup_logging
__version__ = '0.1.10'
__author__ = 'sukrit'
deployer.logger.init_logging('root')
setup_logging.connect(deployer.logger.init_celery_logging)
| from __future__ import absolute_import
import deployer.logger
from celery.signals import setup_logging
__version__ = '0.2'
__author__ = 'sukrit'
deployer.logger.init_logging('root')
setup_logging.connect(deployer.logger.init_celery_logging)
| Upgrade to 0.2 : Centralized logging support | Upgrade to 0.2 : Centralized logging support | Python | mit | totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer | ---
+++
@@ -3,7 +3,7 @@
from celery.signals import setup_logging
-__version__ = '0.1.10'
+__version__ = '0.2'
__author__ = 'sukrit'
deployer.logger.init_logging('root') |
e55a1e97a191dd5c9fc43a1d2ed0b723ac64f46a | stacker/logger/__init__.py | stacker/logger/__init__.py | import sys
import logging
DEBUG_FORMAT = ("[%(asctime)s] %(levelname)s %(name)s:%(lineno)d"
"(%(funcName)s): %(message)s")
INFO_FORMAT = ("[%(asctime)s] %(message)s")
COLOR_FORMAT = ("[%(asctime)s] \033[%(color)sm%(message)s\033[39m")
ISO_8601 = "%Y-%m-%dT%H:%M:%S"
class ColorFormatter(logging.Forma... | import sys
import logging
DEBUG_FORMAT = ("[%(asctime)s] %(levelname)s %(threadName)s "
"%(name)s:%(lineno)d(%(funcName)s): %(message)s")
INFO_FORMAT = ("[%(asctime)s] %(message)s")
COLOR_FORMAT = ("[%(asctime)s] \033[%(color)sm%(message)s\033[39m")
ISO_8601 = "%Y-%m-%dT%H:%M:%S"
class ColorFormatte... | Include threadName in DEBUG format | Include threadName in DEBUG format
| Python | bsd-2-clause | remind101/stacker,remind101/stacker | ---
+++
@@ -1,8 +1,8 @@
import sys
import logging
-DEBUG_FORMAT = ("[%(asctime)s] %(levelname)s %(name)s:%(lineno)d"
- "(%(funcName)s): %(message)s")
+DEBUG_FORMAT = ("[%(asctime)s] %(levelname)s %(threadName)s "
+ "%(name)s:%(lineno)d(%(funcName)s): %(message)s")
INFO_FORMAT = ("[%... |
84e7ebd3df1fc7b9cb52fa5c7fcb3af87e6b454d | playserver/trackchecker.py | playserver/trackchecker.py | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurren... | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurren... | Fix name error in setting daemon | Fix name error in setting daemon
| Python | mit | ollien/playserver,ollien/playserver,ollien/playserver | ---
+++
@@ -36,7 +36,7 @@
def startTimer(self):
self.timer = Timer(self.CHECK_INTERVAL, self.checkSong)
- timer.daemon = True
+ self.timer.daemon = True
self.timer.start()
def cancelTimer(self): |
1c3d2669d9bbe1aa3f4387f864d9085945e9257c | zeus/api/schemas/hook.py | zeus/api/schemas/hook.py | from base64 import urlsafe_b64encode
from datetime import timedelta
from marshmallow import Schema, fields, post_load
from zeus.models import Hook
from zeus.utils import timezone
class HookSchema(Schema):
id = fields.UUID(dump_only=True)
provider = fields.Str()
token = fields.Method('get_token', dump_onl... | from base64 import urlsafe_b64encode
from datetime import timedelta
from marshmallow import Schema, fields, post_load
from zeus.models import Hook
from zeus.utils import timezone
class HookSchema(Schema):
id = fields.UUID(dump_only=True)
provider = fields.Str()
token = fields.Method('get_token', dump_onl... | Fix base url for public generation | Fix base url for public generation
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus | ---
+++
@@ -25,7 +25,7 @@
return None
def get_public_uri(self, obj):
- return '/hooks/{}'.format(str(obj.id))
+ return '/hooks/{}/public'.format(str(obj.id))
def get_secret_uri(self, obj):
return '/hooks/{}/{}'.format(str(obj.id), obj.get_signature()) |
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... | ---
+++
@@ -8,7 +8,8 @@
'pombola.place_data',
'pombola.votematch',
'speeches',
- 'pombola.spinner' ) + \
+ 'pombola.spinner',
+ 'pombola.interests_register') + \
APPS_REQUIRED_BY_SPEECHES
#... |
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 | ---
+++
@@ -19,7 +19,6 @@
for config_class in configs:
config_obj = config_class()
- self.stdout.write("Processing {}".format(config_class.__name__))
try:
config_obj.collect()
except Exception: |
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 | ---
+++
@@ -29,6 +29,7 @@
plugin, created = cls.get_or_create_plugin_object()
if not created and plugin.version != cls.version:
+ print('Plugin updated: {0} -> {1}'.format(cls.version, plugin.version))
plugin.version = cls.version
plugin.save()
@@ -42,9 +43,2... |
17499a12c9216d1db907305ef30f58970cd0932e | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/api/serializers.py | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/api/serializers.py | from django.contrib.auth import get_user_model
from rest_framework import serializers
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["username", "email", "name", "url"]
extra_kwargs = {
"url": {"view_name": "api:u... | from django.contrib.auth import get_user_model
from rest_framework import serializers
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["username", "name", "url"]
extra_kwargs = {
"url": {"view_name": "api:user-detai... | Remove email from User API | Remove email from User API | Python | bsd-3-clause | pydanny/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-dja... | ---
+++
@@ -7,7 +7,7 @@
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
- fields = ["username", "email", "name", "url"]
+ fields = ["username", "name", "url"]
extra_kwargs = {
"url": {"view_name": "api:user-detail", "lookup_field": "user... |
e32d95c40dcfa4d3eb07572d5fd4f0fda710c64c | indra/sources/phosphoELM/api.py | indra/sources/phosphoELM/api.py | import csv
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
ppelm_json = []
if fname is None:
# ToDo Get from S3
pass
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
columns = next(csv_reader... | import csv
ppelm_s3_key = ''
def process_from_dump(fname=None, delimiter='\t'):
if fname is None:
# ToDo Get from S3
return []
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
ppelm_json = _get_json_from_entry_rows(c... | Move iterator to own function | Move iterator to own function
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra | ---
+++
@@ -4,16 +4,21 @@
def process_from_dump(fname=None, delimiter='\t'):
- ppelm_json = []
if fname is None:
# ToDo Get from S3
- pass
+ return []
else:
with open(fname, 'r') as f:
csv_reader = csv.reader(f.readlines(), delimiter=delimiter)
- ... |
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 | ---
+++
@@ -3,19 +3,18 @@
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_parts = ... |
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 | ---
+++
@@ -3,24 +3,39 @@
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 ... |
b47d7b44030a8388d1860316c117e02796ba9ccc | __init__.py | __init__.py | # -*- coding: utf-8 -*-
"""
FLUID DYNAMICS SIMULATOR
Requires Python 2.7 and OpenCV 2
Tom Blanchet (c) 2013 - 2014 (revised 2017)
"""
import cv2
from fluidDoubleCone import FluidDoubleCone, RGB
from fluidDoubleConeView import FluidDCViewCtrl
def slow_example():
inImg = cv2.imread("gameFace.jpg")
game_face_dC... | # -*- coding: utf-8 -*-
"""
FLUID DYNAMICS SIMULATOR
Requires Python 2.7, pygame, numpy, and OpenCV 2
Tom Blanchet (c) 2013 - 2014 (revised 2017)
"""
import cv2
from fluidDoubleCone import FluidDoubleCone, RGB
from fluidDoubleConeView import FluidDCViewCtrl
def slow_example():
inImg = cv2.imread("gameFace.jpg")
... | Include pygame and numpy in discription. | Include pygame and numpy in discription.
| Python | apache-2.0 | FrogBomb/fluidDynamicsSimulator | ---
+++
@@ -2,7 +2,7 @@
"""
FLUID DYNAMICS SIMULATOR
-Requires Python 2.7 and OpenCV 2
+Requires Python 2.7, pygame, numpy, and OpenCV 2
Tom Blanchet (c) 2013 - 2014 (revised 2017)
""" |
6447f7f025d00006300ec17668a479214206b09a | examples/guess/submissions/wrong_answer/guess_modulo.py | examples/guess/submissions/wrong_answer/guess_modulo.py | #!/usr/bin/env python3
for i in range(1000):
print(337*i%1000+1)
| #!/usr/bin/env python3
import sys
# This submission exposes a bug in an older version of the output validator
# where the valid range of possible submissions becomes empty because the range
# of possible values was updated incorrectly.
# The expected verdict is WA, but with the bug present, it would give RTE.
min_hi... | Fix counterexample to be more explicit | Fix counterexample to be more explicit
| Python | mit | Kattis/problemtools,Kattis/problemtools,Kattis/problemtools,Kattis/problemtools | ---
+++
@@ -1,3 +1,25 @@
#!/usr/bin/env python3
-for i in range(1000):
- print(337*i%1000+1)
+
+import sys
+
+# This submission exposes a bug in an older version of the output validator
+# where the valid range of possible submissions becomes empty because the range
+# of possible values was updated incorrectly.
... |
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 | ---
+++
@@ -3,3 +3,10 @@
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()) |
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 | ---
+++
@@ -9,26 +9,36 @@
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 antifuzz")
+ parser.add_argument("newFile", ... |
0418a4a2e2cf2dc6e156c880600491691a57c525 | setup.py | setup.py | from setuptools import setup, find_packages
import versioneer
with open('requirements.txt') as f:
requirements = f.read().splitlines()
requirements = ['setuptools'] + requirements
setup(
name='pyxrf',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
author='Brookhaven Nation... | from setuptools import setup, find_packages
import versioneer
with open('requirements.txt') as f:
requirements = f.read().splitlines()
requirements = ['setuptools'] + requirements
setup(
name='pyxrf',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
author='Brookhaven Nation... | Include YAML data file in the package | Include YAML data file in the package
| Python | bsd-3-clause | NSLS-II-HXN/PyXRF,NSLS-II-HXN/PyXRF,NSLS-II/PyXRF | ---
+++
@@ -15,7 +15,7 @@
url='https://github.com/NSLS-II/PyXRF',
packages=find_packages(),
entry_points={'console_scripts': ['pyxrf = pyxrf.gui:run']},
- package_data={'pyxrf.view': ['*.enaml'], 'configs': ['*.json']},
+ package_data={'pyxrf.view': ['*.enaml'], 'configs': ['*.json'], 'pyxrf.core... |
0866695a2f60538d59277f45a69771664d6dee27 | setup.py | setup.py | import sys
import platform
from setuptools import setup, Extension
cpython = platform.python_implementation() == 'CPython'
is_glibc = platform.libc_ver()[0] == 'glibc'
libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9'
windows = sys.platform.startswith('win')
min_win_version = windows and sys.version_info >= (3, 5... | import sys
import platform
from setuptools import setup, Extension
cpython = platform.python_implementation() == 'CPython'
is_glibc = platform.libc_ver()[0] == 'glibc'
if is_glibc:
glibc_ver = platform.libc_ver()[1]
libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit())
libc_ok = libc_nu... | Fix glibc version detect string | Fix glibc version detect string
| Python | mit | agronholm/cbor2,agronholm/cbor2,agronholm/cbor2 | ---
+++
@@ -4,7 +4,12 @@
cpython = platform.python_implementation() == 'CPython'
is_glibc = platform.libc_ver()[0] == 'glibc'
-libc_ok = is_glibc and platform.libc_ver()[1] >= '2.9'
+if is_glibc:
+ glibc_ver = platform.libc_ver()[1]
+ libc_numeric = tuple(int(x) for x in glibc_ver.split('.') if x.isdigit())... |
bb204204482e868291efc34c5195d76024546a80 | setup.py | setup.py | from distutils.core import setup
from setuptools import find_packages
setup(name='geventconnpool',
version = "0.1",
description = 'TCP connection pool for gevent',
url="https://github.com/rasky/geventconnpool",
author="Giovanni Bajo",
author_email="rasky@develer.com",
packages=find_packages('sr... | from distutils.core import setup
from setuptools import find_packages
with open('README.rst') as file:
long_description = file.read()
setup(name='geventconnpool',
version = "0.1a",
description = 'TCP connection pool for gevent',
long_description = long_description,
url="https://github.com/rasky/ge... | Add long description to the package. | Add long description to the package.
| Python | mit | rasky/geventconnpool,rasky/geventconnpool | ---
+++
@@ -1,9 +1,13 @@
from distutils.core import setup
from setuptools import find_packages
+with open('README.rst') as file:
+ long_description = file.read()
+
setup(name='geventconnpool',
- version = "0.1",
+ version = "0.1a",
description = 'TCP connection pool for gevent',
+ long_descripti... |
eebf41e6cf85f98d034708999e0321f9e09e4093 | setup.py | setup.py | import names
from setuptools import setup, find_packages
setup(
name=names.__title__,
version=names.__version__,
author=names.__author__,
url="https://github.com/treyhunner/names",
description="Generate random names",
license=names.__license__,
packages=find_packages(),
package_data={'... | import names
from setuptools import setup, find_packages
setup(
name=names.__title__,
version=names.__version__,
author=names.__author__,
url="https://github.com/treyhunner/names",
description="Generate random names",
long_description=open('README.rst').read(),
license=names.__license__,
... | Use readme file for package long description | Use readme file for package long description
| Python | mit | treyhunner/names,treyhunner/names | ---
+++
@@ -8,6 +8,7 @@
author=names.__author__,
url="https://github.com/treyhunner/names",
description="Generate random names",
+ long_description=open('README.rst').read(),
license=names.__license__,
packages=find_packages(),
package_data={'names': ['dist.*']}, |
70e0c6bf40776cda30e871a290b2760bfdb993e5 | setup.py | setup.py | from setuptools import setup
__version__ = '0.2.2'
setup(
name='kuberender',
version=__version__,
py_modules=['kuberender'],
install_requires=[
'Jinja2==2.9.6',
'click==6.7',
'PyYAML==3.12',
'dpath==1.4.0',
'libvcs==0.2.3',
],
entry_points='''
[console_scr... | from setuptools import setup
__version__ = '0.2.3'
setup(
name='kuberender',
version=__version__,
py_modules=['kuberender'],
description='A tool to render and apply Kubernetes manifests using Jinja2',
install_requires=[
'Jinja2==2.9.6',
'click==6.7',
'PyYAML==3.12',
'dpath=... | Add description and bump version | Add description and bump version
| Python | mit | jusbrasil/kube-render | ---
+++
@@ -1,11 +1,12 @@
from setuptools import setup
-__version__ = '0.2.2'
+__version__ = '0.2.3'
setup(
name='kuberender',
version=__version__,
py_modules=['kuberender'],
+ description='A tool to render and apply Kubernetes manifests using Jinja2',
install_requires=[
'Jinja2==2... |
676a1d3c74e526bd8cc67e97d89db2da7e207637 | setup.py | setup.py | """
Py-Tree-sitter
"""
import platform
from setuptools import setup, Extension
setup(
name = "tree_sitter",
version = "0.0.8",
maintainer = "Max Brunsfeld",
maintainer_email = "maxbrunsfeld@gmail.com",
author = "Max Brunsfeld",
author_email = "maxbrunsfeld@gmail.com",
url = "https://gith... | """
Py-Tree-sitter
"""
import platform
from setuptools import setup, Extension
setup(
name = "tree_sitter",
version = "0.0.8",
maintainer = "Max Brunsfeld",
maintainer_email = "maxbrunsfeld@gmail.com",
author = "Max Brunsfeld",
author_email = "maxbrunsfeld@gmail.com",
url = "https://gith... | Remove an incorrect documentation URL | Remove an incorrect documentation URL
Fixes #9.
| Python | mit | tree-sitter/py-tree-sitter,tree-sitter/py-tree-sitter,tree-sitter/py-tree-sitter | ---
+++
@@ -43,6 +43,5 @@
],
project_urls = {
'Source': 'https://github.com/tree-sitter/py-tree-sitter',
- 'Documentation': 'http://initd.org/psycopg/docs/',
}
) |
20596e2ff6c0d107362628770db4602e5089c7de | setup.py | setup.py | import versioneer
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Read long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='tohu',
... | import versioneer
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Read long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='tohu',
... | Add geojson as required dependency | Add geojson as required dependency
| Python | mit | maxalbert/tohu | ---
+++
@@ -30,7 +30,7 @@
'Programming Language :: Python :: 3.6',
],
packages=['tohu', 'tohu/v4'],
- install_requires=['attrs', 'bidict', 'faker', 'pandas', 'psycopg2-binary', 'shapely', 'sqlalchemy', 'tqdm'],
+ install_requires=['attrs', 'bidict', 'faker' 'geojson', 'pandas', 'psycopg2-bina... |
ae8a38c5e3952a98a586db1df15fd8b4527441c6 | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=nat... | #!/usr/bin/env python
import os
import sys
import io
try:
import setuptools
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, Extension
from setuptools import find_packages
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=nat... | Include windows.cpp only on Windows | Include windows.cpp only on Windows | Python | apache-2.0 | ulikoehler/cv_algorithms,ulikoehler/cv_algorithms | ---
+++
@@ -12,13 +12,14 @@
extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"]
extra_link_args = [] if os.name == 'nt' else ["-g"]
+platform_src = ["src/windows.cpp"] if os.name == 'nt' else []
mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms',
s... |
bf57dc8255df91954701fc13ca08e1999b9d2d39 | setup.py | setup.py | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'pyramid_zodbconn',
'pyramid_tm',
'pyramid_debugtoolbar',
... | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'pyramid_zodbconn',
'pyramid_tm',
'pyramid_debugtoolbar',
... | Add author and URL info to make mkrelease happy. | Add author and URL info to make mkrelease happy.
| Python | bsd-3-clause | ucla/PushHubCore | ---
+++
@@ -31,9 +31,9 @@
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
- author='',
- author_email='',
- url='',
+ author='Six Feet Up',
+ author_email='info@sixfeetup.com',
+ url='http://www.sixfeetup.com',
... |
af802bd8c7f8787f80caf64f226edc996ac6fc3b | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='tangled',
version='0.1a3.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages... | from setuptools import setup
setup(
name='tangled',
version='0.1a3.dev0',
description='Tangled namespace and utilities',
long_description=open('README.rst').read(),
url='http://tangledframework.org/',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
packages=[
'tan... | Update package configuration, pt. ii | Update package configuration, pt. ii
| Python | mit | TangledWeb/tangled | ---
+++
@@ -1,4 +1,4 @@
-from setuptools import setup, find_packages
+from setuptools import setup
setup(
@@ -9,7 +9,12 @@
url='http://tangledframework.org/',
author='Wyatt Baldwin',
author_email='self@wyattbaldwin.com',
- packages=find_packages(),
+ packages=[
+ 'tangled',
+ '... |
a8fe2b52a418718bbde4214efc44cb59a7175430 | setup.py | setup.py | #from distutils.core import setup
from setuptools import setup
setup(
name='nubomedia',
version='0.1',
packages=['core', 'test', 'util', 'wsgi', 'model'],
install_requires=[
'python-heatclient',
'bottle',
],
url='',
license='',
author='mpa',
author_email='',
description='Setuptool for Nubomed... | #from distutils.core import setup
from setuptools import setup
setup(
name='nubomedia',
version='0.1',
packages=['core', 'test', 'util', 'wsgi', 'model'],
install_requires=[
'python-heatclient',
'bottle',
],
url='',
license='',
author='mpa',
author_email='',
description='Nubomedia',
)
| Fix bugs in install script. Now it works fine. | Fix bugs in install script. Now it works fine.
| Python | apache-2.0 | manue1/connectivity-manager-agent,manue1/connectivity-manager-agent | ---
+++
@@ -13,5 +13,5 @@
license='',
author='mpa',
author_email='',
- description='Setuptool for Nubomedia',
+ description='Nubomedia',
) |
b10412389ee886633d1721063489159252e759e8 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='bfg9000',
version='0.1.0pre',
license='BSD',
author='Jim Porter',
author_email='porterj@alum.rit.edu',
packages=find_packages(exclude=['test']),
entry_points={
'console_scripts': ['bfg9000=bfg9000.driver:main'],
},
... | from setuptools import setup, find_packages
setup(
name='bfg9000',
version='0.1.0-dev',
license='BSD',
author='Jim Porter',
author_email='porterj@alum.rit.edu',
packages=find_packages(exclude=['test']),
entry_points={
'console_scripts': ['bfg9000=bfg9000.driver:main'],
},
... | Fix version number to comply with PEP 440 | Fix version number to comply with PEP 440
| Python | bsd-3-clause | jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000,jimporter/bfg9000 | ---
+++
@@ -2,7 +2,7 @@
setup(
name='bfg9000',
- version='0.1.0pre',
+ version='0.1.0-dev',
license='BSD',
author='Jim Porter', |
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 | ---
+++
@@ -17,7 +17,7 @@
description='OVF implementation',
url='http://open-ovf.sourceforge.net',
license='EPL',
- packages=['ovf', 'ovf.commands'],
+ packages=['ovf', 'ovf.commands', 'ovf.env'],
package_dir = {'': CODE_BASE_DIR},
scripts=list_scripts(),
... |
c19c69926e54e8268b7587a91264a976724a8801 | setup.py | setup.py | from distutils.core import setup
setup(
name='scrAPI Utils',
version='0.4.7',
author='Chris Seto',
author_email='Chris@seto.xyz',
packages=['scrapi.linter'],
package_data={'scrapi.linter': ['../__init__.py']},
url='http://www.github.com/chrisseto/scrapi',
license='LICENSE.txt',
desc... | from distutils.core import setup
setup(
name='scrAPI Utils',
version='0.4.8',
author='Chris Seto',
author_email='Chris@seto.xyz',
packages=['scrapi.linter'],
package_data={'scrapi.linter': ['../__init__.py']},
url='http://www.github.com/chrisseto/scrapi',
license='LICENSE.txt',
desc... | Increment version number for latest linter version | Increment version number for latest linter version
| Python | apache-2.0 | fabianvf/scrapi,mehanig/scrapi,fabianvf/scrapi,mehanig/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,ostwald/scrapi,jeffreyliu3230/scrapi,icereval/scrapi,felliott/scrapi,erinspace/scrapi,alexgarciac/scrapi,felliott/scrapi,CenterForOpenScience/scrapi | ---
+++
@@ -2,7 +2,7 @@
setup(
name='scrAPI Utils',
- version='0.4.7',
+ version='0.4.8',
author='Chris Seto',
author_email='Chris@seto.xyz',
packages=['scrapi.linter'], |
b785a0dd83b6521d62e5d52c5c4c8115fa4b98fc | setup.py | setup.py | from setuptools import find_packages, setup
setup(
name='txkazoo',
version='0.0.4',
description='Twisted binding for Kazoo',
maintainer='Manish Tomar',
maintainer_email='manish.tomar@rackspace.com',
license='Apache 2.0',
packages=find_packages(),
install_requires=['twisted==13.2.0', 'ka... | from setuptools import find_packages, setup
setup(
name='txkazoo',
version='0.0.4',
description='Twisted binding for Kazoo',
long_description=open("README.md").read(),
url="https://github.com/rackerlabs/txkazoo",
maintainer='Manish Tomar',
maintainer_email='manish.tomar@rackspace.com',
... | Add long_description from README + URL | Add long_description from README + URL
| Python | apache-2.0 | rackerlabs/txkazoo | ---
+++
@@ -3,10 +3,15 @@
setup(
name='txkazoo',
version='0.0.4',
+
description='Twisted binding for Kazoo',
+ long_description=open("README.md").read(),
+ url="https://github.com/rackerlabs/txkazoo",
+
maintainer='Manish Tomar',
maintainer_email='manish.tomar@rackspace.com',
lice... |
3cc473fb6316fffa3c19980115f800518dcee115 | setup.py | setup.py | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | Fix missing raven.processors in build | Fix missing raven.processors in build
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | ---
+++
@@ -21,7 +21,7 @@
"numpy.core._methods",
"numpy.lib",
"numpy.lib.format"
- ],
+ "raven.processors"
"namespace_packages": [
"virtool"
], |
9529a7321b4cfc74594d7391baa760959fcb7568 | setup.py | setup.py | from setuptools import setup
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytest
errco... | from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import pytes... | Add entry point for quick_add_keys_to_file | Add entry point for quick_add_keys_to_file
| Python | bsd-3-clause | mwcraig/msumastro | ---
+++
@@ -1,4 +1,4 @@
-from setuptools import setup
+from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
@@ -16,21 +16,29 @@
setup(
name='msumastro',
- version='IXME',
+ version='FIXME',
description='Process FITS files painlessly',
+ ... |
352d8578eabe5c0474875c5ddcff9f97fc7df73e | setup.py | setup.py | from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='baldr',
version='0.4.5',
url='https://github.com/timsavage/baldr',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredby... | from setuptools import setup, find_packages
try:
long_description = open("README.rst").read()
except IOError:
long_description = ""
setup(
name='baldr',
version='0.4.5',
url='https://github.com/timsavage/baldr',
license='LICENSE',
author='Tim Savage',
author_email='tim.savage@poweredby... | Exclude test_runner from dist package | Exclude test_runner from dist package
| Python | bsd-3-clause | timsavage/baldr,timsavage/baldr | ---
+++
@@ -14,7 +14,7 @@
author_email='tim.savage@poweredbypenguins.org',
description='Odin integration to Django',
long_description=long_description,
- packages=find_packages(),
+ packages=find_packages(exclude=("django_test_runner",)),
install_requires=['six', 'odin>=0.5', 'django>=1.5'],... |
a709f5de366da5121e1d03f5de1ddd2b202c661e | setup.py | setup.py | from setuptools import setup
setup(
name="servicemanager",
version="2.0.6",
description="A python tool to manage developing and testing with lots of microservices",
url="https://github.com/hmrc/service-manager",
author="hmrc-web-operations",
license="Apache Licence 2.0",
packages=[
... | from setuptools import setup
setup(
name="servicemanager",
version="2.0.7",
description="A python tool to manage developing and testing with lots of microservices",
url="https://github.com/hmrc/service-manager",
author="hmrc-web-operations",
license="Apache Licence 2.0",
packages=[
... | Allow later patch versions of argcomplete | Allow later patch versions of argcomplete
Using ~ should install 1.12.1 if available (which it is)
Specifically, we want the changes here:
https://github.com/kislyuk/argcomplete/issues/321
importlib-metadata 2.0 was released, and argcomplete defined that 2.0
should never be use that version, until the most recent cu... | Python | apache-2.0 | hmrc/service-manager,hmrc/service-manager,hmrc/service-manager,hmrc/service-manager | ---
+++
@@ -2,7 +2,7 @@
setup(
name="servicemanager",
- version="2.0.6",
+ version="2.0.7",
description="A python tool to manage developing and testing with lots of microservices",
url="https://github.com/hmrc/service-manager",
author="hmrc-web-operations",
@@ -20,7 +20,7 @@
"bot... |
b5d801c561b4a73ba7ea41665b7fe756fc56689d | setup.py | setup.py | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
SCRIPT_DIR = os.path.dirname(__file__)
if not SCRIPT_DIR:
SCRIPT_DIR = os.getcwd()
SRC_PREFIX = 'src'
packages = find_packages(SRC_PREFIX)
setup(
name='cmdline',
version='0.0.0',
description='Utilities for consistent... | #!/usr/bin/env python
import os
from setuptools import find_packages, setup
SCRIPT_DIR = os.path.dirname(__file__)
if not SCRIPT_DIR:
SCRIPT_DIR = os.getcwd()
SRC_PREFIX = 'src'
def readme():
with open('README.md') as f:
return f.read()
packages = find_packages(SRC_PREFIX)
setup(
name='cmd... | Add markdown content type for README | Add markdown content type for README
| Python | apache-2.0 | rca/cmdline | ---
+++
@@ -10,6 +10,11 @@
SRC_PREFIX = 'src'
+def readme():
+ with open('README.md') as f:
+ return f.read()
+
+
packages = find_packages(SRC_PREFIX)
setup(
@@ -20,7 +25,8 @@
author_email='r@rreboto.com',
package_dir={'': SRC_PREFIX},
packages=packages,
- long_description... |
1d391ef70edcb81a7a6f27685e2dca103b24bd66 | app.py | app.py | #!/usr/bin/env python
import sys
import os
from flask import Flask, render_template, make_response
app = Flask(__name__)
@app.route('/')
def index():
"""Render index template"""
return render_template('index.html')
@app.route('/styles.css')
def css():
"""Render widget styles"""
response = make_res... | #!/usr/bin/env python
import sys
import os
import yaml
import inspect
from flask import Flask, render_template, make_response, Response, \
stream_with_context
import workers
app = Flask(__name__)
active_workers = []
@app.route('/')
def index():
"""Render index template"""
return render_template('index.... | Implement server-sent events and basic worker support | Implement server-sent events and basic worker support
| Python | mit | martinp/jarvis2,mpolden/jarvis2,Foxboron/Frank,martinp/jarvis2,Foxboron/Frank,mpolden/jarvis2,Foxboron/Frank,martinp/jarvis2,mpolden/jarvis2 | ---
+++
@@ -2,9 +2,15 @@
import sys
import os
-from flask import Flask, render_template, make_response
+import yaml
+import inspect
+from flask import Flask, render_template, make_response, Response, \
+ stream_with_context
+
+import workers
app = Flask(__name__)
+active_workers = []
@app.route('/')
@@... |
994fc67234a60fbe2c8f4146fa72089ee94432a9 | setup.py | setup.py | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="sphinx-refdoc",
version=read('VERSION').strip(),
author="Mateusz 'novo' Klos",
author_email="novopl@gmail.com",
license="MIT",
descriptio... | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="sphinx-refdoc",
url="https://github.com/novopl/sphinx-refdoc",
version=read('VERSION').strip(),
author="Mateusz 'novo' Klos",
author_email="n... | Add URL to the package descirption | Add URL to the package descirption
| Python | mit | novopl/sphinx-refdoc | ---
+++
@@ -8,6 +8,7 @@
setup(
name="sphinx-refdoc",
+ url="https://github.com/novopl/sphinx-refdoc",
version=read('VERSION').strip(),
author="Mateusz 'novo' Klos",
author_email="novopl@gmail.com", |
e024f15d20f974a3dc4922631264d79d93a26e5f | setup.py | setup.py | from setuptools import setup, find_packages
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
setup(name='substance',
version=__versi... | from setuptools import setup, find_packages
import platform
with open('README.rst') as f:
readme = f.read()
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts==0.3.3', 'jinja2']
if 'Darwin' in platform.syste... | Add macfsevents dependency on Mac OS X | Add macfsevents dependency on Mac OS X
| Python | apache-2.0 | turbulent/substance,turbulent/substance | ---
+++
@@ -1,4 +1,5 @@
from setuptools import setup, find_packages
+import platform
with open('README.rst') as f:
readme = f.read()
@@ -6,6 +7,9 @@
execfile('substance/_version.py')
install_requires = ['setuptools>=1.1.3', 'PyYAML', 'tabulate', 'paramiko', 'netaddr', 'requests', 'tinydb', 'python_hosts=... |
4c43e16c8f39007e1e91195b40e80b53f67b5823 | app.py | app.py | import json
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_templa... | import json
import os
import webapp2
from webapp2_extras import jinja2
class BaseHandler(webapp2.RequestHandler):
@webapp2.cached_property
def jinja2(self):
return jinja2.get_jinja2(app=self.app)
def render_template(self, filename, **template_args):
self.response.write(self.jinja2.render_templa... | Return Status 422 on bad JSON content | Return Status 422 on bad JSON content
| Python | mit | supermitch/mech-ai,supermitch/mech-ai,supermitch/mech-ai | ---
+++
@@ -19,7 +19,10 @@
class RegistrationHandler(webapp2.RequestHandler):
def post(self):
json_object = json.loads(self.request.body)
- self.response.write('Registration Received {}'.format(json_object))
+ if not 'username' in json_object:
+ webapp2.abort(422, detail='Field... |
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 ... | #!/usr/bin/env python
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... | Add --config argument as a path to the config file | Add --config argument as a path to the config file
| Python | mit | azeier/hearthbot | ---
+++
@@ -1,22 +1,32 @@
+#!/usr/bin/env python
+
+import argparse
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)
+def main():
+ p = argpars... |
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 | ---
+++
@@ -1,12 +1,31 @@
+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):
+... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.