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 |
|---|---|---|---|---|---|---|---|---|---|---|
1c78dfa0e0d1905910476b4052e42de287a70b74 | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver"
apps = []
if len(sys.argv) > 1:
... | #!/usr/bin/env python
import os
import sys
import string
def main():
"""
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver --noinput"
apps = []
if len(sys.argv)... | Update to the run tests script to force database deletion if the test database exists. | Update to the run tests script to force database deletion if the test database exists.
| Python | mit | jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,csdl/makahiki,yongwen/makahiki,yongwen/makahiki,jtakayama/makahiki-draft,yongwen/makahiki,justinslee/Wai-Not-Makahiki,csdl/makahiki,jtakayama/makahiki-draft,yongwen/makahiki,csdl/makahiki,csdl/makahiki,jtakayama/makahiki-draft,jtakayama/ics691-setupbooster,jtakayam... | ---
+++
@@ -9,7 +9,7 @@
Executes the tests. Requires the CherryPy live server to be installed.
"""
command = "python manage.py test"
- options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver"
+ options = "--exe --with-selenium --with-selenium-fixtures --with-cherrypyliveserver ... |
20124d599c6305889315847c15329c02efdd2b8c | migrations/versions/0313_email_access_validated_at.py | migrations/versions/0313_email_access_validated_at.py | """
Revision ID: 0313_email_access_validated_at
Revises: 0312_populate_returned_letters
Create Date: 2020-01-28 18:03:22.237386
"""
from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto gen... | """
Revision ID: 0313_email_access_validated_at
Revises: 0312_populate_returned_letters
Create Date: 2020-01-28 18:03:22.237386
"""
from alembic import op
import sqlalchemy as sa
revision = '0313_email_access_validated_at'
down_revision = '0312_populate_returned_letters'
def upgrade():
# ### commands auto gen... | Make sure email_access_validated_at is not null after being populated | Make sure email_access_validated_at is not null after being populated
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -22,8 +22,6 @@
users
SET
email_access_validated_at = created_at
- WHERE
- auth_type = 'sms_auth'
""")
op.execute("""
UPDATE
@@ -32,6 +30,8 @@
email_access_validated_at = logged_in_at
WHERE
auth_type =... |
d09fb55bd49e266901305b9126077f44f7a1301e | annoying/functions.py | annoying/functions.py | from django.shortcuts import _get_queryset
from django.conf import settings
def get_object_or_None(klass, *args, **kwargs):
"""
Uses get() to return an object or None if the object does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are ... | from django.shortcuts import _get_queryset
from django.conf import settings
def get_object_or_None(klass, *args, **kwargs):
"""
Uses get() to return an object or None if the object does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are ... | Set default for get_config to None. | Set default for get_config to None. | Python | bsd-3-clause | skorokithakis/django-annoying,artscoop/django-annoying,kabakchey/django-annoying,skorokithakis/django-annoying,kabakchey/django-annoying,YPCrumble/django-annoying,JshWright/django-annoying | ---
+++
@@ -20,7 +20,7 @@
-def get_config(key, default):
+def get_config(key, default=None):
"""
Get settings from django.conf if exists,
return default value otherwise |
78b2978c3e0e56c4c75a3a6b532e02c995ca69ed | openedx/core/djangoapps/user_api/permissions/views.py | openedx/core/djangoapps/user_api/permissions/views.py | """
NOTE: this API is WIP and has not yet been approved. Do not use this API
without talking to Christina or Andy.
For more information, see:
https://openedx.atlassian.net/wiki/display/TNL/User+API
"""
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import stat... | from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from openedx.core.lib.api.authentication import (
SessionAuthenticationAllowInactiveUser,
OAuth2AuthenticationAllowInactiveUser,
)
from openedx.core.lib.api.parsers import MergePatchParser
fr... | Remove unused import and redundant comment | Remove unused import and redundant comment
| Python | agpl-3.0 | mbareta/edx-platform-ft,mbareta/edx-platform-ft,mbareta/edx-platform-ft,mbareta/edx-platform-ft | ---
+++
@@ -1,24 +1,12 @@
-"""
-NOTE: this API is WIP and has not yet been approved. Do not use this API
-without talking to Christina or Andy.
-
-For more information, see:
-https://openedx.atlassian.net/wiki/display/TNL/User+API
-"""
from rest_framework.views import APIView
from rest_framework.response import Res... |
cadee051a462de765bab59ac42d6b372fa49c033 | examples/logfile.py | examples/logfile.py | """
Output an Eliot message to a log file using the threaded log writer.
"""
from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger, addDestination
_logger = Logger()
def main(reactor):
p... | """
Output an Eliot message to a log file using the threaded log writer.
"""
from __future__ import unicode_literals, print_function
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
from eliot import Message, Logger
_logger = Logger()
def main(reactor):
print("Logging to... | Fix bug where the service was added as a destination one time too many. | Fix bug where the service was added as a destination one time too many.
| Python | apache-2.0 | iffy/eliot,ClusterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot,ScatterHQ/eliot | ---
+++
@@ -6,7 +6,7 @@
from twisted.internet.task import react
from eliot.logwriter import ThreadedFileWriter
-from eliot import Message, Logger, addDestination
+from eliot import Message, Logger
_logger = Logger()
@@ -16,10 +16,10 @@
def main(reactor):
print("Logging to example-eliot.log...")
lo... |
9f10dbdabe61ed841c0def319f021a4735f39217 | src/sct/templates/__init__.py | src/sct/templates/__init__.py | # -*- coding: utf-8 -*-
'''
Copyright 2014 Universitatea de Vest din Timișoara
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 appli... | # -*- coding: utf-8 -*-
"""
Copyright 2014 Universitatea de Vest din Timișoara
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 appli... | Add provisional (needs to be replaced with pkg_resources entry point discovery) template registry | Add provisional (needs to be replaced with pkg_resources entry point discovery) template registry
| Python | apache-2.0 | mneagul/scape-cloud-toolkit,mneagul/scape-cloud-toolkit,mneagul/scape-cloud-toolkit | ---
+++
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-'''
+"""
Copyright 2014 Universitatea de Vest din Timișoara
Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,5 +17,31 @@
@author: Marian Neagul <marian@info.uvt.ro>
@contact: marian@info.uvt.ro
@copyright: 2014 Universitatea de Vest din Ti... |
a9a794384c6f4c153768cf609f3d8dc657f59daf | campaigns/scrapers.py | campaigns/scrapers.py | import requests
import json
class KickstarterScraper(object):
# TODO: get list of all categories from projects for rendering possible list on main view
base_url = "https://www.kickstarter.com/"
projects_query_path = "projects/search.json?search={0}&term={1}"
@classmethod
def scrape_projects(cls... | import requests
import json
from bs4 import BeautifulSoup
class KickstarterScraper(object):
# TODO: get list of all categories from projects for rendering possible list on main view
base_url = "https://www.kickstarter.com/"
projects_query_path = "projects/search.json?search={0}&term={1}"
@classmeth... | Add base logic for finding Give Forward campaigns by query that are almost funded | Add base logic for finding Give Forward campaigns by query that are almost funded
| Python | mit | lorenanicole/almost_funded,lorenanicole/almost_funded,lorenanicole/almost_funded | ---
+++
@@ -1,5 +1,6 @@
import requests
import json
+from bs4 import BeautifulSoup
class KickstarterScraper(object):
@@ -18,3 +19,31 @@
print content
return content
+
+
+class GiveForwardScraper(object):
+ base_url = "http://www.giveforward.com/"
+ fundraiser_query_path = "fundrai... |
19dd4495b09a0019fcce2cfb21b083724033dd7f | handover_service.py | handover_service.py | from flask import Flask
app = Flask(__name__)
VERSION_PREFIX="/api/v1"
@app.route(VERSION_PREFIX + "/handovers")
def handovers():
return "handovers\n"
@app.route(VERSION_PREFIX + "/drafts")
def drafts():
return "drafts\n"
if __name__ == "__main__":
app.run()
| from flask import Flask
from flask_restful import Resource, Api
app = Flask(__name__)
api = Api(app)
class Handover(Resource):
def get(self):
return [{'handover' : 42}]
class Draft(Resource):
def get(self):
return [{'draft' : 1024}]
api.add_resource(Handover, '/api/v1/handovers')
api.add_res... | Switch skeleton API to use flask-restful | Switch skeleton API to use flask-restful
| Python | mit | Duke-GCB/DukeDSHandoverService,Duke-GCB/DukeDSHandoverService,Duke-GCB/DukeDSHandoverService | ---
+++
@@ -1,15 +1,19 @@
from flask import Flask
+from flask_restful import Resource, Api
+
app = Flask(__name__)
+api = Api(app)
-VERSION_PREFIX="/api/v1"
+class Handover(Resource):
+ def get(self):
+ return [{'handover' : 42}]
-@app.route(VERSION_PREFIX + "/handovers")
-def handovers():
- return "... |
0534c1cdeb92503a90ef309dee6edddb45234bf7 | comrade/users/urls.py | comrade/users/urls.py | from django.conf.urls.defaults import *
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/', 'login', name='login'),
url(r'^logout/', 'logout', {'next_page':'/'}, name='logout'),
url(r'^password/forgot/$', 'password_reset',
# LH #269 - ideally this wouldn't be hard coded
... | from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.utils.functional import lazy
reverse_lazy = lazy(reverse, unicode)
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/', 'login', name='login'),
url(r'^logout/', 'logout', {'next_page':'/'}, name='lo... | Resolve old Django 1.1 bug in URLs to keep it DRY. | Resolve old Django 1.1 bug in URLs to keep it DRY.
| Python | mit | bueda/django-comrade | ---
+++
@@ -1,18 +1,21 @@
from django.conf.urls.defaults import *
+from django.core.urlresolvers import reverse
+from django.utils.functional import lazy
+
+reverse_lazy = lazy(reverse, unicode)
urlpatterns = patterns('django.contrib.auth.views',
url(r'^login/', 'login', name='login'),
url(r'^logout/', ... |
3572171a917138982cf7e329e5293e1345a9e76d | comics/comics/gws.py | comics/comics/gws.py | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Girls With Slingshots"
language = "en"
url = "http://www.girlswithslingshots.com/"
start_date = "2004-09-30"
rights = "Danielle Corsetto"
class... | from comics.aggregator.crawler import CrawlerBase, CrawlerImage
from comics.core.comic_data import ComicDataBase
class ComicData(ComicDataBase):
name = "Girls With Slingshots"
language = "en"
url = "http://www.girlswithslingshots.com/"
start_date = "2004-09-30"
rights = "Danielle Corsetto"
class... | Update "Girls With Slingshots" after feed change | Update "Girls With Slingshots" after feed change
| Python | agpl-3.0 | jodal/comics,datagutten/comics,jodal/comics,jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics | ---
+++
@@ -19,7 +19,7 @@
feed = self.parse_feed("http://www.girlswithslingshots.com/feed/")
for entry in feed.for_date(pub_date):
page = self.parse_page(entry.link)
- url = page.src("img#comic")
+ url = page.src("img#cc-comic")
title = entry.title.rep... |
00a3da330668284f700275c7fc3072c792eff374 | kolibri/__init__.py | kolibri/__init__.py | """
CAUTION! Keep everything here at at minimum. Do not import stuff.
This module is imported in setup.py, so you cannot for instance
import a dependency.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils import env
from .utils.version ... | """
CAUTION! Keep everything here at at minimum. Do not import stuff.
This module is imported in setup.py, so you cannot for instance
import a dependency.
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from .utils import env
from .utils.version ... | Update VERSION to 0.12.5 final | Update VERSION to 0.12.5 final | Python | mit | indirectlylit/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,mrpau/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,mrpau/kolibri | ---
+++
@@ -15,7 +15,7 @@
#: This may not be the exact version as it's subject to modification with
#: get_version() - use ``kolibri.__version__`` for the exact version string.
-VERSION = (0, 12, 5, "beta", 0)
+VERSION = (0, 12, 5, "final", 0)
__author__ = "Learning Equality"
__email__ = "info@learningequalit... |
e9e4c622ff667e475986e1544ec78b0604b8a511 | girder_worker/tasks.py | girder_worker/tasks.py | import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(tasks, *pargs, **kwargs):
jobInfo = kwargs.pop('jobInfo', {})
retval = 0
kwargs['_jo... | import core
from girder_worker.utils import JobStatus
from .app import app
def _cleanup(*args, **kwargs):
core.events.trigger('cleanup')
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
if hasattr(task,... | Fix typo from bad conflict resolution during merge | Fix typo from bad conflict resolution during merge
| Python | apache-2.0 | girder/girder_worker,girder/girder_worker,girder/girder_worker | ---
+++
@@ -8,10 +8,7 @@
@app.task(name='girder_worker.run', bind=True, after_return=_cleanup)
-def run(tasks, *pargs, **kwargs):
- jobInfo = kwargs.pop('jobInfo', {})
- retval = 0
-
+def run(task, *pargs, **kwargs):
kwargs['_job_manager'] = task.job_manager \
if hasattr(task, 'job_manager') ... |
0a4922dba3367a747d7460b5c1b59c49c67f3026 | hcalendar/hcalendar.py | hcalendar/hcalendar.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .vcalendar import vCalendar
from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, valu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .vcalendar import vCalendar
from bs4 import BeautifulSoup
class hCalendar(object):
def __init__(self, markup, valu... | Add missing parser argument to BeautifulSoup instance | Add missing parser argument to BeautifulSoup instance
| Python | mit | mback2k/python-hcalendar | ---
+++
@@ -13,7 +13,7 @@
if isinstance(markup, BeautifulSoup):
self._soup = markup
else:
- self._soup = BeautifulSoup(markup)
+ self._soup = BeautifulSoup(markup, 'html.parser')
if value:
self._soup = self._soup.find(**{key: value})
... |
9a32f922e6d5ec6e5bd22eccbe3dceaef7bbd7dc | tailor/tests/utils/charformat_test.py | tailor/tests/utils/charformat_test.py | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charform... | import unittest
from tailor.utils import charformat
class MyTestCase(unittest.TestCase):
def is_upper_camel_case_test_upper_camel_case_name(self):
self.assertTrue(charformat.is_upper_camel_case('HelloWorld'))
def is_upper_camel_case_test_lower_camel_case_name(self):
self.assertFalse(charform... | Add special character name test case | Add special character name test case
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor | ---
+++
@@ -19,5 +19,9 @@
def is_upper_camel_case_test_numeric_name(self):
self.assertFalse(charformat.is_upper_camel_case('1ello_world'))
+ def is_upper_camel_case_test_special_character_name(self):
+ self.assertFalse(charformat.is_upper_camel_case('!ello_world'))
+
+
if __name__ == '__mai... |
fd48211548c8c2d5daec0994155ddb7e8d226882 | tests/test_anki_sync.py | tests/test_anki_sync.py | import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
m, stora... | import pytest
import os
import rememberberry
from rememberscript import RememberMachine, FileStorage
from rememberberry.testing import tmp_data_path, assert_replies, get_isolated_story
@pytest.mark.asyncio
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
storage[... | Fix missing username in test | Fix missing username in test
| Python | agpl-3.0 | rememberberry/rememberberry-server,rememberberry/rememberberry-server | ---
+++
@@ -8,6 +8,7 @@
@tmp_data_path('/tmp/data/', delete=True)
async def test_anki_account():
storage = FileStorage()
+ storage['username'] = 'alice'
m, storage = get_isolated_story('login_anki', storage)
await assert_replies(m.reply(''), 'What is your Anki username?')
await assert_replies... |
2c38fea1434f8591957c2707359412151c4b6c43 | tests/test_timezones.py | tests/test_timezones.py | import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
print('xxx', utc, cst)
self.assertEqual(2000, c... | import unittest
import datetime
from garage.timezones import TimeZone
class TimeZoneTest(unittest.TestCase):
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
self.assertEqual(2000, cst.year)
self.assertEqu... | Remove print in unit test | Remove print in unit test
| Python | mit | clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage | ---
+++
@@ -10,7 +10,6 @@
def test_time_zone(self):
utc = datetime.datetime(2000, 1, 2, 3, 4, 0, 0, TimeZone.UTC)
cst = utc.astimezone(TimeZone.CST)
- print('xxx', utc, cst)
self.assertEqual(2000, cst.year)
self.assertEqual(1, cst.month)
self.assertEqual(2, cst... |
b1d3a0c79a52ca1987ea08a546213e1135539927 | tools/bots/ddc_tests.py | tools/bots/ddc_tests.py | #!/usr/bin/env python
#
# Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import os.path
import shutil
import sys
import subprocess
import bot
im... | #!/usr/bin/env python
#
# Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import os.path
import shutil
import sys
import subprocess
import bot
im... | Set CHROME_BIN on DDC bot | Set CHROME_BIN on DDC bot
Noticed the Linux bot is failing on this:
https://build.chromium.org/p/client.dart.fyi/builders/ddc-linux-release-be/builds/1724/steps/ddc%20tests/logs/stdio
R=whesse@google.com
Review-Url: https://codereview.chromium.org/2640093002 .
| Python | bsd-3-clause | dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/... | ---
+++
@@ -30,4 +30,4 @@
# These mirror pkg/dev_compiler/tool/browser_test.sh.
bot.RunProcess(['npm', 'install'])
- bot.RunProcess(['npm', 'test'])
+ bot.RunProcess(['npm', 'test'], {'CHROME_BIN': 'chrome'}) |
c143bc14be8d486d313056c0d1313e03ac438284 | examples/ex_aps_parser.py | examples/ex_aps_parser.py | from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads/fulltext/source... | from __future__ import print_function
import os
import glob
import pyingest.parsers.aps as aps
import pyingest.parsers.arxiv as arxiv
import pyingest.serializers.classic
import traceback
import json
import xmltodict
from datetime import datetime
import sys
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads/full... | Use open mode syntax on example file | Use open mode syntax on example file
| Python | mit | adsabs/adsabs-pyingest,adsabs/adsabs-pyingest,adsabs/adsabs-pyingest | ---
+++
@@ -8,24 +8,31 @@
import json
import xmltodict
from datetime import datetime
+import sys
input_list = 'bibc.2.out'
testfile=[]
xmldir = '/proj/ads/fulltext/sources/downloads/cache/APS_HARVEST/harvest.aps.org/v2/journals/articles/'
xmltail = '/fulltext.xml'
-with open(input_list,'rU') as fi:
+
+if sys... |
7d9115aaa429f0a6453c8fcc75c77abc2bdaec93 | sort/heap_sort.py | sort/heap_sort.py | def heap_sort(arr):
""" Heapsort
Complexity: O(n log(n))
"""
pass
def heapify(arr):
pass
array = [1,5,65,23,57,1232,-1,-5,-2,242,100,4,423,2,564,9,0,10,43,64]
print(array)
heap_sort(array)
print(array) | Set up basic structure of code | Set up basic structure of code
| Python | mit | keon/algorithms,amaozhao/algorithms | ---
+++
@@ -0,0 +1,13 @@
+def heap_sort(arr):
+ """ Heapsort
+ Complexity: O(n log(n))
+ """
+ pass
+
+def heapify(arr):
+ pass
+
+array = [1,5,65,23,57,1232,-1,-5,-2,242,100,4,423,2,564,9,0,10,43,64]
+print(array)
+heap_sort(array)
+print(array) | |
bfd166e9679e6fa06e694fd5e587fcf10186d79b | vx_intro.py | vx_intro.py | import vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tic... | import vx
import math
import os
import sys
_tick_functions = []
def _register_tick_function(f, front=False):
if front:
_tick_functions.insert(0, f)
else:
_tick_functions.append(f)
def _tick():
for f in _tick_functions:
f()
vx.my_vx = _tick
vx.register_tick_function = _register_tic... | Fix a crash if there is no ~/.python/rc.py | Fix a crash if there is no ~/.python/rc.py
| Python | mit | philipdexter/vx,philipdexter/vx | ---
+++
@@ -41,4 +41,7 @@
vx.default_start = _default_start
sys.path.append(os.path.expanduser('~/.python'))
-import rc
+try:
+ import rc
+except ImportError:
+ pass # just means there was no ~/.python/rc module |
bc593f1716a8e36e65cf75a58e524e77d38d5d9c | notation/statistics.py | notation/statistics.py | # encoding: utf-8
# included for ease of use with Python 2 (which has no statistics package)
def mean(values):
return float(sum(values)) / len(values)
def median(values):
middle = (len(values) - 1) // 2
if len(values) % 2:
return values[middle]
else:
return mean(values[middle:middle ... | # encoding: utf-8
# included for ease of use with Python 2 (which has no statistics package)
def mean(values):
return float(sum(values)) / len(values)
def quantile(p):
def bound_quantile(values):
ix = int(len(values) * p)
if len(values) % 2:
return values[ix]
elif ix < 1... | Add a rudimentary quantile factory function. | Add a rudimentary quantile factory function.
| Python | isc | debrouwere/python-ballpark | ---
+++
@@ -2,13 +2,25 @@
# included for ease of use with Python 2 (which has no statistics package)
+
def mean(values):
return float(sum(values)) / len(values)
-def median(values):
- middle = (len(values) - 1) // 2
+def quantile(p):
+ def bound_quantile(values):
+ ix = int(len(values) * p)
... |
54c856e987bf570c7bcb8c449726a5d2895c0241 | octopus/__init__.py | octopus/__init__.py |
__version__ = "trunk"
def run (runnable, logging = True):
from twisted.internet import reactor
if reactor.running:
return runnable.run()
else:
def _complete (result):
reactor.stop()
def _run ():
runnable.run().addBoth(_complete)
if logging:
import sys
from twisted.python import log
log.s... |
__version__ = "trunk"
def run (runnable, logging = True):
from twisted.internet import reactor
if reactor.running:
return runnable.run()
else:
if logging:
import sys
from twisted.python import log
log.startLogging(sys.stdout)
runnable.on("log", log.msg)
def _complete (result):
reactor.stop... | Fix octopus.run for new events model. | Fix octopus.run for new events model.
| Python | mit | richardingham/octopus,richardingham/octopus,richardingham/octopus,richardingham/octopus | ---
+++
@@ -8,17 +8,21 @@
return runnable.run()
else:
+ if logging:
+ import sys
+ from twisted.python import log
+
+ log.startLogging(sys.stdout)
+ runnable.on("log", log.msg)
+
def _complete (result):
reactor.stop()
+
+ if logging:
+ runnable.off("log", log.msg)
def _run ():
run... |
fa98f32ce9c2d4e7dff8281bf5e6f154b82599d6 | gargoyle/__init__.py | gargoyle/__init__.py | """
gargoyle
~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
__all__ = ('gargoyle', 'ConditionSet', 'autodiscover', 'VERSION')
try:
VERSION = __import__('pkg_resources') \
.get_distribution('gargoyle').version
except Exception, e:
VERSION = 'unkno... | """
gargoyle
~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
__all__ = ('gargoyle', 'ConditionSet', 'autodiscover', 'VERSION')
try:
VERSION = __import__('pkg_resources') \
.get_distribution('gargoyle').version
except Exception, e:
VERSION = 'unkno... | Use python import lib (django import lib will be removed in 1.9). | Use python import lib (django import lib will be removed in 1.9).
| Python | apache-2.0 | brilliant-org/gargoyle,brilliant-org/gargoyle,brilliant-org/gargoyle | ---
+++
@@ -25,7 +25,7 @@
"""
import copy
from django.conf import settings
- from django.utils.importlib import import_module
+ from importlib import import_module
for app in settings.INSTALLED_APPS:
# Attempt to import the app's gargoyle module. |
3443c7164e490e0607fff599c497a4fc054f3c48 | oslo_cache/_i18n.py | oslo_cache/_i18n.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
# d... | # 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
# d... | Update i18n domain to correct project name | Update i18n domain to correct project name
The current oslo_i18n domain name is listed as oslo.versionedobjects
Change-Id: I493b66efbd83fb7704fe927866a24b765feb1576
| Python | apache-2.0 | citrix-openstack-build/oslo.cache,openstack/oslo.cache,openstack/oslo.cache | ---
+++
@@ -19,7 +19,7 @@
import oslo_i18n
-_translators = oslo_i18n.TranslatorFactory(domain='oslo.versionedobjects')
+_translators = oslo_i18n.TranslatorFactory(domain='oslo.cache')
# The primary translation function using the well-known name "_"
_ = _translators.primary |
ec235e290b4428dec2db03a19d678eba52f02fb5 | keyring/getpassbackend.py | keyring/getpassbackend.py | """Specific support for getpass."""
import os
import getpass
from keyring.core import get_password as original_get_password
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
retu... | """Specific support for getpass."""
import os
import getpass
import keyring.core
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
return keyring.core.get_password(service_name, ... | Use module namespaces to distinguish names instead of 'original_' prefix | Use module namespaces to distinguish names instead of 'original_' prefix
| Python | mit | jaraco/keyring | ---
+++
@@ -2,12 +2,12 @@
import os
import getpass
-from keyring.core import get_password as original_get_password
+import keyring.core
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = get... |
4a711a2709ec5d8a8e04bb0f735fcfaa319cffdf | designate/objects/validation_error.py | designate/objects/validation_error.py | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Fix the displayed error message in V2 API | Fix the displayed error message in V2 API
Change-Id: I07c3f1ed79fa507dbe9b76eb8f5964475516754c
| Python | apache-2.0 | tonyli71/designate,openstack/designate,ionrock/designate,ionrock/designate,ramsateesh/designate,grahamhayes/designate,cneill/designate-testing,muraliselva10/designate,muraliselva10/designate,cneill/designate-testing,openstack/designate,tonyli71/designate,muraliselva10/designate,grahamhayes/designate,ionrock/designate,t... | ---
+++
@@ -11,8 +11,6 @@
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
-import six
-
from designate.objects import base
@@ -33,7 +31,7 @@
e = cls()
e.path =... |
0ae360b675f2dd0b3607af1bc7b72864e43236b2 | userreport/settings_local.EXAMPLE.py | userreport/settings_local.EXAMPLE.py | # Fill in this file and save as settings_local.py
PROJECT_NAME = 'SuperTuxKart'
PROJECT_URL = 'http://supertuxkart.net/'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
# Add the name/ip of the server that is running the stats server
ALLOWED_HOSTS = ["api.stkaddo... | # Fill in this file and save as settings_local.py
PROJECT_NAME = 'SuperTuxKart'
PROJECT_URL = 'http://supertuxkart.net/'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
# Add the name/ip of the server that is running the stats server
ALLOWED_HOSTS = ["addons.supe... | Change default example for allowed hosts | Change default example for allowed hosts
| Python | mit | leyyin/stk-stats,supertuxkart/stk-stats,leyyin/stk-stats,supertuxkart/stk-stats | ---
+++
@@ -9,7 +9,7 @@
TEMPLATE_DEBUG = True
# Add the name/ip of the server that is running the stats server
-ALLOWED_HOSTS = ["api.stkaddons.net"]
+ALLOWED_HOSTS = ["addons.supertuxkart.net"]
ADMINS = (
('Your Name', 'you@example.com'), |
6fc2e75426eb34755bf6dbedbd21a4345d9c5738 | plugins/websites.py | plugins/websites.py | import re
from smartbot import utils
class Plugin:
def on_message(self, bot, msg, reply):
match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE)
for i, url in enumerate(match):
title = utils.web.get_title(url)
if title:
reply("[{0}]: {1}".f... | import io
import re
import unittest
from smartbot import utils
class Plugin:
def on_message(self, bot, msg, reply):
match = re.findall(r"(https?://[^\s]+)", msg["message"], re.IGNORECASE)
for i, url in enumerate(match):
title = utils.web.get_title(url)
if title:
... | Add tests for website plugin | Add tests for website plugin
| Python | mit | Muzer/smartbot,Cyanogenoid/smartbot,thomasleese/smartbot-old,tomleese/smartbot | ---
+++
@@ -1,4 +1,6 @@
+import io
import re
+import unittest
from smartbot import utils
@@ -13,3 +15,14 @@
def on_help(self):
return "Echos the titles of websites for any HTTP(S) URL."
+
+
+class Test(unittest.TestCase):
+ def setUp(self):
+ self.plugin = Plugin()
+
+ def test_mess... |
58b8b63a8a8e9d1b61d8fc1a0f84f8b2a697efc3 | flask_debugtoolbar/panels/versions.py | flask_debugtoolbar/panels/versions.py | import pkg_resources
from flask_debugtoolbar.panels import DebugPanel
_ = lambda x: x
flask_version = pkg_resources.get_distribution('Flask').version
class VersionDebugPanel(DebugPanel):
"""
Panel that displays the Django version.
"""
name = 'Version'
has_content = False
def nav_title(self)... | from flask import __version__ as flask_version
from flask_debugtoolbar.panels import DebugPanel
_ = lambda x: x
class VersionDebugPanel(DebugPanel):
"""
Panel that displays the Flask version.
"""
name = 'Version'
has_content = False
def nav_title(self):
return _('Versions')
def n... | Use flask.__version__ instead of pkg_resources. | Use flask.__version__ instead of pkg_resources.
This is a simpler way of getting the Flask version.
| Python | bsd-3-clause | lepture/flask-debugtoolbar,dianchang/flask-debugtoolbar,lepture/flask-debugtoolbar,dianchang/flask-debugtoolbar,dianchang/flask-debugtoolbar | ---
+++
@@ -1,14 +1,11 @@
-import pkg_resources
-
+from flask import __version__ as flask_version
from flask_debugtoolbar.panels import DebugPanel
_ = lambda x: x
-flask_version = pkg_resources.get_distribution('Flask').version
-
class VersionDebugPanel(DebugPanel):
"""
- Panel that displays the Django... |
8852955632b0ef0250ebbe21b5bdefdecdf30e8a | tests/test_dem.py | tests/test_dem.py | import unittest
import numpy as np
class CalculationMethodsTestCase(unittest.TestCase):
def setUp(self):
self.dem = DEMGrid()
def test_calculate_slope(self):
sx, sy = self.dem._calculate_slope()
def test_calculate_laplacian(self):
del2z = self.dem._calculate_lapalacian()
... | import unittest
import numpy as np
class CalculationMethodsTestCase(unittest.TestCase):
def setUp(self):
self.dem = DEMGrid()
def test_calculate_slope(self):
sx, sy = self.dem._calculate_slope()
def test_calculate_laplacian(self):
del2z = self.dem._calculate_lapalacian()
... | Remove redundant case from padding test | Remove redundant case from padding test
| Python | mit | stgl/scarplet,rmsare/scarplet | ---
+++
@@ -16,17 +16,6 @@
del2z = self.dem._calculate_lapalacian(alpha)
def test_pad_boundary(self):
- dx = 4
- dy = 4
- grid = self.dem._griddata
-
- pad_x = np.zeros((self.ny, dx/2))
- pad_y = np.zeros((self.nx + dx, dy/2))
- padgrid = np.vstack([pad_y, np.... |
d9938a50429db16ce60d905bca9844073fe2b0fa | this_app/forms.py | this_app/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.validators import Required, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[Required(), Email(), Length(1, 32)])
username = StringField(... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="Invalid email f... | Use DataRequired to validate form | Use DataRequired to validate form
| Python | mit | borenho/flask-bucketlist,borenho/flask-bucketlist | ---
+++
@@ -1,10 +1,17 @@
from flask_wtf import FlaskForm
-from wtforms import StringField, PasswordField
-from wtforms.validators import Required, Length, Email
+from wtforms import StringField, PasswordField, BooleanField
+from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):... |
5f2ab0dcaec5a7826ff0652e7c052971083a8398 | openid/test/datadriven.py | openid/test/datadriven.py | import unittest
class DataDrivenTestCase(unittest.TestCase):
cases = []
@classmethod
def generateCases(cls):
return cls.cases
@classmethod
def loadTests(cls):
tests = []
for case in cls.generateCases():
if isinstance(case, tuple):
test = cls(*c... | import unittest
class DataDrivenTestCase(unittest.TestCase):
cases = []
@classmethod
def generateCases(cls):
return cls.cases
@classmethod
def loadTests(cls):
tests = []
for case in cls.generateCases():
if isinstance(case, tuple):
test = cls(*c... | Replace ad-hoc pain with builtin methods | Replace ad-hoc pain with builtin methods
| Python | apache-2.0 | moreati/python3-openid,isagalaev/sm-openid,moreati/python3-openid,moreati/python3-openid,necaris/python3-openid,misli/python3-openid,necaris/python3-openid,misli/python3-openid,misli/python3-openid | ---
+++
@@ -31,15 +31,7 @@
def loadTests(module_name):
loader = unittest.defaultTestLoader
- this_module = __import__(module_name, {}, {}, [None])
-
- tests = []
- for name in dir(this_module):
- obj = getattr(this_module, name)
- if isinstance(obj, unittest.TestCase):
- if h... |
82bd501f89d3a228c3de9a2f355266b374c35a54 | twork/assembly.py | twork/assembly.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zhang ZY<http://idupx.blogspot.com/>
#
# 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/L... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zhang ZY<http://idupx.blogspot.com/>
#
# 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/L... | Add current project path to the first position of sys.modules | Add current project path to the first position of sys.modules
| Python | apache-2.0 | bufferx/twork,bufferx/twork | ---
+++
@@ -25,7 +25,7 @@
PROJECT_PATH = os.path.realpath(os.path.join(CURRENT_PATH, '..'))
if PROJECT_PATH not in sys.path:
- sys.path.append(PROJECT_PATH)
+ sys.path.insert(0, PROJECT_PATH)
def main():
print 'CURRENT_PATH:', CURRENT_PATH |
847a66ed8eb19206ecc77904dd5db547284b905f | pip/runner.py | pip/runner.py | import sys
import os
def run():
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
## FIXME: this is kind of crude; if we could create a fake pip
## module, then exec into it and update pip.__path__ properly, we
## wouldn't have to update sys.path:
sys.path.insert(0, base)
impor... | import sys
import os
def run():
base = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
## FIXME: this is kind of crude; if we could create a fake pip
## module, then exec into it and update pip.__path__ properly, we
## wouldn't have to update sys.path:
sys.path.insert(0, base)
impor... | Make sure exit code is used in -E situation | Make sure exit code is used in -E situation
| Python | mit | mindw/pip,pjdelport/pip,patricklaw/pip,alquerci/pip,esc/pip,harrisonfeng/pip,haridsv/pip,prasaianooz/pip,habnabit/pip,ncoghlan/pip,blarghmatey/pip,h4ck3rm1k3/pip,msabramo/pip,Gabriel439/pip,alex/pip,xavfernandez/pip,zvezdan/pip,haridsv/pip,Ivoz/pip,cjerdonek/pip,yati-sagade/pip,harrisonfeng/pip,RonnyPfannschmidt/pip,al... | ---
+++
@@ -11,4 +11,6 @@
return pip.main()
if __name__ == '__main__':
- run()
+ exit = run()
+ if exit:
+ sys.exit(exit) |
2bbc289ce21365e18b04cb865328c494b75075fd | numpy/version.py | numpy/version.py | version='0.9.7'
import os
svn_version_file = os.path.join(os.path.dirname(__file__),
'core','__svn_version__.py')
if os.path.isfile(svn_version_file):
import imp
svn = imp.load_module('numpy.core.__svn_version__',
open(svn_version_file),
... | version='0.9.9'
import os
svn_version_file = os.path.join(os.path.dirname(__file__),
'core','__svn_version__.py')
if os.path.isfile(svn_version_file):
import imp
svn = imp.load_module('numpy.core.__svn_version__',
open(svn_version_file),
... | Update head revision to 0.9.9 | Update head revision to 0.9.9
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@2524 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,illume/numpy3k,Ademan/NumPy-GSoC,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,Ademan/NumPy-GSoC,efiring/numpy-work,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,chadnetzer/numpy... | ---
+++
@@ -1,4 +1,4 @@
-version='0.9.7'
+version='0.9.9'
import os
svn_version_file = os.path.join(os.path.dirname(__file__), |
7a49e7c4344f7d78a84644ade5ca1c3251065f4a | salt/grains/ssds.py | salt/grains/ssds.py | # -*- coding: utf-8 -*-
'''
Detect SSDs
'''
import os
import salt.utils
import logging
log = logging.getLogger(__name__)
def ssds():
'''
Return list of disk devices that are SSD (non-rotational)
'''
SSDs = []
for subdir, dirs, files in os.walk('/sys/block'):
for dir in dirs:
... | # -*- coding: utf-8 -*-
'''
Detect SSDs
'''
# Import python libs
import glob
import salt.utils
import logging
log = logging.getLogger(__name__)
def ssds():
'''
Return list of disk devices that are SSD (non-rotational)
'''
ssd_devices = []
for entry in glob.glob('/sys/block/*/queue/rotational... | Use `glob.glob` instead of `os.walk` | Use `glob.glob` instead of `os.walk`
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -2,33 +2,29 @@
'''
Detect SSDs
'''
-import os
+
+# Import python libs
+import glob
import salt.utils
import logging
log = logging.getLogger(__name__)
+
def ssds():
'''
Return list of disk devices that are SSD (non-rotational)
'''
-
- SSDs = []
- for subdir, dirs, files i... |
89d8ee0b91c9fd579dcf965e9e07f18954625c72 | xero/api.py | xero/api.py | from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
u'Payments', u'TaxRates', u'TrackingCategories')
def __init__... | from .manager import Manager
class Xero(object):
"""An ORM-like interface to the Xero API"""
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
u'Payments', u'TaxRates', u'TrackingCategories', u'ManualJournals'... | Add support for manual journals | Add support for manual journals
| Python | bsd-3-clause | wegotpop/pyxero,jarekwg/pyxero,jaymcconnell/pyxero,opendesk/pyxero,thisismyrobot/pyxero,freakboy3742/pyxero,MJMortimer/pyxero,unomena/pyxero,schinckel/pyxero,unomena/pyxeropos,jacobg/pyxero,direvus/pyxero | ---
+++
@@ -6,7 +6,7 @@
OBJECT_LIST = (u'Contacts', u'Accounts', u'CreditNotes',
u'Currencies', u'Invoices', u'Items', u'Organisation',
- u'Payments', u'TaxRates', u'TrackingCategories')
+ u'Payments', u'TaxRates', u'TrackingCategories', u'ManualJournals'... |
fb9591c4a2801bfe5f5380c3e33aa44a25db3591 | customforms/models.py | customforms/models.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
class Meta:
ordering = ('title', )
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.db import models
class Form(models.Model):
title = models.CharField(_("Title"), max_length=255)
def __unicode__(self):
return u'%s' % self.title
... | Add absolute URLs to form and question admin | Add absolute URLs to form and question admin
| Python | apache-2.0 | cschwede/django-customforms | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
+from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.db import models
@@ -14,6 +15,8 @@
class Meta:
ordering = ('title', )
+ def get_absolute_url(self):
+ return ... |
d6ff777c7fb3f645c021da1319bb5d78d13aa9db | meshnet/interface.py | meshnet/interface.py | import serial
import struct
from siphashc import siphash
def _hash(key: str, sender: int, receiver: int, msg_type: int, data: bytes):
packed_data = struct.pack(">h>hBs", sender, receiver, msg_type, data)
return struct.pack("Q", siphash(key, packed_data))
class SerialMessage(object):
def __init__(self):
... | import serial
import struct
from siphashc import siphash
def _hash(key: bytes, sender: int, receiver: int, msg_type: int, data: bytes):
packed_data = struct.pack(">hhB", sender, receiver, msg_type) + data
return struct.pack(">Q", siphash(key, packed_data))
class SerialMessage(object):
def __init__(self)... | Fix python siphashing to match c implementation | Fix python siphashing to match c implementation
Signed-off-by: Jan Losinski <577c4104c61edf9f052c616c0c23e67bef4a9955@wh2.tu-dresden.de>
| Python | bsd-3-clause | janLo/automation_mesh,janLo/automation_mesh,janLo/automation_mesh | ---
+++
@@ -2,9 +2,10 @@
import struct
from siphashc import siphash
-def _hash(key: str, sender: int, receiver: int, msg_type: int, data: bytes):
- packed_data = struct.pack(">h>hBs", sender, receiver, msg_type, data)
- return struct.pack("Q", siphash(key, packed_data))
+
+def _hash(key: bytes, sender: int,... |
b2bab786c4af3dcca7d35b1e6ecff8699e542ec4 | pytest_girder/pytest_girder/plugin.py | pytest_girder/pytest_girder/plugin.py | from .fixtures import * # noqa
def pytest_addoption(parser):
group = parser.getgroup('girder')
group.addoption('--mock-db', action='store_true', default=False,
help='Whether or not to mock the database using mongomock.')
group.addoption('--mongo-uri', action='store', default='mongodb:... | import os
from .fixtures import * # noqa
def pytest_configure(config):
"""
Create the necessary directories for coverage. This is necessary because neither coverage nor
pytest-cov have support for making the data_file directory before running.
"""
covPlugin = config.pluginmanager.get_plugin('_cov... | Add a pytest hook for creating the coverage data_file directory | Add a pytest hook for creating the coverage data_file directory
| Python | apache-2.0 | jbeezley/girder,jbeezley/girder,girder/girder,kotfic/girder,jbeezley/girder,data-exp-lab/girder,Xarthisius/girder,data-exp-lab/girder,girder/girder,RafaelPalomar/girder,jbeezley/girder,girder/girder,kotfic/girder,manthey/girder,kotfic/girder,girder/girder,RafaelPalomar/girder,Xarthisius/girder,RafaelPalomar/girder,Xart... | ---
+++
@@ -1,4 +1,22 @@
+import os
from .fixtures import * # noqa
+
+
+def pytest_configure(config):
+ """
+ Create the necessary directories for coverage. This is necessary because neither coverage nor
+ pytest-cov have support for making the data_file directory before running.
+ """
+ covPlugin = ... |
b1e6f3eacccb5e575ac47b6a40809f4671510672 | rest_flex_fields/utils.py | rest_flex_fields/utils.py | try:
# Python 3
from collections.abc import Iterable
string_types = (str,)
except ImportError:
# Python 2
from collections import Iterable
string_types = (str, unicode)
def is_expanded(request, key):
""" Examines request object to return boolean of whether
passed field is expanded.... | from collections.abc import Iterable
def is_expanded(request, key):
""" Examines request object to return boolean of whether
passed field is expanded.
"""
expand = request.query_params.get("expand", "")
expand_fields = []
for e in expand.split(","):
expand_fields.extend([e for e i... | Drop Python 2 support in split_level utility function | Drop Python 2 support in split_level utility function
| Python | mit | rsinger86/drf-flex-fields | ---
+++
@@ -1,11 +1,4 @@
-try:
- # Python 3
- from collections.abc import Iterable
- string_types = (str,)
-except ImportError:
- # Python 2
- from collections import Iterable
- string_types = (str, unicode)
+from collections.abc import Iterable
def is_expanded(request, key):
@@ -37,7 +30,7 @@
... |
cde48bca684e225b2f99be6637380f4ef3365f17 | dimod/package_info.py | dimod/package_info.py | __version__ = '1.0.0.dev3'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
| __version__ = '1.0.0.dev4'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.'
| Update version 1.0.0.dev3 -> 1.0.0.dev4 | Update version 1.0.0.dev3 -> 1.0.0.dev4 | Python | apache-2.0 | dwavesystems/dimod,dwavesystems/dimod | ---
+++
@@ -1,4 +1,4 @@
-__version__ = '1.0.0.dev3'
+__version__ = '1.0.0.dev4'
__author__ = 'D-Wave Systems Inc.'
__authoremail__ = 'acondello@dwavesys.com'
__description__ = 'A shared API for binary quadratic model samplers.' |
71ea6816eea95e8bf750563718b0dd39114a3c49 | pyramid_authsanity/sources.py | pyramid_authsanity/sources.py | from zope.interface import implementer
from .interfaces (
IAuthSourceService,
)
@implementer(IAuthSourceService)
class SessionAuthSource(object):
""" An authentication source that uses the current session """
vary = ()
value_key = 'sanity.value'
def __init__(self, context, request):
... | from webob.cookies (
SignedCookieProfile,
SignedSerializer,
)
from zope.interface import implementer
from .interfaces (
IAuthSourceService,
)
@implementer(IAuthSourceService)
class SessionAuthSource(object):
""" An authentication source that uses the current session """
... | Add a cookie based authentication source | Add a cookie based authentication source
| Python | isc | usingnamespace/pyramid_authsanity | ---
+++
@@ -1,3 +1,8 @@
+from webob.cookies (
+ SignedCookieProfile,
+ SignedSerializer,
+ )
+
from zope.interface import implementer
from .interfaces (
@@ -28,3 +33,56 @@
if value_key in self.session:
del self.session[value_key]
return []
+
+
+def CookieAuthSou... |
494f14a69d08e9bfd556fccc6b4e2319db129a38 | books/models.py | books/models.py | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
class Receipt(models.Model):
title = fields.CharField(max_length=255)
price = fields.DecimalField(max_digits=10, decimal_places=2)
user = models.ForeignKey(User)
def __str__(self):
ret... | from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
from django.utils import timezone
class Receipt(models.Model):
title = fields.CharField(max_length=255)
price = fields.DecimalField(max_digits=10, decimal_places=2)
created = fields.DateTimeField(a... | Add created and modified fields to Receipt | Add created and modified fields to Receipt
| Python | mit | trimailov/finance,trimailov/finance,trimailov/finance | ---
+++
@@ -1,11 +1,14 @@
from django.contrib.auth.models import User
from django.db import models
from django.db.models import fields
+from django.utils import timezone
class Receipt(models.Model):
title = fields.CharField(max_length=255)
price = fields.DecimalField(max_digits=10, decimal_places=2)... |
b1547647deec6c1edf54c497fa4ed20235ea6902 | pymodels/middlelayer/devices/__init__.py | pymodels/middlelayer/devices/__init__.py | from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import HVPS
from .egun import Filament
| from .dcct import DCCT
from .li_llrf import LiLLRF
from .rf import RF
from .sofb import SOFB
from .kicker import Kicker
from .septum import Septum
from .screen import Screen
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
from .egun import Bias
from .egun import Filament
from .egun import HVPS
| Add missing egun.bias in init | ENH: Add missing egun.bias in init
| Python | mit | lnls-fac/sirius | ---
+++
@@ -8,5 +8,6 @@
from .bpm import BPM
from .ict import ICT
from .ict import TranspEff
+from .egun import Bias
+from .egun import Filament
from .egun import HVPS
-from .egun import Filament |
5856e4daaf141e5bf9cdef438378a3757297f9c0 | recipe_scrapers/wholefoods.py | recipe_scrapers/wholefoods.py | from ._abstract import AbstractScraper
class WholeFoods(AbstractScraper):
@classmethod
def host(self, domain="com"):
return f"www.wholefoodsmarket.{domain}"
| from ._abstract import AbstractScraper
class WholeFoods(AbstractScraper):
@classmethod
def host(self, domain="com"):
return f"www.wholefoodsmarket.{domain}"
def title(self):
return self.schema.title()
def total_time(self):
return self.schema.total_time()
def yields(self)... | Add wrapper methods for clarity. | Add wrapper methods for clarity.
| Python | mit | hhursev/recipe-scraper | ---
+++
@@ -5,3 +5,24 @@
@classmethod
def host(self, domain="com"):
return f"www.wholefoodsmarket.{domain}"
+
+ def title(self):
+ return self.schema.title()
+
+ def total_time(self):
+ return self.schema.total_time()
+
+ def yields(self):
+ return self.schema.yields()... |
b4e8dd76e3095941c9837151b263365f08426ea1 | WEIPDCRM/styles/DefaultStyle/views/chart.py | WEIPDCRM/styles/DefaultStyle/views/chart.py | # coding=utf-8
"""
DCRM - Darwin Cydia Repository Manager
Copyright (C) 2017 WU Zheng <i.82@me.com> & 0xJacky <jacky-943572677@qq.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either ... | # coding=utf-8
"""
DCRM - Darwin Cydia Repository Manager
Copyright (C) 2017 WU Zheng <i.82@me.com> & 0xJacky <jacky-943572677@qq.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either ... | Fix privileges of package frontend. | Fix privileges of package frontend.
| Python | agpl-3.0 | 82Flex/DCRM,82Flex/DCRM,82Flex/DCRM,82Flex/DCRM | ---
+++
@@ -29,7 +29,7 @@
class ChartView(ListView):
model = Package
context_object_name = 'package_list'
- ordering = '-download_times'
+ ordering = '-download_count'
template_name = 'frontend/chart.html'
def get_queryset(self): |
5f42f76ffd11e82d51a334b91d64723388ca4a0d | newswall/providers/feed.py | newswall/providers/feed.py | from datetime import datetime
import feedparser
import time
from newswall.providers.base import ProviderBase
class Provider(ProviderBase):
def update(self):
feed = feedparser.parse(self.config['source'])
for entry in feed['entries']:
self.create_story(entry.link,
titl... | """
RSS Feed Provider
=================
Required configuration keys::
{
"provider": "newswall.providers.feed",
"source": "http://twitter.com/statuses/user_timeline/feinheit.rss"
}
"""
from datetime import datetime
import feedparser
import time
from newswall.providers.base import ProviderBase
class ... | Add RSS Feed Provider docs | Add RSS Feed Provider docs
| Python | bsd-3-clause | michaelkuty/django-newswall,registerguard/django-newswall,matthiask/django-newswall,HerraLampila/django-newswall,registerguard/django-newswall,HerraLampila/django-newswall,michaelkuty/django-newswall,matthiask/django-newswall | ---
+++
@@ -1,3 +1,14 @@
+"""
+RSS Feed Provider
+=================
+
+Required configuration keys::
+
+ {
+ "provider": "newswall.providers.feed",
+ "source": "http://twitter.com/statuses/user_timeline/feinheit.rss"
+ }
+"""
from datetime import datetime
import feedparser
import time |
931e2d1e8ba3fd6b129a6d74e3a1ad9984c1938a | benchmarks/benchmarks/bench_random.py | benchmarks/benchmarks/bench_random.py | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = name.split()
name = items.pop(... | from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
from numpy.lib import NumpyVersion
class Random(Benchmark):
params = ['normal', 'uniform', 'weibull 1', 'binomial 10 0.5',
'poisson 10']
def setup(self, name):
items = nam... | Add benchmark tests for numpy.random.randint. | ENH: Add benchmark tests for numpy.random.randint.
This add benchmarks randint. There is one set of benchmarks for the
default dtype, 'l', that can be tracked back, and another set for the
new dtypes 'bool', 'uint8', 'uint16', 'uint32', and 'uint64'.
| Python | bsd-3-clause | shoyer/numpy,Dapid/numpy,jakirkham/numpy,WarrenWeckesser/numpy,chatcannon/numpy,WarrenWeckesser/numpy,b-carter/numpy,anntzer/numpy,ssanderson/numpy,simongibbons/numpy,nbeaver/numpy,SiccarPoint/numpy,numpy/numpy,Eric89GXL/numpy,kiwifb/numpy,seberg/numpy,rgommers/numpy,ESSS/numpy,shoyer/numpy,anntzer/numpy,utke1/numpy,dw... | ---
+++
@@ -3,6 +3,7 @@
from .common import Benchmark
import numpy as np
+from numpy.lib import NumpyVersion
class Random(Benchmark):
@@ -27,3 +28,40 @@
def time_100000(self):
np.random.shuffle(self.a)
+
+
+class Randint(Benchmark):
+
+ def time_randint_fast(self):
+ """Compare to u... |
ca8e15d50b816c29fc2a0df27d0266826e38b5b8 | cellcounter/statistics/serializers.py | cellcounter/statistics/serializers.py | from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
| from rest_framework.serializers import ModelSerializer
from .models import CountInstance
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
fields = ('count_total',)
| Update serializer to deal with new model | Update serializer to deal with new model
| Python | mit | cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter | ---
+++
@@ -5,3 +5,4 @@
class CountInstanceSerializer(ModelSerializer):
class Meta:
model = CountInstance
+ fields = ('count_total',) |
6f4758b39c257dcabcabc6405cf400e8f6a358ea | cpt/__init__.py | cpt/__init__.py |
__version__ = '0.35.0-dev'
def get_client_version():
from conans.model.version import Version
from conans import __version__ as client_version
from os import getenv
# It is a mess comparing dev versions, lets assume that the -dev is the further release
return Version(client_version.replace("-dev"... |
__version__ = '0.36.0-dev'
def get_client_version():
from conans.model.version import Version
from conans import __version__ as client_version
from os import getenv
# It is a mess comparing dev versions, lets assume that the -dev is the further release
return Version(client_version.replace("-dev"... | Update develop version to 0.36.0 | Update develop version to 0.36.0
Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>
| Python | mit | conan-io/conan-package-tools | ---
+++
@@ -1,5 +1,5 @@
-__version__ = '0.35.0-dev'
+__version__ = '0.36.0-dev'
def get_client_version(): |
3245946ff25889149dc60cf6b1364bd09c953809 | faas/puzzleboard-pop/puzzleboard_pop.py | faas/puzzleboard-pop/puzzleboard_pop.py | import json
from datetime import datetime
import requests
from .model.puzzleboard import pop_puzzleboard
class HuntwordsPuzzleBoardPopCommand(object):
'''Command class that processes puzzleboard-pop message'''
def run(self, jreq):
'''Command that processes puzzleboard-pop message'''
req = ... | import json
from datetime import datetime
import requests
from .model.puzzleboard import pop_puzzleboard
class HuntwordsPuzzleBoardPopCommand(object):
'''Command class that processes puzzleboard-pop message'''
def run(self, jreq):
'''Command that processes puzzleboard-pop message'''
req = ... | Change url from relative to internal service endpoint | Change url from relative to internal service endpoint
| Python | mit | klmcwhirter/huntwords,klmcwhirter/huntwords,klmcwhirter/huntwords,klmcwhirter/huntwords | ---
+++
@@ -32,7 +32,8 @@
def send_consumed(pboard):
'''Send async request to generate a new copy'''
- url = '/async-function/puzzleboard-consumed'
+ url = 'http://puzzleboard-consumed.openfaas-fn:8080'
+
data = f'{{"puzzle": "{pboard.puzzle.name}" }}'
requests.post(url, data) |
608dc0db688be1dabe3c6ba7647807f6697fcefe | tools/misc/python/test-data-in-out.py | tools/misc/python/test-data-in-out.py | # TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# OUTPUT OPTIONAL missing_output.txt
import shutil
shutil.copyfile('input', 'output')
| # TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.)
# INPUT input TYPE GENERIC
# OUTPUT output
# OUTPUT OPTIONAL missing_output.txt
# IMAGE chipster-tools-python
import shutil
shutil.copyfile('input', 'output')
| Test image definition in SADL | Test image definition in SADL
| Python | mit | chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools | ---
+++
@@ -2,6 +2,7 @@
# INPUT input TYPE GENERIC
# OUTPUT output
# OUTPUT OPTIONAL missing_output.txt
+# IMAGE chipster-tools-python
import shutil
|
5548e32a32bd1cd5951ce50e74c0fad944a1cf04 | ideascube/conf/idb_col_llavedelsaber.py | ideascube/conf/idb_col_llavedelsaber.py | """Configuration for Llave Del Saber, Colombia"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
LANGUAGE_CODE = 'es'
DOMAIN = 'bibliotecamovil.lan'
ALLOWED_HOSTS = ['.bibliotecamovil.lan', 'localhost']
USER_FORM_FIELDS = USER_FORM_FIELDS + (
(_('Personal informations'), ['... | """Configuration for Llave Del Saber, Colombia"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
LANGUAGE_CODE = 'es'
DOMAIN = 'bibliotecamovil.lan'
ALLOWED_HOSTS = ['.bibliotecamovil.lan', 'localhost']
USER_FORM_FIELDS = USER_FORM_FIELDS + (
(_('Personal informations'), ['... | Stop using the extra field for Colombia | Stop using the extra field for Colombia
After discussion, this is not something we will have in Ideascube.
Fixes #609
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | ---
+++
@@ -7,7 +7,5 @@
ALLOWED_HOSTS = ['.bibliotecamovil.lan', 'localhost']
USER_FORM_FIELDS = USER_FORM_FIELDS + (
- (_('Personal informations'), ['extra', 'disabilities']),
+ (_('Personal informations'), ['disabilities']),
)
-
-USER_EXTRA_FIELD_LABEL = 'Etnicidad' |
c1b433e5ed4c06b956b4d27f6da4e8b1dab54aaf | services/cloudwatch/sample.py | services/cloudwatch/sample.py | '''
===================================
Boto 3 - CloudWatch Service Example
===================================
This application implements the CloudWatch service that lets you gets
information from Amazon Cloud Watch. See the README for more details.
'''
import boto3
'''
Define your AWS credentials:
'''
AWS_ACCESS_KE... | '''
===================================
Boto 3 - CloudWatch Service Example
===================================
This application implements the CloudWatch service that lets you gets
information from Amazon Cloud Watch. See the README for more details.
'''
import boto3
'''
Define your AWS credentials:
'''
AWS_ACCESS_KE... | Fix issue in cloudwacth service credentials | Fix issue in cloudwacth service credentials
| Python | mit | rolandovillca/aws_samples_boto3_sdk | ---
+++
@@ -10,8 +10,8 @@
'''
Define your AWS credentials:
'''
-AWS_ACCESS_KEY_ID = 'AKIAJM7BQ4WBJJSVU2JQ'
-AWS_SECRET_ACCESS_KEY = 'Fq9GmwWEsvbcdHuh4McD+ZUmfowPKrnzFmhczV2U'
+AWS_ACCESS_KEY_ID = '<YOUR ACCESS KEY ID>'
+AWS_SECRET_ACCESS_KEY = '<YOUR SECRET ACCESS KEY>'
'''
Connection to AWS. |
a05a05f24c29dcf039e02b55c18c476dc69757df | shell_manager/problem_repo.py | shell_manager/problem_repo.py | """
Problem repository management for the shell manager.
"""
import spur, gzip
from shutil import copy2
from os.path import join
def local_update(repo_path, deb_paths=[]):
"""
Updates a local deb repository by copying debs and running scanpackages.
Args:
repo_path: the path to the local reposito... | """
Problem repository management for the shell manager.
"""
import spur, gzip
from shutil import copy2
from os.path import join
def update_repo(args):
"""
Main entrypoint for repo update operations.
"""
if args.repo_type == "local":
local_update(args.repository, args.package_paths)
else... | Update repo entrypoint and remote_update stub. | Update repo entrypoint and remote_update stub.
| Python | mit | RitwikGupta/picoCTF-shell-manager,cganas/picoCTF-shell-manager,RitwikGupta/picoCTF-shell-manager,cganas/picoCTF-shell-manager,picoCTF/picoCTF-shell-manager,cganas/picoCTF-shell-manager,cganas/picoCTF-shell-manager,RitwikGupta/picoCTF-shell-manager,picoCTF/picoCTF-shell-manager,picoCTF/picoCTF-shell-manager,picoCTF/pico... | ---
+++
@@ -6,6 +6,27 @@
from shutil import copy2
from os.path import join
+
+def update_repo(args):
+ """
+ Main entrypoint for repo update operations.
+ """
+
+ if args.repo_type == "local":
+ local_update(args.repository, args.package_paths)
+ else:
+ remote_update(args.repository,... |
6f7dba3beccca655b84879ccd0f3071d15536b2f | test/utils.py | test/utils.py | # coding: utf-8
import string
import random
def generate_string(str_len=6, src=string.ascii_lowercase):
return "".join(random.choice(src) for x in xrange(str_len))
def lorem_ipsum():
words_count = random.randint(20, 50)
lorem = list([])
for i in xrange(words_count):
word_length = random.randin... | # coding: utf-8
import string
import random
def generate_string(str_len=6, src=string.ascii_lowercase):
return "".join(random.choice(src) for x in xrange(str_len))
def lorem_ipsum(words_count=30):
lorem = list([])
for i in xrange(words_count):
word_length = random.randint(4, 8)
lorem.app... | Add word_count parameter for lorem_ipsum generator | Add word_count parameter for lorem_ipsum generator
| Python | mit | sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda | ---
+++
@@ -2,11 +2,12 @@
import string
import random
+
def generate_string(str_len=6, src=string.ascii_lowercase):
return "".join(random.choice(src) for x in xrange(str_len))
-def lorem_ipsum():
- words_count = random.randint(20, 50)
+
+def lorem_ipsum(words_count=30):
lorem = list([])
for i... |
d80f7a89b5bc23802ad5ec9bb8cc6ad523976718 | test_gitnl.py | test_gitnl.py | from __future__ import print_function, division, absolute_import
import unittest
import gitnl
class GitnlTestCase(unittest.TestCase):
"""Tests from 'gitnl.py'."""
def test_push_remotename_branchfrom(self):
desired = 'push remotename branchfrom'
actual = gitnl.parse_to_git('push my branch bra... | from __future__ import print_function, division, absolute_import
import unittest
import gitnl
class GitnlTestCase(unittest.TestCase):
"""Tests from 'gitnl.py'."""
def test_push_remotename_branchfrom(self):
desired = 'push remotename branchfrom'
actual = gitnl.parse_to_git('push my branch bra... | Add rename branch locally test | Add rename branch locally test
| Python | mit | eteq/gitnl,eteq/gitnl | ---
+++
@@ -12,5 +12,10 @@
actual = gitnl.parse_to_git('push my branch branchfrom to a remote called remotename')
self.assertEqual(actual, desired)
+ def test_rename_branch(self):
+ desired = 'branch -m old_branch new_branch'
+ actual = gitnl.parse_to_git('branch rename branch old... |
fb213097e838ddfa40d9f71f1705d7af661cfbdf | tests/unit.py | tests/unit.py | # -*- coding: latin-1 -*-
import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(t... | # -*- coding: latin-1 -*-
import unittest
from github2.issues import Issue
from github2.client import Github
class ReprTests(unittest.TestCase):
"""__repr__ must return strings, not unicode objects."""
def test_issue(self):
"""Issues can have non-ASCII characters in the title."""
i = Issue(t... | Allow tests to be run with Python <2.6. | Allow tests to be run with Python <2.6.
| Python | bsd-3-clause | ask/python-github2 | ---
+++
@@ -30,6 +30,10 @@
start = datetime.datetime.now()
client.users.show('mojombo')
end = datetime.datetime.now()
- self.assertGreaterEqual((end - start).total_seconds(), 2.0,
+
+ delta = end - start
+ delta_seconds = delta.days * 24 * 60 * 60 + delta.seconds
+
+ ... |
d19fa3b085d691780bbdc7b8e5edf9e8b53906e6 | todo/views.py | todo/views.py | from todo import app
from flask import jsonify, request, url_for
from flask import json
from todo.database import db_session
from todo.models import Entry
@app.route("/", methods=["GET", "POST", "DELETE"])
def index():
if request.method == "POST":
request_json = request.get_json()
entry = Entry(r... | from todo import app
from flask import jsonify, request, url_for
from flask import json
from todo.database import db_session
from todo.models import Entry
@app.route("/", methods=["GET", "POST", "DELETE"])
def index():
if request.method == "POST":
request_json = request.get_json()
entry = Entry(r... | Revert "Adding request context for proper url generation." | Revert "Adding request context for proper url generation."
This reverts commit 3fa12f6b36f7d1d0dd23cf28e79b7c54f1589fbc.
| Python | mit | Faerbit/todo-backend-flask | ---
+++
@@ -13,23 +13,22 @@
entry = Entry(request_json["title"])
db_session.add(entry)
db_session.commit()
- return jsonify(construct_dict(entry, request))
+ return jsonify(construct_dict(entry))
else:
if request.method == "DELETE":
Entry.query.delet... |
4be7f694220ee969683f07b982f8fcbe61971a04 | hairball/plugins/duplicate.py | hairball/plugins/duplicate.py | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, ... | """This module provides plugins for basic duplicate code detection."""
from hairball.plugins import HairballPlugin
class DuplicateScripts(HairballPlugin):
"""Plugin that keeps track of which scripts have been
used more than once whithin a project."""
def __init__(self):
super(DuplicateScripts, ... | Add comment to explain the length of the scripts taken into account in DuplicateScripts | Add comment to explain the length of the scripts taken into account in DuplicateScripts
| Python | bsd-2-clause | ucsb-cs-education/hairball,jemole/hairball,thsunmy/hairball,jemole/hairball,ucsb-cs-education/hairball,thsunmy/hairball | ---
+++
@@ -20,7 +20,8 @@
print duplicate
def analyze(self, scratch):
- """Run and return the results from the DuplicateChecks plugin."""
+ """Run and return the results from the DuplicateChecks plugin.
+ Only takes into account scripts with more than 3 blocks"""
... |
15996286496d913c25290362ba2dba2d349bd5f6 | imageManagerUtils/settings.py | imageManagerUtils/settings.py | # Copyright (c) 2017, MIT Licensed, Medicine Yeh
# This file helps to read settings from bash script into os.environ
import os
import sys
import subprocess
# This path is the location of the caller script
MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
# Set up the path to settings.sh
settings_path ... | # Copyright (c) 2017, MIT Licensed, Medicine Yeh
# This file helps to read settings from bash script into os.environ
import os
import sys
import subprocess
# This path is the location of the caller script
MAIN_SCRIPT_PATH = os.path.dirname(os.path.abspath(sys.argv[0]))
# Set up the path to settings.sh
settings_path ... | Fix bug of invoking /bin/sh on several OSs | Fix bug of invoking /bin/sh on several OSs
| Python | mit | snippits/qemu_image,snippits/qemu_image,snippits/qemu_image | ---
+++
@@ -14,7 +14,7 @@
print('Cannot find settings.sh in ' + MAIN_SCRIPT_PATH)
exit(1)
# This is a tricky way to read bash envs in the script
-env_str = subprocess.check_output('source {} && env'.format(settings_path), shell=True)
+env_str = subprocess.check_output('source {} && env'.format(settings_pat... |
c027e671d1a47d485755b748f2dffc202c704ff8 | goodreadsapi.py | goodreadsapi.py | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | #!/usr/bin/env python
import re
from xml.parsers.expat import ExpatError
import requests
import xmltodict
from settings import goodreads_api_key
def get_goodreads_ids(comment_msg):
# receives goodreads url
# returns the id using regex
regex = r'goodreads.com/book/show/(\d+)'
return set(re.findall(r... | Update goodreads API to `show original_publication_year` | Update goodreads API to `show original_publication_year`
| Python | mit | avinassh/Reddit-GoodReads-Bot | ---
+++
@@ -24,10 +24,16 @@
except (TypeError, KeyError, ExpatError):
return False
keys = ['title', 'average_rating', 'ratings_count', 'description',
- 'num_pages', 'publication_year']
+ 'num_pages']
book = {}
for k in keys:
book[k] = book_data.get(k)
+ t... |
59b015bb3e45497b7ec86bf1799e8442a30b65da | py/PMUtil.py | py/PMUtil.py | # PMUtil.py
# Phenotype microarray utility functions
#
# Author: Daniel A Cuevas
# Created on 27 Jan. 2015
# Updated on 27 Jan. 2015
from __future__ import absolute_import, division, print_function
import sys
import time
import datetime
def timeStamp():
'''Return time stamp'''
t = time.time()
fmt = '[%Y-... | # PMUtil.py
# Phenotype microarray utility functions
#
# Author: Daniel A Cuevas
# Created on 27 Jan 2015
# Updated on 20 Aug 2015
from __future__ import absolute_import, division, print_function
import sys
import time
import datetime
def timeStamp():
'''Return time stamp'''
t = time.time()
fmt = '[%Y-%m... | Exit method. - (New) Added exit method. | Exit method.
- (New) Added exit method.
| Python | mit | dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer,dacuevas/PMAnalyzer | ---
+++
@@ -2,8 +2,8 @@
# Phenotype microarray utility functions
#
# Author: Daniel A Cuevas
-# Created on 27 Jan. 2015
-# Updated on 27 Jan. 2015
+# Created on 27 Jan 2015
+# Updated on 20 Aug 2015
from __future__ import absolute_import, division, print_function
import sys
@@ -22,3 +22,8 @@
'''Print stat... |
a8976ff1c3bdc177ca72becf48c4278f963d2627 | gtr/__init__.py | gtr/__init__.py | __all__ = [
"gtr.services.funds.Funds",
"gtr.services.organisations.Organisations",
"gtr.services.persons.Persons",
"gtr.services.projects.Projects"
]
__version__ = "0.1.0"
from gtr.services.base import _Service
from gtr.services.funds import Funds
from gtr.services.organisations import Organisations
f... | __all__ = [
"gtr.services.funds.Funds",
"gtr.services.organisations.Organisations",
"gtr.services.persons.Persons",
"gtr.services.projects.Projects",
"gtr.services.publications.Publications"
]
__version__ = "0.1.0"
from gtr.services.base import _Service
from gtr.services.funds import Funds
from gtr... | Add Publications class to initialisation | Add Publications class to initialisation
| Python | apache-2.0 | nestauk/gtr | ---
+++
@@ -2,7 +2,8 @@
"gtr.services.funds.Funds",
"gtr.services.organisations.Organisations",
"gtr.services.persons.Persons",
- "gtr.services.projects.Projects"
+ "gtr.services.projects.Projects",
+ "gtr.services.publications.Publications"
]
__version__ = "0.1.0"
@@ -11,3 +12,4 @@
from ... |
63a26cbf76a3d0135f5b67dd10cc7f383ffa7ebf | helusers/jwt.py | helusers/jwt.py | from django.conf import settings
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication settings from allauth"""
defaults = ap... | from django.conf import settings
from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
from .user_utils import get_or_create_user
def patch_jwt_settings():
"""Patch rest_framework_jwt authentication sett... | Change authenticate_credentials method to raise an exception if the account is disabled | Change authenticate_credentials method to raise an exception if the account is disabled
| Python | bsd-2-clause | City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers | ---
+++
@@ -1,4 +1,5 @@
from django.conf import settings
+from rest_framework import exceptions
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings
@@ -29,6 +30,12 @@
class JWTAuthentication(JSONWebTokenAuthentication):
def authent... |
764f8d9d7818076555cde5fcad29f3052b523771 | company/autocomplete_light_registry.py | company/autocomplete_light_registry.py | import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['^name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| import autocomplete_light
from .models import Company
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete)
| Add more search fields to autocomplete | Add more search fields to autocomplete
| Python | bsd-3-clause | KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend,KlubJagiellonski/pola-backend | ---
+++
@@ -3,6 +3,6 @@
class CompanyAutocomplete(autocomplete_light.AutocompleteModelBase):
- search_fields = ['^name']
+ search_fields = ['name', 'official_name', 'common_name']
model = Company
autocomplete_light.register(CompanyAutocomplete) |
a06010fcb2f4424d085da1487a6666867a8cbf5b | dbaas/maintenance/admin/maintenance.py | dbaas/maintenance/admin/maintenance.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from ..models import Maintenance
from ..service.maintenance import MaintenanceService
class MaintenanceAdmin(admin.DjangoServicesAdmin):
service_class = MaintenanceService
search_fields = ("sche... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from ..models import Maintenance
from ..service.maintenance import MaintenanceService
from ..forms import MaintenanceForm
class MaintenanceAdmin(admin.DjangoServicesAdmin):
service_class = Maintenanc... | Remove add_view and add form for the hole admin | Remove add_view and add form for the hole admin
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | ---
+++
@@ -3,7 +3,7 @@
from django_services import admin
from ..models import Maintenance
from ..service.maintenance import MaintenanceService
-
+from ..forms import MaintenanceForm
class MaintenanceAdmin(admin.DjangoServicesAdmin):
@@ -14,7 +14,7 @@
"host_query","maximum_workers", "status", "celer... |
6f822cf46957d038588e7a71eb91f8ca9f9c95f1 | scaffolder/commands/install.py | scaffolder/commands/install.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder import get_minion_path
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand... | Use get_minion_path to get default dir. | InstallCommand: Use get_minion_path to get default dir.
| Python | mit | goliatone/minions | ---
+++
@@ -3,6 +3,7 @@
from optparse import make_option
from optparse import OptionParser
+from scaffolder import get_minion_path
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
@@ -12,7 +13,7 @@
"-t",
"--target",
de... |
95d9bb3a9500d80b5064c5fb4d5bd7b30406d1ae | conanfile.py | conanfile.py | from conans import ConanFile, CMake
class GrpccbConan(ConanFile):
name = "grpc_cb_core"
version = "0.2"
license = "Apache-2.0"
url = "https://github.com/jinq0123/grpc_cb_core"
description = "C++ gRPC core library with callback interface."
settings = "os", "compiler", "build_type", "arch"
op... | from conans import ConanFile, CMake
class GrpccbConan(ConanFile):
name = "grpc_cb_core"
version = "0.2"
license = "Apache-2.0"
url = "https://github.com/jinq0123/grpc_cb_core"
description = "C++ gRPC core library with callback interface."
settings = "os", "compiler", "build_type", "arch"
op... | Fix update remote to ConanCenter and grpc to highest buildable/supported version | Fix update remote to ConanCenter and grpc to highest buildable/supported version
| Python | apache-2.0 | jinq0123/grpc_cb_core,jinq0123/grpc_cb_core,jinq0123/grpc_cb_core | ---
+++
@@ -10,10 +10,9 @@
options = {"shared": [True, False]}
default_options = "shared=False"
- requires = "grpc/1.17.2@inexorgame/stable",
+ requires = "grpc/1.44.0@",
- generators = "cmake", "Premake" # A custom generator: PremakeGen/0.1@memsharded/testing
- build_requires = "Premak... |
c13a12e6355423d6756b8b514942596c31b0e3a9 | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.7"
class CMakeModuleCommonConan(ConanFile):
name = "cmake-module-common"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
url = "http://github.com/polysquare/cmake-module-com... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.7"
class CMakeModuleCommonConan(ConanFile):
name = "cmake-module-common"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
url = "http://github.com/polysquare/cmake-module-com... | Make cmake-unit, cmake-linter-cmake and style-linter-cmake normal deps | conan: Make cmake-unit, cmake-linter-cmake and style-linter-cmake normal deps
| Python | mit | polysquare/cmake-module-common | ---
+++
@@ -11,6 +11,9 @@
generators = "cmake"
url = "http://github.com/polysquare/cmake-module-common"
license = "MIT"
+ requires = ("cmake-unit/master@smspillaz/cmake-unit",
+ "cmake-linter-cmake/master@smspillaz/cmake-linter-cmake",
+ "style-linter-cmake/master@smspi... |
306e6939c5b369f4a4ef4bb4d16948dc1f027f53 | tests/test_initial_ismaster.py | tests/test_initial_ismaster.py | # Copyright 2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Update for PYTHON 985: MongoClient properties now block until connected. | Update for PYTHON 985: MongoClient properties now block until connected.
| Python | apache-2.0 | ajdavis/pymongo-mockup-tests | ---
+++
@@ -31,13 +31,13 @@
self.addCleanup(client.close)
# A single ismaster is enough for the client to be connected.
- self.assertIsNone(client.address)
- server.receives('ismaster').ok()
- wait_until(lambda: client.address is not None,
- 'update address',... |
af5e90cb544e2e37819302f5750084fc17f7ee12 | make_example.py | make_example.py | #!/usr/bin/env python
import os
import sys
import yaml
import subprocess
class SDBUSPlus(object):
def __init__(self, path):
self.path = path
def __call__(self, *a, **kw):
args = [
os.path.join(self.path, 'sdbus++'),
'-t',
os.path.join(self.path, 'template... | #!/usr/bin/env python
import os
import sys
import yaml
import subprocess
if __name__ == '__main__':
genfiles = {
'server-cpp': lambda x: '%s.cpp' % x,
'server-header': lambda x: os.path.join(
os.path.join(*x.split('.')), 'server.hpp')
}
with open(os.path.join('example', 'inter... | Remove sdbus++ template search workaround | Remove sdbus++ template search workaround
sdbus++ was fixed upstream to find its templates automatically.
Change-Id: I29020b9d1ea4ae8baaca5fe869625a3d96cd6eaf
Signed-off-by: Brad Bishop <713d098c0be4c8fd2bf36a94cd08699466677ecd@fuzziesquirrel.com>
| Python | apache-2.0 | openbmc/phosphor-inventory-manager,openbmc/phosphor-inventory-manager | ---
+++
@@ -6,31 +6,7 @@
import subprocess
-class SDBUSPlus(object):
- def __init__(self, path):
- self.path = path
-
- def __call__(self, *a, **kw):
- args = [
- os.path.join(self.path, 'sdbus++'),
- '-t',
- os.path.join(self.path, 'templates')
- ]
-
... |
1e07e9424a1ac69e1e660e6a6f1e58bba15472c1 | make_spectra.py | make_spectra.py | # -*- coding: utf-8 -*-
import halospectra as hs
import randspectra as rs
import sys
snapnum=sys.argv[1]
sim=sys.argv[2]
#base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/"
#savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3... | # -*- coding: utf-8 -*-
import halospectra as hs
import randspectra as rs
import sys
snapnum=sys.argv[1]
sim=sys.argv[2]
#base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/"
#savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3... | Implement saving and loading the observer tau | Implement saving and loading the observer tau
| Python | mit | sbird/vw_spectra | ---
+++
@@ -10,10 +10,10 @@
base="/home/spb/data/Cosmo/Cosmo"+str(sim)+"_V6/L25n256"
savedir="/home/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6/snapdir_"+str(snapnum).rjust(3,'0')
#halo = hs.HaloSpectra(snapnum, base,3, savefile="halo_spectra_DLA.hdf5", savedir=savedir)
-halo = rs.RandSpectra(snapnum, base,numlos=3000,... |
8316a60ba2887a511579e8cedb90b3a02fc1889a | dope/util.py | dope/util.py | from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
to_url = str
| from uuid import UUID
from werkzeug.routing import BaseConverter
class UUIDConverter(BaseConverter):
to_python = UUID
def to_url(self, obj):
return str(obj).replace('-', '')
| Drop dashes from download urls. | Drop dashes from download urls.
| Python | mit | mbr/dope,mbr/dope | ---
+++
@@ -5,4 +5,6 @@
class UUIDConverter(BaseConverter):
to_python = UUID
- to_url = str
+
+ def to_url(self, obj):
+ return str(obj).replace('-', '') |
9d46df1680e3d799971e73ec73043c2a6c0590ce | scripts/build_tar.py | scripts/build_tar.py | #! /usr/bin/python
import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
for ... | #! /usr/bin/python
import os
import subprocess
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
tarfile = os.path.join(root_dir, "src_pkg.tar")
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
if _... | Fix building tar in deployment | Fix building tar in deployment
| Python | bsd-3-clause | vmalloc/mailboxer,Infinidat/lanister,vmalloc/mailboxer,Infinidat/lanister,getslash/mailboxer,vmalloc/mailboxer,getslash/mailboxer,getslash/mailboxer | ---
+++
@@ -8,6 +8,8 @@
def _is_dir_newer(directory, filename):
file_mtime = os.stat(filename).st_mtime
for dirname, _, filenames in os.walk(directory):
+ if _is_file_newer(dirname, file_mtime):
+ return True
for filename in filenames:
if filename.endswith(".pyc"):
... |
a1390619619a364b9fab13504fb5c2464491d449 | Largest_Palindrome_Product.py | Largest_Palindrome_Product.py | # Find the largest palindrome made from the product of two n-digit numbers.
# Since the result could be very large, you should return the largest palindrome mod 1337.
# Example:
# Input: 2
# Output: 987
# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
# Note:
# The range of n is [1,8].
def largestPalindrome(n):
"... | # Find the largest palindrome made from the product of two n-digit numbers.
# Since the result could be very large, you should return the largest palindrome mod 1337.
# Example:
# Input: 2
# Output: 987
# Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
# Note:
# The range of n is [1,8].
from itertools import product... | Refactor Largest Palindrome Product for range of n is | Refactor Largest Palindrome Product for range of n is [1,8]
| Python | mit | Kunal57/Python_Algorithms | ---
+++
@@ -10,6 +10,8 @@
# Note:
# The range of n is [1,8].
+from itertools import product
+
def largestPalindrome(n):
"""
:type n: int
@@ -18,32 +20,24 @@
number = ""
for x in range(n):
number += "9"
- minNum = int(number[:-1])
number = int(number)
palindrome = 0
- for x in range(numbe... |
de4af7935c1c8d6751c5a71ad90dd5f531f7a1b0 | bin/trigger_upload.py | bin/trigger_upload.py | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | Fix the script function args | fedimg: Fix the script function args
Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
| Python | agpl-3.0 | fedora-infra/fedimg,fedora-infra/fedimg | ---
+++
@@ -14,7 +14,7 @@
log = logging.getLogger('fedmsg')
-def trigger_upload(compose_id, url, push_notifications):
+def trigger_upload(url, compose_id, push_notifications):
upload_pool = multiprocessing.pool.ThreadPool(processes=4)
fedimg.uploader.upload(upload_pool, [url],
... |
166bff52496bfb47c5a3a03585bd10fb449b8d77 | Lib/curses/__init__.py | Lib/curses/__init__.py | """curses
The main package for curses support for Python. Normally used by importing
the package, and perhaps a particular module inside it.
import curses
from curses import textpad
curses.initwin()
...
"""
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
| """curses
The main package for curses support for Python. Normally used by importing
the package, and perhaps a particular module inside it.
import curses
from curses import textpad
curses.initwin()
...
"""
__revision__ = "$Id$"
from _curses import *
from curses.wrapper import wrapper
# Some const... | Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings | Add wrapper for initscr() to copy the ACS_ and LINES,COLS bindings
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -15,4 +15,20 @@
from _curses import *
from curses.wrapper import wrapper
+# Some constants, most notably the ACS_* ones, are only added to the C
+# _curses module's dictionary after initscr() is called. (Some
+# versions of SGI's curses don't define values for those constants
+# until initscr() has be... |
17faea99343e37036b7ee35e5d3273f98a52dba9 | Python/tomviz/utils.py | Python/tomviz/utils.py | import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vtkarray.Association = dsa.ArrayAssociation.POINT
return... | import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
import vtk.util.numpy_support as np_s
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
# get the first
rawarray = do.PointData.GetScalars()
vtkarray = dsa.vtkDataArrayToVTKArray(rawarray, do)
vtkarray.Association =... | Fix numpy related errors on Mavericks. | Fix numpy related errors on Mavericks.
The problem was due to the fact that operations (like sqrt) can return a
float16 arrays which cannot be passed back to VTK directly. Added a
temporary conversion to float64. We should potentially handle this in
VTK.
| Python | bsd-3-clause | cryos/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,cryos/tomviz,Hovden/tomviz,Hovden/tomviz,yijiang1/tomviz,cjh1/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,yijiang1/tomviz,cjh1/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,thewtex/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,OpenChemistry/tomviz | ---
+++
@@ -1,5 +1,6 @@
import numpy as np
import vtk.numpy_interface.dataset_adapter as dsa
+import vtk.util.numpy_support as np_s
def get_scalars(dataobject):
do = dsa.WrapDataObject(dataobject)
@@ -15,5 +16,12 @@
oldscalars = do.PointData.GetScalars()
name = oldscalars.GetName()
del oldsca... |
98649d486b9e2eb2c83e594e73cf6bbaa29213e5 | examples/simple_server.py | examples/simple_server.py | import argparse
import math
from pythonosc import dispatcher
from pythonosc import osc_server
def print_volume_handler(args, volume):
print("[{0}] ~ {1}".format(args[0], volume))
def print_compute_handler(args, volume):
try:
print("[{0}] ~ {1}".format(args[0], args[1](volume)))
except ValueError: pass
if ... | import argparse
import math
from pythonosc import dispatcher
from pythonosc import osc_server
def print_volume_handler(args, volume):
print("[{0}] ~ {1}".format(args[0], volume))
def print_compute_handler(args, volume):
try:
print("[{0}] ~ {1}".format(args[0], args[1](volume)))
except ValueError: pass
if ... | Make the server example listen on 0.0.0.0 by default. | Make the server example listen on 0.0.0.0 by default. | Python | unlicense | mwicat/python2-osc,attwad/python-osc,ragnarula/python-osc,emlyn/python-osc | ---
+++
@@ -15,7 +15,7 @@
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--ip",
- default="127.0.0.1", help="The ip to listen on")
+ default="0.0.0.0", help="The ip to listen on")
parser.add_argument("--port",
type=int, default=5005, help="The port to lis... |
8b77e1e865d72720a602b7b7cc5912cb852d68cf | settings/dev.py | settings/dev.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
}
}
ACCOUNT_DEFAULT_H... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from .common import * # noqa
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ROOT_DIR, 'db.sqlite3'),
}
}
ACCOUNT_DEFAULT_H... | Revert back to original settings for Celery Broker | Revert back to original settings for Celery Broker
| Python | mit | pythonindia/junction,pythonindia/junction,pythonindia/junction,pythonindia/junction | ---
+++
@@ -26,5 +26,5 @@
INSTALLED_APPS += ('django_extensions',)
# settings for celery
-BROKER_URL = os.environ.get("BROKER_URL", "redis://127.0.0.1:6379/0")
-CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", 'redis://127.0.0.1:6379/0')
+BROKER_URL = os.environ.get("BROKER_URL", "redis://redis:637... |
e753038de039fd23f0d59bb0094f59fc73efe22b | flask_apscheduler/json.py | flask_apscheduler/json.py | import flask
import json
from datetime import datetime
from apscheduler.job import Job
from .utils import job_to_dict
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, Job):
return job_to_d... | import datetime
import flask
import json
from apscheduler.job import Job
from .utils import job_to_dict
loads = json.loads
def dumps(obj, indent=None):
return json.dumps(obj, indent=indent, cls=JSONEncoder)
def jsonify(data, status=None):
indent = None
if flask.current_app.config['JSONIFY_PRETTYPRINT_... | Set a custom JSON Encoder to serialize date class. | Set a custom JSON Encoder to serialize date class.
| Python | apache-2.0 | viniciuschiele/flask-apscheduler | ---
+++
@@ -1,20 +1,11 @@
+import datetime
import flask
import json
-from datetime import datetime
from apscheduler.job import Job
from .utils import job_to_dict
-
-class JSONEncoder(json.JSONEncoder):
- def default(self, obj):
- if isinstance(obj, datetime):
- return obj.isoformat()
-
- ... |
edcfe2b156af23943478bc86592b4c8d5dc07e10 | flask_mongoengine/json.py | flask_mongoengine/json.py | from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
from mongoengine import QuerySet
def _make_encoder(superclass):
class MongoEngineJSONEncoder(superclass):
'''
A JSONEncoder which provides serialization of MongoEngine
documents and quer... | from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
try:
from mongoengine.base import BaseQuerySet
except ImportError as ie: # support mongoengine < 0.7
from mongoengine.queryset import QuerySet as BaseQuerySet
def _make_encoder(superclass):
class MongoEn... | Support older versions of MongoEngine | Support older versions of MongoEngine
| Python | bsd-3-clause | gerasim13/flask-mongoengine-1,rochacbruno/flask-mongoengine,quokkaproject/flask-mongoengine,quokkaproject/flask-mongoengine,gerasim13/flask-mongoengine-1,losintikfos/flask-mongoengine,rochacbruno/flask-mongoengine,losintikfos/flask-mongoengine | ---
+++
@@ -1,19 +1,21 @@
from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
-from mongoengine import QuerySet
-
+try:
+ from mongoengine.base import BaseQuerySet
+except ImportError as ie: # support mongoengine < 0.7
+ from mongoengine.queryset import Que... |
3d7b5d61b7e985d409cd50c98d4bcbdc8ab9c723 | mailer.py | mailer.py | from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
@staticmethod
def send(message):
Mailer.MAILER.send(message)
@staticmethod
def start():
Mailer.MAILER.s... | from marrow.mailer import Mailer as MarrowMailer
from message import Message
import sys
import os
import pwd
import socket
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
DEFAULT_AUTHOR = pwd.getpwuid(os.getuid()).pw_name + '@' + socket.getfqdn()
@stat... | Use current user as email author | Use current user as email author
| Python | isc | 2mv/raapija | ---
+++
@@ -2,11 +2,15 @@
from message import Message
import sys
+import os
+import pwd
+import socket
class Mailer:
MAILER = MarrowMailer(dict(manager=dict(use='immediate'), transport=dict(use='sendmail')))
+ DEFAULT_AUTHOR = pwd.getpwuid(os.getuid()).pw_name + '@' + socket.getfqdn()
@staticmetho... |
65973802a3e68e23f9a903937ef94f8afa277013 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create documentation of DataSource Settings | : Create documentation of DataSource Settings
Task-Url: | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -18,7 +18,8 @@
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
-
-for db in dbs.splitlines().split('('):
+dbs = dbs.splitlines()
+print dbs
+for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
Adm... |
93f2ff45ff3d61487ed061ae3d1a65051c3d1799 | django/contrib/admin/__init__.py | django/contrib/admin/__init__.py | from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. T... | # ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInli... | Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. | Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.
git-svn-id: 554f83ef17aa7291f84efa897c1acfc5d0035373@14359 bcc190cf-cafb-0310-a4f2-bffc1f526a37
| Python | bsd-3-clause | svn2github/django,svn2github/django,svn2github/django | ---
+++
@@ -1,3 +1,6 @@
+# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
+# has been referenced in documentation.
+from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options im... |
445f244ddac6001b65f03d058a14178a19919eed | diamondash/config.py | diamondash/config.py | import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
for base in bases:
... | import yaml
from diamondash import utils
class ConfigError(Exception):
"""Raised when there is an error parsing a configuration"""
class ConfigMetaClass(type):
def __new__(mcs, name, bases, dict):
cls = type.__new__(mcs, name, bases, dict)
defaults = {}
for base in bases:
... | Allow Config to be initialised without any args | Allow Config to be initialised without any args
| Python | bsd-3-clause | praekelt/diamondash,praekelt/diamondash,praekelt/diamondash | ---
+++
@@ -26,8 +26,8 @@
__metaclass__ = ConfigMetaClass
DEFAULTS = {}
- def __init__(self, items):
- super(Config, self).__init__(self._parse(items))
+ def __init__(self, items=None):
+ super(Config, self).__init__(self._parse(items or {}))
@classmethod
def parse(cls, ite... |
bfcec696308ee8bfd226a54c17a7e15d49e2aed7 | var/spack/repos/builtin/packages/nextflow/package.py | var/spack/repos/builtin/packages/nextflow/package.py | from spack import *
from glob import glob
import os
class Nextflow(Package):
"""Data-driven computational pipelines"""
homepage = "http://www.nextflow.io"
version('0.20.1', '0e4e0e3eca1c2c97f9b4bffd944b923a',
url='https://github.com/nextflow-io/nextflow/releases/download/v0.20.1/nextflow',
... | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | Add standard header, use spack helpers | Add standard header, use spack helpers
Added the standard header (stolen from R).
Touched up the install to use set_executable rather than doing it
myself.
| Python | lgpl-2.1 | matthiasdiener/spack,mfherbst/spack,lgarren/spack,tmerrick1/spack,TheTimmy/spack,LLNL/spack,tmerrick1/spack,TheTimmy/spack,TheTimmy/spack,matthiasdiener/spack,LLNL/spack,iulian787/spack,matthiasdiener/spack,krafczyk/spack,tmerrick1/spack,EmreAtes/spack,TheTimmy/spack,tmerrick1/spack,iulian787/spack,matthiasdiener/spack... | ---
+++
@@ -1,6 +1,29 @@
+##############################################################################
+# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
+# Produced at the Lawrence Livermore National Laboratory.
+#
+# This file is part of Spack.
+# Created by Todd Gamblin, tgamblin@llnl.gov, Al... |
e81b1ce7536ce32e022fb3132f8468d2472b2e31 | atlas/prodtask/management/commands/extendopenended.py | atlas/prodtask/management/commands/extendopenended.py | from django.core.management.base import BaseCommand, CommandError
from atlas.prodtask.open_ended import check_open_ended
class Command(BaseCommand):
args = '<request_id, request_id>'
help = 'Extend open ended requests'
def handle(self, *args, **options):
if not args:
try:
... | from django.core.management.base import BaseCommand, CommandError
import time
from atlas.prodtask.open_ended import check_open_ended
class Command(BaseCommand):
args = '<request_id, request_id>'
help = 'Extend open ended requests'
def handle(self, *args, **options):
self.stdout.write('Start open ... | Improve logging of openended extension | Improve logging of openended extension
| Python | apache-2.0 | PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas,PanDAWMS/panda-bigmon-atlas | ---
+++
@@ -1,4 +1,5 @@
from django.core.management.base import BaseCommand, CommandError
+import time
from atlas.prodtask.open_ended import check_open_ended
@@ -7,10 +8,10 @@
help = 'Extend open ended requests'
def handle(self, *args, **options):
-
+ self.stdout.write('Start open ended at %s... |
6632157febfed7ce99fa1aaecb72393b0301d3aa | geotrek/authent/migrations/0003_auto_20181203_1518.py | geotrek/authent/migrations/0003_auto_20181203_1518.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from django.core.management import call_command
from django.conf import settings
def add_permissions(apps, schema_editor):
if 'geotrek.infrastructure' in settings.INSTALLED_APPS:
call_command('update_geotrek_... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('authent', '0002_auto_20181107_1620'),
]
operations = [
]
| Make empty migration authent 3 | Make empty migration authent 3
| Python | bsd-2-clause | makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek | ---
+++
@@ -2,38 +2,6 @@
from __future__ import unicode_literals
from django.db import migrations
-from django.core.management import call_command
-from django.conf import settings
-
-
-def add_permissions(apps, schema_editor):
- if 'geotrek.infrastructure' in settings.INSTALLED_APPS:
- call_command('up... |
0324d220872ef063cb39ce62264bd4835f260920 | test_project/urls.py | test_project/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from test_app.models import DummyModel, MushroomSpot
from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint
from mapentity.registry import registry
handler403 = 'mapentity.views.hand... | from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
from test_app.models import DummyModel, MushroomSpot
from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint
from mapentity.registry import registry
from django.contrib.auth import view... | Replace str into call in url | Replace str into call in url
| Python | bsd-3-clause | makinacorpus/django-mapentity,makinacorpus/django-mapentity,makinacorpus/django-mapentity | ---
+++
@@ -5,6 +5,7 @@
from test_app.models import DummyModel, MushroomSpot
from test_app.views import DummyDocumentOdt, DummyDocumentWeasyprint
from mapentity.registry import registry
+from django.contrib.auth import views as auth_views
handler403 = 'mapentity.views.handler403'
@@ -18,8 +19,8 @@
url(r'... |
a53612d5f276180d204378b9e4974fcd812f6a5b | tests/fake_camera.py | tests/fake_camera.py | from os import listdir
from os.path import isfile, join
class Camera(object):
def __init__(self, path):
self.files = [join(path, f) for f in listdir(path)]
self.files = sorted([f for f in self.files if isfile(f)])
self.current = 0
def reset(self):
self.current = 0
def ha... | # -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# ... | Add licence header in fake camera test file. | Add licence header in fake camera test file.
| Python | apache-2.0 | angus-ai/angus-sdk-python | ---
+++
@@ -1,3 +1,22 @@
+# -*- coding: utf-8 -*-
+
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the A... |
d1ea64d6645f60df38221cbd194c26dff9686dcd | scripts/utils.py | scripts/utils.py | import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
def __init__(self):
self._mod... | import sys
import hashlib
def e(s):
if type(s) == str:
return str
return s.encode('utf-8')
def d(s):
if type(s) == unicode:
return s
return unicode(s, 'utf-8')
def mkid(s):
return hashlib.sha1(e(s)).hexdigest()[:2*4]
class Logger(object):
def __init__(self):
self._mod... | Handle logging unicode messages in python2. | Handle logging unicode messages in python2.
Former-commit-id: 257d94eb71d5597ff52a18ec1530d73496901ef4 | Python | mit | guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt | ---
+++
@@ -19,6 +19,7 @@
self._mode = 'INFO'
def progress(self, message):
+ message = e(message)
if not sys.stderr.isatty():
return
@@ -28,6 +29,7 @@
self._mode = 'PROGRESS'
def info(self, message):
+ message = e(message)
if self._mode ==... |
84a99e9557a323e094c360e748c7d7042980fc59 | tests/test_sample.py | tests/test_sample.py | import unittest
from tip.algorithms.dummy import dummy_add
class TestDummyAdd(unittest.TestCase):
def test_lcm(self):
r = dummy_add(2, 2)
self.assertEqual(r, 4)
| import unittest
from tip.algorithms.dummy import dummy_add
class TestDummyAdd(unittest.TestCase):
def test_lcm(self):
r = dummy_add(2, 2)
self.assertEqual(r, 4)
| Test PEP8 integration into Atom | Test PEP8 integration into Atom
| Python | unlicense | davidgasquez/tip | ---
+++
@@ -3,6 +3,7 @@
class TestDummyAdd(unittest.TestCase):
+
def test_lcm(self):
r = dummy_add(2, 2)
self.assertEqual(r, 4) |
1c28341a4cd828de607d9cc4252f444844c0a892 | test/bibliopixel/util/udp_test.py | test/bibliopixel/util/udp_test.py | import contextlib, queue, time, unittest
from bibliopixel.util import udp
TEST_ADDRESS = '127.0.0.1', 5678
TIMEOUT = 0.2
@contextlib.contextmanager
def receive_udp(address, results):
receiver = udp.QueuedReceiver(address)
receiver.start()
yield
try:
while True:
results.append(r... | import contextlib, queue, time, unittest
from bibliopixel.util import udp
TEST_ADDRESS = '127.0.0.1', 5678
TIMEOUT = 0.3
@contextlib.contextmanager
def receive_udp(address, results):
receiver = udp.QueuedReceiver(address)
receiver.start()
yield
try:
while True:
results.append(r... | Tweak up timeout in UDP test | Tweak up timeout in UDP test
| Python | mit | rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel | ---
+++
@@ -3,7 +3,7 @@
from bibliopixel.util import udp
TEST_ADDRESS = '127.0.0.1', 5678
-TIMEOUT = 0.2
+TIMEOUT = 0.3
@contextlib.contextmanager |
a74e91613be376d6d71fb90c15cab689af661e37 | money_conversion/money.py | money_conversion/money.py | from currency_rates import rates
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
def to_currency(self, new_currency):
new_currency = new_c... | from currency_rates import rates
class Money(object):
def __init__(self, amount, currency):
self.amount = amount
self.currency = currency.upper()
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
def __getattr__(self, currency):
def convert():
... | Add __getattr__ method in order to be able to call non-defined methods | Add __getattr__ method in order to be able to call non-defined methods
| Python | mit | mdsrosa/money-conversion-py | ---
+++
@@ -10,11 +10,16 @@
def __repr__(self):
return "%.2f %s" % (self.amount, self.currency)
- def to_currency(self, new_currency):
- new_currency = new_currency.split('_')[1].upper()
+ def __getattr__(self, currency):
+ def convert():
+ return self.to_currency(curren... |
9a698d1428fbe0744c9dba3532b778569dbe1dd4 | server.py | server.py | import socket
import sys
class SimpleServer(object):
"""Simple server using the socket library"""
def __init__(self, blocking=False, connection_oriented=True):
"""
The constructor initializes socket specifying the blocking status and
if it must be a connection oriented socket.
... | """
A Simple Server class that allows to configure a socket in a very simple way.
It is for studying purposes only.
"""
import socket
import sys
__author__ = "Facundo Victor"
__license__ = "MIT"
__email__ = "facundovt@gmail.com"
class SimpleServer(object):
"""Simple server using the socket library"""
def ... | Add docstrings and author reference | Add docstrings and author reference
| Python | mit | facundovictor/non-blocking-socket-samples | ---
+++
@@ -1,5 +1,15 @@
+"""
+A Simple Server class that allows to configure a socket in a very simple way.
+It is for studying purposes only.
+"""
+
import socket
import sys
+
+
+__author__ = "Facundo Victor"
+__license__ = "MIT"
+__email__ = "facundovt@gmail.com"
class SimpleServer(object):
@@ -31,4 +41,6 @... |
5f501af61b416dae0e46236a8e1f9684dcc66e21 | python/decoder_test.py | python/decoder_test.py | import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(args['dataset'], 'edr')
v... | import argparse
import scanner
import numpy as np
import cv2
from decode import db
@db.loader('frame')
def load_frames(buf, metadata):
return np.frombuffer(buf, dtype=np.uint8) \
.reshape((metadata.height,metadata.width,3))
def extract_frames(args):
job = load_frames(args['dataset'], 'edr')
v... | Write out concatenated frame on decode test failure | Write out concatenated frame on decode test failure
| Python | apache-2.0 | scanner-research/scanner,scanner-research/scanner,scanner-research/scanner,scanner-research/scanner | ---
+++
@@ -22,10 +22,12 @@
_, video_frame = inp.read()
video_frame_num += 1
scanner_frame = cv2.cvtColor(buf, cv2.COLOR_RGB2BGR)
- frame_diff = (scanner_frame - video_frame).sum()
- if frame_diff != 0:
+ frame_diff = np.abs(scanner_frame... |
e2cba02550dfbe8628daf024a2a35c0dffb234e9 | python/cli/request.py | python/cli/request.py | import requests
import os
aport = os.environ.get('MYAPORT')
if aport is None:
aport = "80"
aport = "23456"
url1 = 'http://localhost:' + aport + '/'
url2 = 'http://localhost:' + aport + '/action/improvesimulateinvest'
url3 = 'http://localhost:' + aport + '/action/autosimulateinvest'
url4 = 'http://localhost:' + a... | import requests
import os
aport = os.environ.get('MYAPORT')
if aport is None:
aport = "80"
aport = "23456"
ahost = os.environ.get('MYAHOST')
if ahost is None:
ahost = "localhost"
url1 = 'http://' + ahost + ':' + aport + '/'
#headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
#hea... | Handle different environments, for automation (I4). | Handle different environments, for automation (I4).
| Python | agpl-3.0 | rroart/aether,rroart/aether,rroart/aether,rroart/aether,rroart/aether | ---
+++
@@ -4,13 +4,13 @@
aport = os.environ.get('MYAPORT')
if aport is None:
aport = "80"
+ aport = "23456"
-aport = "23456"
-
-url1 = 'http://localhost:' + aport + '/'
-url2 = 'http://localhost:' + aport + '/action/improvesimulateinvest'
-url3 = 'http://localhost:' + aport + '/action/autosimulateinvest'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.